Tuesday, February 7, 2012
Interview questions ASP.Net 4.0
Q. What is new with ASP.Net 4 WebForms ?
Ans. Some of the Features are:
. Ability to Set Metatags.
. More control over view state.
. Added and Updated browser definition files.
. ASP.Net Routing.
. The ability to Persist Selected rows in data Control.
. More control over rendered HTML in FormView and ListView Controls.
. Filtering Support for datasource Controls.
Q. What is machine.config file and how do you use it in ASP.Net 4.0?
Ans. Machine.Config file is found in the "CONFIG" subfolder of your .NET Framework install directory (c:\WINNT\Microsoft.NET\Framework\{Version Number}\CONFIG on Windows 2000 installations). It contains configuration settings for machine-wide assembly binding, built-in remoting channels, and ASP.NET.
In .the NET Framework 4.0, the major configuration elements(that use to be in web.config) have been moved to the machine.config file, and the applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty or to contain just the following lines.
Q. What is RedirectPermanent in ASP.Net 4.0?
Ans. In earlier Versions of .Net, Response.Redirect was used, which issues an HTTP 302 Found or temporary redirect response to the browser (meaning that asked resource is temporarily moved to other location) which inturn results in an extra HTTP round trip. ASP.NET 4.0 however, adds a new RedirectPermanent that Performs a permanent redirection from the requested URL to the specified URL. and returns 301 Moved Permanently responses.
e.g. RedirectPermanent("/newpath/foroldcontent.aspx");
Q. How will you specify what version of the framework your application is targeting?
Ans. In Asp.Net 4 a new element "targetFramework" of compilation tag (in Web.config file) lets you specify the framework version in the webconfig file
It only lets you target the .NET Framework 4.0 and later verisons.
Q. What is the use of MetaKeywords and MetaDescription properties.
Ans. MetaKeywords and MetaDescription are the new properties added to the Page class of ASP.NET 4.0 Web Forms. The two properties are used to set the keywords and description meta tags in your page.
For e.g.
You can set these properties at run time, which lets you get the content from a database or other source, and which lets you set the tags dynamically to describe what a particular page is for.
You can also set the Keywords and Description properties in the @ Page directive at the top of the Web Forms page markup like,
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Keywords="ASP,4.0,are keywords" Description="blah blah" %>
Q. What is Microsoft Ajax Library.
Ans. Microsoft Ajax Library is a client-only JavaScript library that is compatible with all modern browsers, including Internet Explorer, Google Chrome, Apple Safari, and Mozilla Firefox.Because the Microsoft Ajax Library is a client-only JavaScript library, you can use the library with both ASP.NET Web Forms and ASP.NET MVC applications. You can also create Ajax pages that consist only of HTML.
Q. What are the Changes in CheckBoxList and RadioButtonList Control ?
Ans. In ASP.NET 4, the CheckBoxList and RadioButtonList controls support two new values for the RepeatLayout property, OrderedList(The content is rendered as li elements within an ol element) and UnorderedList(The content is rendered as li elements within a ul element.)
For more info see : Specify Layout in CheckBoxList and RadioButtonList Control - ASP.Net 4
Q. Whats Application Warm-Up Module?
Ans. We can set-up a Warm-Up module for warming up your applications before they serve their first request.Instead of writing custom code, you specify the URLs of resources to execute before the Web application accepts requests from the network. This warm-up occurs during startup of the IIS service (if you configured the IIS application pool as AlwaysRunning) and when an IIS worker process recycles. During recycle, the old IIS worker process continues to execute requests until the newly spawned worker process is fully warmed up, so that applications experience no interruptions or other issues due to unprimed caches.
Monday, February 6, 2012
Html Raw of Asp.net MVC 3 with Razor view engine
HtmlString IHtmlString and HttpUtlity.HtmlEncode in ASP.NET 4 are fantastic features.
Saving Content in Database, retrieve it dynamically on Front end page that is absolutely nice.
HtmlHelper.Raw Method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
1: public IHtmlString Raw(2: string value 3: )
1: @{ var para = "<p>I am a parargraph</p>";}
2: @Html.Raw(para)Sunday, February 5, 2012
LinkedList(Of T) Class C#
What LinkedList class can do:
You can remove nodes and reinsert them, either in the same list or in another list, which results in no additional object allocated on the heap. LinkedList accepts null value.
Please note: LinkedList class doesn't support chaining, splitting, cycles or other features that can leave the list in inconsistent state. The list remains consistent on a signle thread. The Linkedlist supports multithread read.
Please see the following examples:
1: using System;
2: using System.Text;
3: using System.Collections.Generic;
4: 5: public class Example
6: {7: public static void Main()
8: {9: // Create the link list.
10: string[] words =
11: { "the", "fox", "jumped", "over", "the", "dog" };
12: LinkedList<string> sentence = new LinkedList<string>(words);
13: Display(sentence, "The linked list values:");
14: Console.WriteLine("sentence.Contains(\"jumped\") = {0}",
15: sentence.Contains("jumped"));
16: 17: // Add the word 'today' to the beginning of the linked list.
18: sentence.AddFirst("today");
19: Display(sentence, "Test 1: Add 'today' to beginning of the list:");
20: 21: // Move the first node to be the last node.
22: LinkedListNode<string> mark1 = sentence.First;
23: sentence.RemoveFirst(); 24: sentence.AddLast(mark1);25: Display(sentence, "Test 2: Move first node to be last node:");
26: 27: // Change the last node be 'yesterday'.
28: sentence.RemoveLast();29: sentence.AddLast("yesterday");
30: Display(sentence, "Test 3: Change the last node to 'yesterday':");
31: 32: // Move the last node to be the first node.
33: mark1 = sentence.Last; 34: sentence.RemoveLast(); 35: sentence.AddFirst(mark1);36: Display(sentence, "Test 4: Move last node to be first node:");
37: 38: 39: // Indicate, by using parentheisis, the last occurence of 'the'.
40: sentence.RemoveFirst();41: LinkedListNode<string> current = sentence.FindLast("the");
42: IndicateNode(current, "Test 5: Indicate last occurence of 'the':");
43: 44: // Add 'lazy' and 'old' after 'the' (the LinkedListNode named current).
45: sentence.AddAfter(current, "old");
46: sentence.AddAfter(current, "lazy");
47: IndicateNode(current, "Test 6: Add 'lazy' and 'old' after 'the':");
48: 49: // Indicate 'fox' node.
50: current = sentence.Find("fox");
51: IndicateNode(current, "Test 7: Indicate the 'fox' node:");
52: 53: // Add 'quick' and 'brown' before 'fox':
54: sentence.AddBefore(current, "quick");
55: sentence.AddBefore(current, "brown");
56: IndicateNode(current, "Test 8: Add 'quick' and 'brown' before 'fox':");
57: 58: // Keep a reference to the current node, 'fox',
59: // and to the previous node in the list. Indicate the 'dog' node.
60: mark1 = current;61: LinkedListNode<string> mark2 = current.Previous;
62: current = sentence.Find("dog");
63: IndicateNode(current, "Test 9: Indicate the 'dog' node:");
64: 65: // The AddBefore method throws an InvalidOperationException
66: // if you try to add a node that already belongs to a list.
67: Console.WriteLine("Test 10: Throw exception by adding node (fox) already in the list:");
68: try
69: { 70: sentence.AddBefore(current, mark1); 71: }72: catch (InvalidOperationException ex)
73: {74: Console.WriteLine("Exception message: {0}", ex.Message);
75: } 76: Console.WriteLine(); 77: 78: // Remove the node referred to by mark1, and then add it
79: // before the node referred to by current.
80: // Indicate the node referred to by current.
81: sentence.Remove(mark1); 82: sentence.AddBefore(current, mark1);83: IndicateNode(current, "Test 11: Move a referenced node (fox) before the current node (dog):");
84: 85: // Remove the node referred to by current.
86: sentence.Remove(current);87: IndicateNode(current, "Test 12: Remove current node (dog) and attempt to indicate it:");
88: 89: // Add the node after the node referred to by mark2.
90: sentence.AddAfter(mark2, current);91: IndicateNode(current, "Test 13: Add node removed in test 11 after a referenced node (brown):");
92: 93: // The Remove method finds and removes the
94: // first node that that has the specified value.
95: sentence.Remove("old");
96: Display(sentence, "Test 14: Remove node that has the value 'old':");
97: 98: // When the linked list is cast to ICollection(Of String),
99: // the Add method adds a node to the end of the list.
100: sentence.RemoveLast();101: ICollection<string> icoll = sentence;
102: icoll.Add("rhinoceros");
103: Display(sentence, "Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':");
104: 105: Console.WriteLine("Test 16: Copy the list to an array:");
106: // Create an array with the same number of
107: // elements as the inked list.
108: string[] sArray = new string[sentence.Count];
109: sentence.CopyTo(sArray, 0); 110: 111: foreach (string s in sArray)
112: { 113: Console.WriteLine(s); 114: } 115: 116: // Release all the nodes.
117: sentence.Clear(); 118: 119: Console.WriteLine();120: Console.WriteLine("Test 17: Clear linked list. Contains 'jumped' = {0}",
121: sentence.Contains("jumped"));
122: 123: Console.ReadLine(); 124: } 125: 126: private static void Display(LinkedList<string> words, string test)
127: { 128: Console.WriteLine(test);129: foreach (string word in words)
130: {131: Console.Write(word + " ");
132: } 133: Console.WriteLine(); 134: Console.WriteLine(); 135: } 136: 137: private static void IndicateNode(LinkedListNode<string> node, string test)
138: { 139: Console.WriteLine(test);140: if (node.List == null)
141: {142: Console.WriteLine("Node '{0}' is not in the list.\n",
143: node.Value);144: return;
145: } 146: 147: StringBuilder result = new StringBuilder("(" + node.Value + ")");
148: LinkedListNode<string> nodeP = node.Previous;
149: 150: while (nodeP != null)
151: {152: result.Insert(0, nodeP.Value + " ");
153: nodeP = nodeP.Previous; 154: } 155: 156: node = node.Next;157: while (node != null)
158: {159: result.Append(" " + node.Value);
160: node = node.Next; 161: } 162: 163: Console.WriteLine(result); 164: Console.WriteLine(); 165: } 166: } 167: 168: //This code example produces the following output:
169: //
170: //The linked list values:
171: //the fox jumped over the dog
172: 173: //Test 1: Add 'today' to beginning of the list:
174: //today the fox jumped over the dog
175: 176: //Test 2: Move first node to be last node:
177: //the fox jumped over the dog today
178: 179: //Test 3: Change the last node to 'yesterday':
180: //the fox jumped over the dog yesterday
181: 182: //Test 4: Move last node to be first node:
183: //yesterday the fox jumped over the dog
184: 185: //Test 5: Indicate last occurence of 'the':
186: //the fox jumped over (the) dog
187: 188: //Test 6: Add 'lazy' and 'old' after 'the':
189: //the fox jumped over (the) lazy old dog
190: 191: //Test 7: Indicate the 'fox' node:
192: //the (fox) jumped over the lazy old dog
193: 194: //Test 8: Add 'quick' and 'brown' before 'fox':
195: //the quick brown (fox) jumped over the lazy old dog
196: 197: //Test 9: Indicate the 'dog' node:
198: //the quick brown fox jumped over the lazy old (dog)
199: 200: //Test 10: Throw exception by adding node (fox) already in the list:
201: //Exception message: The LinkedList node belongs a LinkedList.
202: 203: //Test 11: Move a referenced node (fox) before the current node (dog):
204: //the quick brown jumped over the lazy old fox (dog)
205: 206: //Test 12: Remove current node (dog) and attempt to indicate it:
207: //Node 'dog' is not in the list.
208: 209: //Test 13: Add node removed in test 11 after a referenced node (brown):
210: //the quick brown (dog) jumped over the lazy old fox
211: 212: //Test 14: Remove node that has the value 'old':
213: //the quick brown dog jumped over the lazy fox
214: 215: //Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':
216: //the quick brown dog jumped over the lazy rhinoceros
217: 218: //Test 16: Copy the list to an array:
219: //the
220: //quick
221: //brown
222: //dog
223: //jumped
224: //over
225: //the
226: //lazy
227: //rhinoceros
228: 229: //Test 17: Clear linked list. Contains 'jumped' = False
230: //
Monday, January 30, 2012
Is Razor or XSLT better for my project?
I don't agree with that. For me, Xslt is good for only static html pages. (no server codes). When you need to use server code, it's a lot difficult to control with XSLT.
XSLT or Razor would help to provide a separation of concerns where the original XML or response represents your model, the XSLT or 'Razor view' represents your view. I'll leave the controller out for this example. The initial design proposal recommends XSLT, however I suggested the use of Razor instead as a more friendly view engine.
These are the reasons I suggested for Razor (C#):
- Easier to work with and build more complicated pages.
- Can easily produce non-*ML output, eg csv, txt, fdf
- Less verbose templates
- The view model is strongly typed, where XSLT would need to rely on convention, eg boolean or date values
- Markup is more approachable, eg nbsp, newline normalization, attibute value normalization, whitespace rules
- Built in HTML helper can generate JS validation code based on DTO attributes
- Built in HTML helper can generate links to actions
And the arguments for XSLT over razor were:
- XSLT is a standard and will still exist many years into the future.
- It is hard to accidentally move logic into the view
- Easer for non programmers (which I don't agree with).
- It's been successful in some of our past projects.
- Data values are HTML-encoded by default
- Always well formed
So I'm looking for aguments on either side, recommendations or any experience making a similar choice?
Sunday, November 6, 2011
Facebook comment:
Google will index comments from sites using Facebook's comments plug-in
Move should see lively discussion sites benefit
Google also tweaking search so 'trending' results 'work faster'
Read more: http://www.dailymail.co.uk/sciencetech/article-2057640/Now-Googles-spiders-read-Facebook-comments.html#ixzz1cyVwuMMU
https://developers.facebook.com/docs/reference/plugins/comments/
Sunday, October 30, 2011
MVC 3 Razor C# View Engine adding
In MVC 3, Default Search view engine works like the following:
If user controls, the View engine finds under View folder OR Shared folder only.
Here is a problem:
If I created a folder under shared folder and your user control having in that folder, MVC ViewEngine couldn't find the correct user control via embedded usercontrol's page.
.Net throws this error.

But in MVC, every class that integreated in MVC you can extend as your custom requried.
Here is an example that I've found in internet that somebody shared in this website
(Waynehaffenden.com
RazorCSharpViewEngine.cs
view source
01 using System.Web.Mvc;
02 public class RazorCSharpViewEngine : RazorViewEngine
03 {
04 public RazorCSharpViewEngine()
05 {
06 AreaViewLocationFormats = new[]
07 {
08 "~/Areas/{2}/Views/{1}/{0}.cshtml",
09 "~/Areas/{2}/Views/Shared/{0}.cshtml"
10 };
11 AreaMasterLocationFormats = new[]
12 {
13 "~/Areas/{2}/Views/{1}/{0}.cshtml",
14 "~/Areas/{2}/Views/Shared/{0}.cshtml"
15 };
16 AreaPartialViewLocationFormats = new[]
17 {
18 "~/Areas/{2}/Views/{1}/{0}.cshtml",
19 "~/Areas/{2}/Views/Shared/{0}.cshtml"
20 };
21 ViewLocationFormats = new[]
22 {
23 "~/Views/{1}/{0}.cshtml",
24 "~/Views/Shared/{0}.cshtml"
25 };
26 MasterLocationFormats = new[]
27 {
28 "~/Views/{1}/{0}.cshtml",
29 "~/Views/Shared/{0}.cshtml"
30 };
31 PartialViewLocationFormats = new[]
32 {
33 "~/Views/{1}/{0}.cshtml",
34 "~/Views/Shared/{0}.cshtml"
35 };
36 }
37 }
Your Global.ascs's Application start() method should be as following.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Add(new RazorCustomViewEngine());
}
Friday, October 7, 2011
OOD Project?
Please look up following code whether it's OOD porject or not.
It's about binding Portfolio data from portfolio database.
I tired to add a new simple functionality to his code. And also he's always saying his code the best one.
Friday, June 24, 2011
Invalid operation. The connection is closed. ASP.NET MVC
Invalid operation. The connection is closed. ASP.NET MVC
In Entity framework 4.0.. datacontext shouldn't be static. so then, in every controller, you need to do a new instance of datacontext.
Otherwise, static datacontext can occur that two different request hitting will break the site.
Globalization .net
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.
NeutralCultures))
{
DropDownListLang.Items.Add(new ListItem(ci.NativeName, ci.Name));
}
That's cool. You will get all available .net culture into the drop down list.
Wednesday, June 1, 2011
return confirm('" & strMessage & "');")
btn.Attributes.Add("onclick", "return confirm('single " & strMessage & " single ');")
what I want to mention is "return confirm('" & strMessage & "')
sometime in development, you may need to do string manipulation. the similar case could be happened any time.
For reference purpose, I've hosted this post. If someone can reference on this, I am worth to put this post.
Friday, May 20, 2011
How to: Move a Database Using Detach and Attach (Transact-SQL)
Attach the moved database and, optionally, its log by executing the following Transact-SQL statements:
USE master;
GO
CREATE DATABASE MyAdventureWorks
ON (FILENAME = 'C:\MySQLServer\AdventureWorks2008R2_Data.mdf'),
(FILENAME = 'C:\MySQLServer\AdventureWorks2008R2_Log.ldf')
FOR ATTACH;
GO
For a production database, place the database and transaction log on separate disks.
Enjoy on this !
Monday, May 16, 2011
MVC validation on controller.
Before in my knowledge, I do understand the validation of mvc has to be placed on the model layer. That gives some headache to me to find right entity in entities.
That a pieces of codes saves my headache. That's just brilliant. Thanks to who posted this post. http://www.asp.net/mvc/tutorials/creating-model-classes-with-the-entity-framework-cs
public ActionResult Add()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(FormCollection form)
{
var movieToAdd = new Movie();
// Deserialize (Include white list!)
TryUpdateModel(movieToAdd, new string[] { "Title", "Director" }, form.ToValueProvider());
// Validate
if (String.IsNullOrEmpty(movieToAdd.Title))
ModelState.AddModelError("Title", "Title is required!");
if (String.IsNullOrEmpty(movieToAdd.Director))
ModelState.AddModelError("Director", "Director is required!");
// If valid, save movie to database
if (ModelState.IsValid)
{
_db.AddToMovieSet(movieToAdd);
_db.SaveChanges();
return RedirectToAction("Index");
}
// Otherwise, reshow form
return View(movieToAdd);
}
Tuesday, May 10, 2011
Microsoft SQL Server 2008 - Saving changes is not permitted
I have the same problem above. If you reference this site, you will get the resolve the problem.
http://www.sqlcoffee.com/Troubleshooting074
Thursday, May 5, 2011
Google map api for searching lat and lng by postcode and country name
I solved this issue with some codes which does reference to this site
http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/
very genius of that.
public LatLng GetLatLng(string addr)
33 {
34 var url = "http://maps.google.co.uk/maps/geo?output=csv&key=" +
35 this.API_KEY + "&q=" + HttpContext.Current.Server.UrlEncode(addr);
36
37 var request = WebRequest.Create(url);
38 var response = (HttpWebResponse)request.GetResponse();
39
40 if (response.StatusCode == HttpStatusCode.OK)
41 {
42
43 var ms = new MemoryStream();
44 var responseStream = response.GetResponseStream();
45
46 var buffer = new Byte[2048];
47 int count = responseStream.Read(buffer, 0, buffer.Length);
48
49 while (count > 0)
50 {
51 ms.Write(buffer, 0, count);
52 count = responseStream.Read(buffer, 0, buffer.Length);
53 }
54
55 responseStream.Close();
56 ms.Close();
57
58 var responseBytes = ms.ToArray();
59 var encoding = new System.Text.ASCIIEncoding();
60
61 var coords = encoding.GetString(responseBytes);
62 var parts = coords.Split(",");
63
64 return new LatLng(
65 Convert.ToDouble(parts[2]),
66 Convert.ToDouble(parts[3]));
67 }
68
69 return null;
70 }
71 }
Have fun with this !
Tuesday, May 3, 2011
How to postback on index change of ASP.net MVC dropdownlist?
I have found this on internet from this site
http://www.altafkhatri.com/Technical/ASP-NET-MVC-Dropdownlist/How-to-post-back/on-selectedIndexChanged
It is really helpful post. I put this on here future reference.
Steps to create the postback in ASP.Net MVC dropdownlist selectedindex change event:
Create a controller - Dropdownlist. Paste the code in the section below.
Create a view of the GetDD action binded to the strongly typed object(CoverObject). Paste the code in the section below.
Code in the controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace MvcApplication1.Controllers
{
public class CoverObject
{
public IList
public string SelectedName { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string formAction { get; set; }
public CoverObject()
{
iliSLI = new List
SelectListItem sli = new SelectListItem();
sli.Text = "Altaf";
sli.Value = "1";
iliSLI.Add(sli);
sli = new SelectListItem();
sli.Text = "Krish";
sli.Value = "22";
iliSLI.Add(sli);
sli = new SelectListItem();
sli.Text = "Sameer";
sli.Value = "3333";
iliSLI.Add(sli);
sli = new SelectListItem();
sli.Text = "Iqbal";
sli.Value = "44444";
iliSLI.Add(sli);
sli = new SelectListItem();
sli.Text = "Maimoona";
sli.Value = "5555";
iliSLI.Add(sli);
}
}
public class DropdownlistController : Controller
{
//
// GET: /Dropdownlist/
public ActionResult Index()
{
return View();
}
public ActionResult GetDD()
{
CoverObject co = new CoverObject();
co.formAction = "";
//ViewData["SecretQuestion"] = co.iliSLI;
return View(co);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetDD(CoverObject co)
{
CoverObject coNew = new CoverObject();
string indexChangedValue = co.SelectedName;
var item = from it in coNew.iliSLI
where it.Value == co.SelectedName
select it;
item.First().Selected = true;
coNew.Name = item.First().Text;
coNew.Address = co.Address;
if (!string.IsNullOrEmpty(co.formAction) && co.formAction.Equals("Submit Form By Clicking"))
{
// Based on the main submit of the form, it can process and redirect or stay on the same view.
ModelState.AddModelError("_FORM", "Form Submitted by clicking submit button");
}
else//Submitted by dropdownlist index change event
{
//DROPDOWNLIST on selectedIndexChangedEvent Handled hereModelState.AddModelError("_FORM", "Form Submitted by clicking submit button");
ModelState.AddModelError("iliSLI", "Form Submitted by selected Index Change event");
}
return View(coNew);
}
}
}
Code in the aspx file
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage
<%= Html.ValidationSummary("Form submitted by what event notification:") %>
<% using (Html.BeginForm()) {%>
<% } %>
Friday, February 18, 2011
Insert query return SCOPE_IDENTITY()
this is very useful when you needed to do more business logic after table inserting.
ALTER PROCEDURE [dbo].[uspNewsletterSubscriptions_Insert]
@TitleId int,
@Forename nvarchar(255),
@Surname nvarchar(255),
@EmailAddress nvarchar(255),
@Id int OUTPUT
AS
BEGIN
insert into tNewsletterSubscriptions(TitleId, Forename, Surname, EmailAddress)
values(@TitleId, @Forename, @Surname, @EmailAddress)
SET @Id = SCOPE_IDENTITY()
SELECT [Id]
,[Created]
,[LastUpdated]
,[TitleId]
,[Forename]
,[Surname]
,[EmailAddress]
FROM tNewsletterSubscriptions
WHERE Id = SCOPE_IDENTITY()
END
Thursday, February 17, 2011
Email Templates with C# asp.net
You write whatever you want that Html email template or text email template in eg(contorlsculture.resx) under App_GlobalResources.
And follows following codes -
private string FormatEmailBody(StringBuilder emailBody)
{
emailBody.Replace("{jobtitle}", HttpUtility.HtmlEncode(drVacancy.Title));
emailBody.Replace("{reference}", HttpUtility.HtmlEncode(drVacancy.Reference));
emailBody.Replace("{location}", HttpUtility.HtmlEncode(drVacancy.Location));
emailBody.Replace("{salary}", HttpUtility.HtmlEncode(drVacancy.Salary));
emailBody.Replace("{title}", HttpUtility.HtmlEncode(txtTitle.Text));
emailBody.Replace("{firstname}", HttpUtility.HtmlEncode(txtFirstName.Text));
emailBody.Replace("{surname}", HttpUtility.HtmlEncode(txtSurname.Text));
emailBody.Replace("{email}", HttpUtility.HtmlEncode(txtEmail.Text));
emailBody.Replace("{telephone}", HttpUtility.HtmlEncode(txtTelephone.Text));
emailBody.Replace("{message}", HttpUtility.HtmlEncode(txtMessage.Text));
return emailBody.ToString();
}
private void SendEmail()
{
// Sends Job application to recruiter
string strEmailBody = FormatEmailBody(new StringBuilder(Resources.ControlsCulture.JobApplicationTemplate));
EmailHelper.SendMail(drVacancy.Title + " Job - Application", strEmailBody, new string[] { ConfigHelper.RecruitmentEmail }, null, null,
ConfigHelper.NoReplyEmail.ToString(), fuApplicationForm.PostedFile, fuCV.PostedFile, fuOpsForm.PostedFile);
txtTitle.Text = txtFirstName.Text = txtSurname.Text = txtEmail.Text = txtConfirmEmail.Text =
txtTelephone.Text = txtMessage.Text = "";
phMessage.Visible = true;
}
protected void lkbSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SendEmail();
}
}
That takes you get sucessful email sending process.
But on the other hand, some opposite idea programmer wants to use a physical files for email templates.
Then creates template files under App_data folder.
now a little bit needs to update the code of sending email. Basically, uses IO and stringbuilder class.
Something like that :
private string FormatEmailBody(StringBuilder emailBody)
{
emailBody.Replace("{contact}", HttpUtility.HtmlEncode("Administrator"));
emailBody.Replace("{name}", HttpUtility.HtmlEncode(txtTitle.Text + " " + txtFirstName.Text + " "
+ txtSurname.Text));
emailBody.Replace("{email}", HttpUtility.HtmlEncode(txtEmail.Text));
emailBody.Replace("{housename}", HttpUtility.HtmlEncode(txtHouseName.Text));
emailBody.Replace("{street}", HttpUtility.HtmlEncode(txtNumberStreet.Text));
emailBody.Replace("{area}", HttpUtility.HtmlEncode(txtLocation.Text));
emailBody.Replace("{town}", HttpUtility.HtmlEncode(txtCity.Text));
emailBody.Replace("{county}", HttpUtility.HtmlEncode(txtCounty.Text));
emailBody.Replace("{postcode}", HttpUtility.HtmlEncode(txtPostcode.Text));
emailBody.Replace("{telephone}", HttpUtility.HtmlEncode(txtTelephone.Text));
emailBody.Replace("{enquiry}", HttpUtility.HtmlEncode(txtEnquiry.Text));
return emailBody.ToString();
}
private void SendEmail()
{
string sFullTemplatePath = HttpContext.Current.Server.MapPath(drFormEmails.EmailTxtFileName);
StringBuilder sbTemplate = new StringBuilder();
using (StreamReader sr = new StreamReader(sFullTemplatePath))
{
sbTemplate = new StringBuilder(sr.ReadToEnd());
}
string strEmailBody = FormatEmailBody(sbTemplate);
EmailHelper.SendMail("Contact us", strEmailBody, new string[] { drFormEmails.MailTo }, null, null,
drFormEmails.MailFrom);
}
protected void lbSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SendEmail();
Response.Redirect("/Contact-us-confirmation");
}
}
Any better suggestion, please comment it. I will reply you.
Thursday, February 10, 2011
how to display a value to textbox whos textmode is set to 'password' in c#
Question: String cookiename = TextBox1.Text;
//grab cookie
HttpCookie cookie = Request.Cookies[cookiename];
//exists?
if (null == cookie)
{
Label1.Text = "cookie not found";
}
else
{
password.Text=cookie.Value.ToString();
}
Answer:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];
TextBox2.Attributes.Add("value", cookie.Value.ToString());
The answer is just one line. but it saves a lot of time.
Monday, February 7, 2011
publicity event fire c#
publicity event fire
In Usercontrol
Declare this:
public event EventHandler FileUploaded;
In some of click event of usercontrol
// Fire public event.
FileUploaded(this.FileResourceId, e);
On .aspx page
On the page load
writes instance to know usercontrol first:
WRVS.Website.V1.WebApplication.Admin.inc.usercontrols.FileUploader uFileUploader =
(WRVS.Website.V1.WebApplication.Admin.inc.usercontrols.FileUploader)
fvContentPage.FindControl("uFileUploader");
if (uFileUploader != null)
{
uFileUploader.FileUploaded += new EventHandler(FileUploaded);
}
Then create event:
private void FileUploaded(object sender, EventArgs e)
{
// logic for page update.
}
Friday, January 28, 2011
session timeout on IIS
1. Start Microsoft Internet Information Services (IIS) Manager.
2. In the Internet Information Services window, expand the ServerName node, where ServerName is the name of the server.
3. Right-click Default Web Site, and then click Properties.
4. In the Default Web Site Properties dialog box, on the Home Directory tab, click Configuration.
5. In the Application Configuration dialog box, on the Options tab, the session timeout box displays the Session.Timeout value.
Back to the top
Microsoft Windows Server 2003
1. Start Internet Information Services Manager, or open the IIS snap-in.
2. In the Internet Information Services window, expand the ServerName node, where ServerName is the name of the server.
3. Expand the Web Sites node.
4. Right-click Default Web Site, and then click Properties.
5. In the Default Web Site Properties dialog box, on the Home Directory tab, click Configuration.
6. In the Application Configuration dialog box, on the Options tab, the session timeout box displays the Session.Timeout value.
To configure session timeout
You can perform this procedure by using the user interface (UI), by running Appcmd.exe commands in a command-line window, by editing configuration files directly, or by writing WMI scripts.
User Interface
To Use the UI
1.
Open IIS Manager and navigate to the level you want to manage. For information about opening IIS Manager, see Open IIS Manager (IIS 7). For information about navigating to locations in the UI, see Navigation in IIS Manager (IIS 7).
2.
In Features View, double-click ASP.
3.
On the ASP page, under Services, expand Session Properties.
4.
In the Time-out field, enter a time-out value in the format hh:mm:ss. For example, enter 00:15:00 for 15 minutes.
5.
In the Actions pane, click Apply.