Send email


Published on and c#

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Send email

  1. 1. protected void SendMail(){ // Gmail Address from where you send the mail var fromAddress = ""; // any address where the email will be sending var toAddress = YourEmail.Text.ToString(); //Password of your gmail address const string fromPassword = "09065090856"; // Passing the values and make a email formate to display string subject = YourSubject.Text.ToString(); string body = "From: " + YourName.Text + "n"; body += "Email: " + YourEmail.Text + "n"; body += "Subject: " + YourSubject.Text + "n"; body += "Question: n" + Comments.Text + "n"; // smtp settings var smtp = new System.Net.Mail.SmtpClient(); { smtp.Host = ""; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 20000; } // Passing values to smtp object smtp.Send(fromAddress, toAddress, subject, body);}protected void btnSubmit_Click(object sender, EventArgs e){ try { //here on button click what will done SendMail(); DisplayMessage.Text = "Your Comments after sending the mail"; DisplayMessage.Visible = true; YourSubject.Text = ""; YourEmail.Text = ""; YourName.Text = ""; Comments.Text = ""; } catch (Exception) { }} }IntroductionFor sending mail through ASP.NET and C# website:
  2. 2. BackgroundThis code is tested and running well on gmail account.Using the codeHTMLThe code below defines the HTML code of the control: Collapse | Copy Code<%this is the client side code for the design and display%><asp:Panel ID="Panel1" runat="server" DefaultButton="btnSubmit"> <p> Please Fill the Following to Send Mail.</p> <p> Your name: <asp:RequiredFieldValidator ID="RequiredFieldValidator11"runat="server" ErrorMessage="*" ControlToValidate="YourName" ValidationGroup="save" /><br /> <asp:TextBox ID="YourName" runat="server" Width="250px" /><br /> Your email address: <asp:RequiredFieldValidator ID="RequiredFieldValidator1"runat="server" ErrorMessage="*"
  3. 3. ControlToValidate="YourEmail" ValidationGroup="save" /><br /> <asp:TextBox ID="YourEmail" runat="server" Width="250px" /> <asp:RegularExpressionValidator runat="server"ID="RegularExpressionValidator23" SetFocusOnError="true" Text="Example:"ControlToValidate="YourEmail" ValidationExpression="w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*" Display="Dynamic" ValidationGroup="save" /><br /> Subject: <asp:RequiredFieldValidator ID="RequiredFieldValidator2"runat="server" ErrorMessage="*" ControlToValidate="YourSubject" ValidationGroup="save" /><br /> <asp:TextBox ID="YourSubject" runat="server" Width="400px" /><br /> Your Question: <asp:RequiredFieldValidator ID="RequiredFieldValidator3"runat="server" ErrorMessage="*" ControlToValidate="Comments" ValidationGroup="save" /><br /> <asp:TextBox ID="Comments" runat="server" TextMode="MultiLine" Rows="10" Width="400px" /> </p> <p> <asp:Button ID="btnSubmit" runat="server" Text="Send" OnClick=" btnSubmit_Click" ValidationGroup="save" /> </p></asp:Panel><p> <asp:Label ID="DisplayMessage" runat="server" Visible="false" /></p>The server side code: Collapse | Copy Codeprotected void SendMail(){ // Gmail Address from where you send the mail var fromAddress = ""; // any address where the email will be sending var toAddress = YourEmail.Text.ToString(); //Password of your gmail address const string fromPassword = "Password"; // Passing the values and make a email formate to display string subject = YourSubject.Text.ToString(); string body = "From: " + YourName.Text + "n"; body += "Email: " + YourEmail.Text + "n"; body += "Subject: " + YourSubject.Text + "n"; body += "Question: n" + Comments.Text + "n"; // smtp settings var smtp = new System.Net.Mail.SmtpClient(); { smtp.Host = ""; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 20000;
  4. 4. } // Passing values to smtp object smtp.Send(fromAddress, toAddress, subject, body);}protected void Button1_Click(object sender, EventArgs e){ try { //here on button click what will done SendMail(); DisplayMessage.Text = "Your Comments after sending the mail"; DisplayMessage.Visible = true; YourSubject.Text = ""; YourEmail.Text = ""; YourName.Text = ""; Comments.Text = ""; } catch (Exception) { }}Sending Web eMail in ASP.NETBy Peter Todorov | March 3, 2003 | .NET2 Email PrintOne of the most common functionalities used in Web development is sending email from aWeb page. Before you ask, I’ll give you a couple of reasons why you might want to sendemail from your Web application: create a "give us your feedback" Web page implement a "forgotten password" script that sends a password to the user’s email account send an automatic welcome email to your new newsletter subscriber send automatic email update notifications send automatic email notifications whenever an error occurs in your Web application
  5. 5. Of course there are many more situations where it’s appropriate to send email from your Webapplications, and it’s up to you to determine exactly how and where you’re going to implementthis functionality.Enter: .NETThe .NET framework makes the task of sending email from a Web page unbelievably easy andI’ll show you how to do it in a matter of minutes. This article presumes that you have a basicunderstanding of how .NET and ASP.NET works.1. Import the namespace, and create instances of required classesWe are going to use the SmtpMail and MailMessage classes, which belong to theSystem.Web.Mail namespace. In order to use them, we will need to import theSystem.Web.Mail namespace like this:view plainprint? 1. <%@ Import Namespace="System.Web.Mail" %>The MailMessage class provides properties and methods for constructing an email message. Tobuild our email message we need to create an instance of this class:view plainprint? 1. Dim objMail As New MailMessage()2. Set the properties of the objectNext, we have to set all the properties of the objMail object:view plainprint? 1. The email address of the sender <br> 2. objMail.From = "" <br> 3. <br> 4. The email address of the recipient <br> 5. objMail.To = "" <br> 6. <br> 7. The email address of the Cc recipient <br> 8. objMail.Cc = "" <br> 9. <br> 10. The email address of the Bcc recipient <br> 11. objMail.Bcc = "" <br> 12. <br> 13. The format of the message - it can be MailFormat.Text <br>
  6. 6. 14. or MailFormat.Html <br> 15. objMail.BodyFormat = MailFormat.Text <br> 16. <br> 17. The priority of the message - it can be MailPriority.High, <br> 18. MailPriority,Normal or MailPriority.Low <br> 19. objMail.Priority = MailPriority.High <br> 20. <br> 21. The subject of the message <br> 22. objMail.Subject = "My first ASP.NET email" <br> 23. <br> 24. The message text <br> 25. objMail.Body = "This is my first email sent via <br> 26. ASP.NET. It was easier than I thought :)"After all the properties (some of them are optional) of our new email message are set properly,the only thing that’s left to do is send the message.3. Send the MessageIf you have experience sending email from classic ASP script with CDONTS you might think thatthe MailMessage class has method Send or something similar. Well, the way ASP.NET sendsemail messages is a little different from ASP.We need to use the static method Send of the SmtpMail class, passing in our objMail instance.You might be asking "what’s a ‘static method’?" A static method is one that’s not associatedwith an instance of a type. An example of an instance of a type is our objMail object. It is illegalto reference a static member of a class through an instance. The proper way to do it is:view plainprint? 1. SmtpMail.Send(objMail)If you want to specify an SMTP server that’s different than the default, you’ll need to set theSmtpServer property of the SmtpMail class:view plainprint? 1. SmtpMail.SmtpServer = ""SummaryIn summary, to send an email from your ASP.NET page, you need to: import the System.Web.Mail namespace in your ASP.NET page create an instance of the MailMessage class
  7. 7. set all the properties of the MailMessage instance send the message with SmtpMail.Send methodAnd finally, to get you started, here’s the complete, functional code for an ASP.NET page thatsends the user’s feedback via email to the Webmaster:view plainprint? 1. <%@ Page Language="VB" EnableSessionState="False" <br> 2. EnableViewState="False" Trace="False" Debug="False"%> <br> 3. <%@ Import Namespace="System.Web.Mail" %> <br> 4. <script language="VB" runat=server> <br> 5. <br> 6. Sub Page_Load(Sender as Object, E as EventArgs) <br> 7. If Page.IsPostBack Then <br> 8. lblResponse.Text = "Your email has been sent." <br> 9. End If <br> 10. End Sub <br> 11. <br> 12. Sub btn_Click(sender as Object, e as System.EventArgs) <br> 13. If Request.Form("Email") <> "" Then <br> 14. Dim objMail As New MailMessage() <br> 15. objMail.From = "" <br> 16. objMail.To = Request.Form("Email") <br> 17. objMail.Subject = Request.Form("Subject") <br> 18. objMail.Body = Request.Form("Message") <br> 19. objMail.BodyFormat = MailFormat.Text <br> 20. SmtpMail.SmtpServer = "" <br> 21. SmtpMail.Send(objMail) <br> 22. Else <br> 23. lblResponse.Text = "Please enter an email address." <br> 24. End If <br> 25. End Sub <br> 26. <br> 27. </script> <br> 28. <html> <br> 29. <head> <br> 30. <style> <br> 31. .main {font-family:Verdana; font-size:12px;} <br> 32. .title {font-family:Verdana; font-size:18px; font-weight:bold;} <br> 33. </style> <br> 34. </head> <br> 35. <body> <br> 36. <span class="title" align="center">Send email from <br> 37. an ASP.NET page</span> <br> 38. <br>
  8. 8. 39. <br><br><asp:Label class="main" id="lblResponse" <br> 40. runat="server"/> <br> 41. <br> 42. <form method="POST" name="MainForm" runat="server"> <br> 43. <table> <br> 44. <tr> <br> 45. <td class="main" align="right">Email:</td> <br> 46. <td class="main"><input type="text" <br> 47. class="main" name="Email" value=""></td> <br> 48. </tr> <br> 49. <tr> <br> 50. <td class="main" align="right"> <br> 51. Subject:</td> <br> 52. <td class="main"><input type="text" <br> 53. class="main" name="Subject" value=""></td> <br> 54. </tr> <br> 55. <tr> <br> 56. <td class="main" align="right" <br> 57. valign="top">Message:</td> <br> 58. <td class="main"><textarea name="Message" <br> 59. cols="50" rows="8"></textarea></td> <br> 60. </tr> <br> 61. <br> 62. <br> 63. <tr> <br> 64. <td class="main">&nbsp;</td> <br> 65. <td class="main"><input type="Submit" <br> 66. id="btnSubmit" OnServerClick="btn_Click" value="Send" <br> 67. runat="server" /></td> <br> 68. </tr> <br> 69. </table> <br> 70. </form> <br> 71. </body> <br> 72. </html>Unable to upload attachment in send mail demoGuys I am stuck with a problem and want your genuine suggestion..Actually the problem is that i am trying to send a mail using is no issues while sending mail but when i try to include an attachment with it is not takingthe path of the concerned directory.. But when i am attaching the file from the root directory herei have my codes it is working absolutely well..Plz look at the code below and give some suggestion to rectify the problem.. protected void btnSend_Click(object sender, EventArgs e) {
  9. 9. try { MailMessage mail = new MailMessage(); mail.To.Add(txtTo.Text); mail.From = newMailAddress(""); mail.Subject = txtSubject.Text; mail.Body = txtBody.Text; System.Net.Mail.Attachment attachment; attachment = newSystem.Net.Mail.Attachment(FileUpload1.FileName); mail.Attachments.Add(attachment); mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = ""; //Or Your SMTP ServerAddress smtp.Credentials = new System.Net.NetworkCredential ("", "orangeorange"); //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail); Response.Write("<script language=javascript>alert(MAILSENT);</script>");
  10. 10. Response.Write("<script language=javascript>alert(Thank You for using VishalMail);</script>"); } catch (Exception ex) { labelError.Text = ex.Message; } }geniusvishalJunior Poster in Training58 posts since Jan 2012Ads by GoogleAjax Control ToolkitAjax Server and Client Controls Check it out! Video tutorials. Months Ago0Needless to say i am using demo gmail id over here so better try with your own id whiledebugging changing the webconfig as well...geniusvishalJunior Poster in Training58 posts since Jan 20124 Months Ago0
  11. 11. Guys i solved this problem.. The code is: protected void btnSend_Click(object sender, EventArgs e) { try { MailMessage mail = new MailMessage(); mail.To.Add(txtTo.Text); mail.From = new MailAddress(""); mail.Subject = txtSubject.Text; mail.Body = txtBody.Text; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(FileUpload1.PostedFile.InputStream,FileUpload1 .FileName); mail.Attachments.Add(attachment); mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = ""; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential ("", "********"); //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail);
  12. 12. Response.Write("<script language=javascript>alert(MAIL SENT);</script>"); Response.Write("<script language=javascript>alert(Thank You for using VishalMail);</script>"); } catch (Exception ex) { labelError.Text = ex.Message; } }geniusvishalJunior Poster in Training58 posts since Jan 20124 Months Ago0hii..Even i did the same but then it didnt work for me ... it was working good in my previous project:-( ...couldnt find where i have gone wrong now...kamilacbeJunior Poster in Training77 posts since Jun 20104 Months Ago0
  13. 13. Then post the code for your project... Lets see what is the problem....geniusvishalJunior Poster in Training58 posts since Jan 20124 Months Ago0hi..this is my code ....did the same 1. try 2. { 3. MailMessage mail = new MailMessage(); 4. 5. mail.To.Add(txtto.text); 6. mail.From = new MailAddress("username"); 7. 8. mail.Subject = "well"; 9. mail.Body = "hii"; 10. // mail.IsBodyHtml = true; 11. SmtpClient smtp = new SmtpClient(); 12. smtp.Host = ""; //Or Your SMTP Server Address 13. 14. smtp.Credentials = new System.Net.NetworkCredential 15. ("username", "password"); 16. //Or your Smtp Email ID and Password 17. smtp.EnableSsl = true; 18. smtp.Send(mail); 19. } 20. catch (Exception ex) 21. { 22. Response.Write(ex.Message); 23. }kamilacbeJunior Poster in Training77 posts since Jun 20104 Months Ago0
  14. 14. Have you changed the configuration in web.config??geniusvishalJunior Poster in Training58 posts since Jan 20124 Months Ago01> IF not then configure the settings for mention the network credentials over derealongwith the port number....2> Change the IMAP/POP settings in your userid...3> If still getting error paste the error msg with error img...geniusvishalJunior Poster in Training58 posts since Jan 20124 Months Ago0hii..I forgot to update my username in webconfig file ...thank you soo much for your fixed it ..:-)kamilacbeJunior Poster in Training77 posts since Jun 2010Related Article: Unable to send mail In silverlight
  15. 15. 10 Things ASP.NET Developers Should Know AboutWeb.config Inheritance and OverridesThe ASP.NET configuration system is build around the idea of inheritance:Each Web.config file applies configuration settings to the directory that it is in and to all ofthe child directories below it. Settings in child directories can optionally override or modifysettings that are specified in parent directories. Configuration settings in a Web.config filecan optionally be applied to individual files or subdirectories by specifying a path in a locationelement.The root of the ASP.NET configuration hierarchy is thesystemrootMicrosoft.NETFrameworkversionNumberCONFIGWeb.config file, whichincludes settings that apply to all ASP.NET applications that run a specific version of the .NETFramework. Because each ASP.NET application inherits default configuration settings from theroot Web.config file, you need to create Web.config files only for settings that override thedefault settings.For a lot of sites, you dont really need to know about that - you can get by with one Web.configfile for the site. But, knowing how the inheritance works - and how to control it - can really helpout.Ive noticed that a lot of the questions I answer questions on forums, StackOverflow, and internale-mail lists can be solved by better understanding how ASP.NET configuration inheritance andoverrides work. And so, a bunch of tips about how ASP.NET configuration inheritance andoverrides work! Ill start with some basics, but there are some towards the end Ill bet mostASP.NET developers dont know.Tip 1: Using Web.config files in site subfoldersAnd ASP.NET websites Web.config is part of an inheritance chain. Your websites subfolderscan have Web.config - an example is the Web.config file in an ASP.NET MVC applicationsView folder which does things like preventing directly viewing the View templates:
  16. 16. This allows for setting general settings at the site level and overriding them when necessary. Anysettings in the base Web.config that arent overridden in the subfolder stay in effect, so the"child" Web.config can be pretty small. You can continue to nest them, so sub-sub-subfolderscan get their own Web.config if needed. Some of the most common uses of subfolders are torestrict permission (e.g. requiring authentication or restricting access to resources), but you canalso use them to do things like include default namespaces in Views, toggle handlers, etc.Tip 2: Understand how your site Web.config inherits itssettingsBut theres an inheritance chain above the site, too. Heres a simplified version from the MSDNdocs:Configuration File name File description level The Machine.config file contains the ASP.NET schema for all of the Web applications on the server.Server Machine.config This file is at the top of the configuration merge hierarchy.IIS ApplicationHost.config ApplicationHost.config is the root file of the IIS 7.0
  17. 17. configuration system. It includes definitions of all sites, applications, virtual directories, and application pools, as well as global defaults for the Web server settings. It is in the following location: %windir%system32inetsrvconfig The Web.config file for the server is stored in the same directory as the Machine.config file and containsRoot Web Web.config default values for most of the system.web configuration sections. At run time, this file is merged second from the top in the configuration hierarchy. The Web.config file for a specific Web site contains settings that apply to the Web site and inheritWeb site Web.config downward through all of the ASP.NET applications and subdirectories of the site. The Web.config file for a specific ASP.NETASP.NET application is located in the root directory of theapplication root Web.config application and contains settings that apply to the Webdirectory application and inherit downward through all of the subdirectories in its branch. The Web.config file for an application subdirectoryASP.NET contains settings that apply to this subdirectory andapplication Web.config inherit downward through all of the subdirectories insubdirectory its branch.So your websites configurations actually inherited a bunch of settings that were set at the serverlevel. Thats nice for a few reasons: 1. It allows the ASP.NET / IIS teams to migrate settings that arent commonly modified from the project template Web.config files to server defaults, keeping your Web.config files smaller and more readable. For example, ASP.NET 4 migrated a bunch of handler registrations to Machine.config, so the Empty ASP.NET Application Web.config is slimmed down to about 8 lines. 2. You can override things at the server level as needed, and theyll take effect for all applications. For example, you can set <deployment retail="true"> on production servers to disable trace output and debug capabilities. 3. You can find a lot of useful information in the Machine.config default settings since theyre stored in plain text. For example, the ASP.NET Membership Provider has some defaults set for password requirements and the membership database, and you can look them up by looking in the appropriate .NET framework versions Machine.config. For a default installation of ASP.NET 4, thats found in C:WindowsMicrosoft.NETFramework64v4.0.30319Configmachine.config with a quick search for <membership>.
  18. 18. Tip 3: Understand how your Web.config inherits IISconfiguration settingsThis overlaps a bit of Tip 2, but it bears repeating. Long-time ASP.NET developers (myselfincluded) are prone to thinking of ASP.NET and IIS configuration separately, but that allchanged with IIS 7. This is all pretty old news, as IIS 7 has been out for a while, but it hasntbeen completely absorbed by ASP.NET developers.CarlosAg summed this up well in a post from 2006(!) which explained The New ConfigurationSystem in IIS 7. Im not going to rehash his post here - go read it. Some important takeaways arethat both the ApplicationHost.config and Machine.config feed into the configuration settings inyour sites Web.config, as shown in Carlos diagram:In addition to the understanding how things work part of it, this is also good to know because -based on the info in Tip 2 - you can see what the base settings are, and how you can overridethem in your applications Web.config. This is why you can do pretty advanced things likeconfigure rules on for the URL Rewrite Module in your applications web.config.Of course, server administrators dont necessarily want to allow any application on the server tomodify settings via Web.config, so there are configurable policies in the ApplicationHost.configwhich state whether individual applications can override settings. Theres also anAdministration.config file which controls things like Module registration.Theres one kind of new update to this list - using aspnet.config for Application Pooltuning. Its found in the same directory as Machine.config, and its been around since .NET 2.0.However, as of ASP.NET 4 its been expanded to handle things like concurrency and threading,as explained in Scott Forsyths post, Setting an aspnet.config File per Application Pool. Whilenot something most ASP.NET developers will need to use, its good to know that you can controlthings like maxConcurrentRequestsPerCPU, maxConcurrentThreadsPerCPU andrequestQueueLimit at the application pool level.Tip 4: Location, location
  19. 19. While its nice to be able to override settings in a subfolder using nested Web.config files, thatcan become hard to manage. In a large application, it can be difficult to manage settings becauseyou cant see the effective permissions in one place. Another option is to use the <location>element to target settings to a specific location. For example, I previously showed how to use thisto allow large file uploads to a specific directory in an ASP.NET application using the locationelement:<location path="Upload"> <system.web> <httpRuntime executionTimeout="110" maxRequestLength="20000" /> </system.web></location>Tip 5: Clearing parent settings when adding to a collectionSometimes you want to remove all inherited settings and start fresh. A common place youll seethis is in handler, module, connection string and provider registration - places whereconfiguration is used to populate a collection. Scott Guthrie blogged about an example in whichjust adding a new Membership Provider causes problems, because you end up with twoproviders - the default, and the one you just added. Its important to clear the collection beforeadding your new provider using the <clear/> element, like this:<membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="MyDatabase" enablePasswordRetrieval="false" (additional elements removed for brevity) /> </providers></membership>As Scott explains, failure to <clear/> the collection first results in both providers attempting tohandle membership, which probably isnt what you intended.Tip 6: Locking settings with with allowOverride andinheritInChildApplicationsYou may need to prevent sub-applications from overriding or extending settings. You can do thatwith the allowOverride attribute, which does exactly what the name suggests - the same way asealed class prevents changes via a derived class. The MSDN documentation summarizes thiswell:
  20. 20. You can lock configuration settings in ASP.NET configuration files (Web.config files) by addingan allowOverride attribute to a location element and setting the allowOverride attribute to false.Then within the location element, you can define the configuration section that you want to lock.ASP.NET will throw an exception if another configuration file attempts to override anyconfiguration section that is defined within this locked location element.Using a location element with an allowOverride=false attribute locks the entire configurationsection. You can also lock individual configuration elements and attributes using lockItem,lockElements, lockAttributes, lockAllAttributesExcept, and lockAllElementsExcept.That last part there - using attributes on sections - works because those lock attributes are amongthe general attributes inherited by section elements.Tip 7: Disinheriting your child applications withinheritInChildApplications="false"If youve got settings that should only apply to the parent application and shouldnt be inherited,you can use the inheritInChildApplications attribute on any section or location element. Thatmakes the settings at the current level, but inheriting applications and subfolders dont have tobother with clearing and rebuilding configuration just to remove those settings.This came up in a recent question on StackOverflow: Unloading parts of a web.config file froma child applicationSince Web.config is so heavily built on the concept of inheritance, its not surprising that turningit off for a section can have some side effects. The aptly self-named "Run Things Proper Harry,"a.k.a. rtpHarry, has written up two good posts covering usage and important things to be awareof. SOLVED: Breaking parent web.config dependencies in sub applications SOLVED: IIS7, validateIntegratedModeConfiguration and inheritInChildApplications clashTip 8: Use configSource to separate configuration intoseparate filesWhile Ive been discussing modification of Web.config settngs through inheritance, it onlymakes sense to mentions some useful ways to handle overriding Web.config settings.Any Web.config section can be moved to a separate file by setting the configSourceattribute to a file reference. Ive mostly used this for handling connection strings, since itallows you a lot more flexibility over versioning and and deployment. Instead of having differentWeb.config files for each environment ("Oops! Just deployed the staging Web.config toproduction!!!"). It looks like this:
  21. 21. <configuration> <connectionStrings configSource="connectionStrings.config" /> ...Then your connectionStrings.config file only needs to change between environments, and cancontain specific settings. It holds the contents of the element youre referring to, so it looks likethis:<connectionStrings> <add name="subtextData" connectionString="Server=.;Database=staging;Trusted_Connection=True;" /></connectionStrings>Another way Ive seen this done is to have differently named connection strings config files foreach environment (e.g. dev.config, staging.config, production.config). That allows you to checkthem all in to source control and not worry about getting files with the same name but differentcontents mixed up, but the tradeoff is that your Web.config in each environment needs to beupdated to point to the right config source.So, this is a handy trick, but isnt quite perfect. A better option is to use Web.config FileTransformations.Tip 9: Use Web.config Transforms to handle environmentaldifferencesI dont hear as much about Web.config Transforms as Id expect. Maybe they just work andeveryone just quietly uses them and doesnt talk about it. But from the questions I see coming upover and over again, Im not sure thats the case.I love Web.config Transforms. At my first ASP.NET MVP summit, I was part of a feedbackgroup discussing frustrations with deploying ASP.NET applications. Two themes that came upover and over were difficulties with packaging and managing configuration. That team laterproduced Web Deployment Packages (a nice format that packages files and settings for a site in away that can be inspected and modified during installation) and Web.config Transforms.All the new ASP.NET projects have Web.config transforms already set up - if you expandthe Web.config node, youll see that its configured to create different settings for Debug andRelease mode.
  22. 22. Its really easy to use - your main Web.config has the base settings for your site, andwhenever you build, the transforms for the appropriate build configuration (e.g. Debug orRelease) are automatically applied. If you had a Test database that you wanted to use bydefault, but wanted your Release builds to run against the Production database, you could set itup so that your base Web.config connection string points to the Test Database connection string,like this:<connectionStrings> <add name="ApplicationServices" connectionString="[TestDatabase]" /></connectionStrings>Then your Web.Release.config overwrites that to point at the Production database, like this:<?xml version="1.0"?><configuration xmlns:xdt=""> <connectionStrings> <add name="ApplicationServices" connectionString="[ProductionDatabase]" xdt:Transform="Replace" xdt:Locator="Match(name)"/> </connectionStrings></configuration>The syntax is pretty straightforward, but you dont need to worry about that because thecomments in the Web.Release.config file already show how to do that.To be clear: unlike the other examples, this is something that happens at build time, notruntime.
  23. 23. I recently ran into an issue where I wanted to deploy something to AppHarbor and wanted toswitch between a local SQL Compact database and the hosted database server, and Web.configTransforms worked just great there.Theres a lot more to talk about with Web.config Transforms thats beyond the scope here, suchas: You can create as many build configurations as you want, with different transforms for each configuration. This makes it simple to switch between different settings in your development environment - say, switching between several development databases or other application settings. You can use the configuration transformation system with any XML file using the SlowCheetah Visual Studio extension. Scott Hanselmans written a post with more information on that here: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file Sayed (the Microsoft developer whos worked on both Web.config Transforms and the SlowCheetah extension) has also built a Package Once Publish Anywhere NuGet package which allows you to defer running the transforms until later, using a PowerShell command. That means you can build one Web Deployment Package with all the transforms included, and run them when youre going to deploy to a specific environment.Theres some good information on MSDN about Web.config Transforms: Web.config File Transformation section in the Web Application Project Deployment Overview Web.config Transformation Syntax for Web Application Project Deployment Scott Hanselman: Web Deployment Made Awesome: If Youre Using XCopy, Youre Doing It WrongTip 10: Managing Application Restarts on ConfigurationChangesThere are a lot of moving parts in figuring out the configuration for a website, as illustratedabove. For that reason, ASP.NET computes the effective settings for the site and caches them. Itonly recomputes them (and restarts the application) when a file in the sites configurationhierarchy is modified. You can control that on a section by section level using therestartOnExternalChanges property.One place where configuration changes dont automatically get recomputed is for external configfiles set using configSource (as shown in Tip 8). You can control that by settingrestartOExternalChanges="true" for that section. Theres an example on MSDN that shows thisin more detail by creating an external configuration file which is loaded via the configurationAPI (not referenced via configSource), then toggling the restartOnExternalChanges property andshowing the differences in operation.
  24. 24. SummaryThe ASP.NET Configuration system does quite a bit - I didnt even mention big topics like usingthe API for reading and writing values to both local and external config files or creating customconfiguration sections. This post focuses on one aspect: getting things done by understandingand leveraging inheritance and overrides. Hopefully this gives you both some new tools foreffectively handling configuration and some background that helps in troubleshooting whenconfiguration is working as youd like.Are there any essential tips that I missed?Hi experts.,:) I have tried to send mail using silverlight application and now i am very much tired becauseof cant get it correctly.... I wrote a Web Service for sending mail as like below. using System.Web.Mail;MailMessage msg = new MailMessage(); msg.From = emailFrom; msg.To = emailTo; msg.Subject = ...Web.configFrom Wikipedia, the free encyclopediaJump to: navigation, searchWeb.config is the main settings and configuration file for an ASP.NET web application. The fileis an XML document that defines configuration information regarding the web application.Thisfile stores the information about how the web application will act. The web.config file containsinformation that control module loading, security configuration, session state configuration, andapplication language and compilation settings. Web.config files can also contain applicationspecific items such as database connection strings.Contents 1 Inheritance 2 See also 3 References 4 External linksInheritanceEach web application in ASP.NET inherits their base web.config from the machines web.configlocated in System RootMicrosoft.NETFrameworkVersion Numbermachine.Config<!-- Web.Config Configuration File --><configuration>
  25. 25. <system.web> <customErrors mode="off"/> </ System.web></ Configuration>ASP.NET Password Protected Login using the Session ObjectAlthough ASP.NET offers forms authentication for creating a password protected login systemyou can still use the Session Object to create a simple admin login system.First of all we will create a login.aspx file that displays a textbox control for the username andpassword. When the asp button LoginButton is clicked the click event is raised and the eventhandler Login is called.This subroutine checks the text property of the Username and Password textbox controls to see ifthey match admin and admin respectively. If they do then a session Session("Admin") iscreated and set to True and the user is redirected to the default.aspx page. If not then the Sessionis set to False and the Literal control LtlLogin text property is set to display a login error.Create a file Login.aspx<%@ Page Language="VB" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"""><script runat="server">Public Sub Login(ByVal s As Object, ByVal e As EventArgs)If UserName.Text = "admin" And Password.Text = "admin" Then Session("Admin") = True Response.Redirect("default.aspx") Else Session("Admin") = False LtlLogin.Text = "<p>Sorry you have provided incorrect login details.</p>"End IfEnd Sub</script><html xmlns=""><head runat="server"><title>Admin Log In</title></head><body><form id="form1" runat="server"><div>
  26. 26. <h1>Admin Log In</h1>Username:<br /><asp:TextBox ID="UserName" RunAt="server" /><br />Password:<br /><asp:TextBox ID="Password" TextMode="password" Runat="server" /><br /><asp:Button ID="LoginButton" Text="Log In" OnClick="LogIn" Runat="server" /><br /><asp:Literal ID="LtlLogin" Runat="server" /></div></form></body></html>To protect a file you can simply place code within the Page Load event that will check whetherthe session Session("Admin") is true or false. If its false then redirect the user back to thelogin.aspx file.Default.aspx<%@ Page Language="VB" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"""><script runat="server">Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) If Session("Admin") <> True Then Response.Redirect("login.aspx") End IfEnd Sub</script><html xmlns="" ><head runat="server"><title>Admin Area</title></head><body><form id="form1" runat="server"><div><p>Welcome to the Admin Area.</p></div></form>
  27. 27. </body></html>Learn how to create an ASP.NET login with Forms Authentication.10.3 Session StateMaintaining state on behalf of each client is often necessary in Web applications, whether it isused to keep track of items in a shopping cart or to note viewing preferences for a particular user.ASP.NET provides three ways of maintaining client-specific state: session state, cookie state,and view state. Each technique has its advantages and disadvantages. Session state is the mostflexible and, in general, the most efficient. ASP.NET has enhanced session state to address someof the problems associated with it in previous versions of ASP, including the abilities to hostsession state out of process (or in a database) and to track session state without using cookies.Session state is maintained on behalf of each client within an ASP.NET application. When a newclient begins to interact with the application, a new session ID (or session key) is generated andassociated with all subsequent requests from that same client (either using a cookie or via URLmangling). By default, the session state is maintained in the same process and AppDomain asyour application, so you can store any data type necessary in session state. If you elect to housesession state in another process or in a database, however, there are restrictions on what can bestored, as we will discuss shortly. Session state is maintained in an instance of theHttpSessionState class and is accessible through the Session property of both the Page andHttpContext classes. When a request comes in to an application, the Session properties of thePage and HttpContext class used to service that request are initialized to the current instance ofHttpSessionState that is associated with that particular client. Listing 10-3 shows the primarymethods and properties of the HttpSessionState class, along with the property accessors inboth the Page and HttpContext classes.Listing 10-3: HttpSessionState Classpublic sealed class HttpSessionState : ICollection, IEnumerable{ // properties public int CodePage {get; set;} public int Count {get;} public bool IsCookieless {get;} public bool IsNewSession {get;} public bool IsReadOnly {get;} public KeysCollection Keys {get;} public int LCID {get; set;} public SessionStateMode Mode {get;} public string SessionID {get;} public HttpStaticObjectsCollection StaticObjects {get;} public int Timeout {get; set;} // indexers public object this[string] {get; set;} public object this[int] {get; set;} // methods
  28. 28. public void Abandon(); public void Add(string name, object value); public void Clear(); public void Remove(string name); public void RemoveAll(); public void RemoveAt(int index); //...}public class Page : TemplateControl, IHttpHandler{ public virtual HttpSessionState Session {get;} //...}public sealed class HttpContext : IServiceProvider{ public HttpSessionState Session {get;} //...}Because the HttpSessionState class supports string and ordinal-based indexers, it can bepopulated and accessed using the standard array access notation that most developers are familiarwith from traditional ASP. There are some new properties, however, including flags for whetherthe session key is being maintained with cookies or with mangled URLs (IsCookieless) andwhether the session state is read-only (IsReadOnly). Also note that although the CodePageproperty is accessible through session state, this is for backward compatibility only. The properway to access the responses encoding is through Response.ContentEncoding.CodePage.For an example of using session state, lets consider an implementation of the classic shoppingcart for a Web application. As a user navigates among the pages of an application, she selectsitems to be retained in a shopping cart for future purchase. When the user is done shopping, shecan navigate to a checkout page, review the items she has collected in her cart, and purchasethem. This requires the Web application to retain a collection of items the user has chosen acrossrequest boundaries, which is exactly what session state provides. Listing 10-4 shows thedefinition of a class called Item. Instances of this class are used to represent the selected items inour shopping cart.Listing 10-4: Item Classpublic class Item{ private string _description; private int _cost; public Item(string description, int cost) { _description = description; _cost = cost; } public string Description {
  29. 29. get { return _description; } set { _description = value; } } public int Cost { get { return _cost; } set { _cost = value; } }}To store Item instances on behalf of the client, we initialize a new ArrayList in session stateand populate the ArrayList with items as the client selects them. If you need to perform one-time initialization of data in session state, the Session_Start event in the Application class isthe place to do so. Listing 10-5 shows a sample handler for the Session_Start event in ourapplication object, which in our case is creating a new ArrayList and adding it to the sessionstate property bag indexed by the keyword "Cart".Listing 10-5: Initializing Session State Objects// in global.asaxpublic class Global : System.Web.HttpApplication{ protected void Session_Start(Object sender, EventArgs e) { // Initialize shopping cart Session["Cart"] = new ArrayList(); }}A sample page that uses the shopping cart is shown in Listings 10-6 and 10-7. In this page, twohandlers are defined: one for purchasing a pencil and another for purchasing a pen. To keepthings simple, the items and their costs have been hard-coded, but in a real application thisinformation would normally come from a database lookup. When the user elects to add an itemto her cart, the AddItem method is called. This allocates a new instance of the Item class andinitializes it with the description and cost of the item to be purchased. That new item is thenadded to the ArrayList maintained by the Session object, indexed by the string "Cart".Listings 10-8 and 10-9 show a sample page that displays all the items in the current clients cartalong with a cumulative total cost.Listing 10-6: Session State Shopping Page Example<!— File: Purchase.aspx —><%@ Page language="c#" Codebehind="Purchase.aspx.cs" Inherits="PurchasePage" %><HTML> <body> <form runat="server"> <p>Items for purchase:</p> <asp:LinkButton id=_buyPencil runat="server" onclick="BuyPencil_Click"> Pencil ($1)</asp:LinkButton> <asp:LinkButton id=_buyPen runat="server" onclick="BuyPen_Click">
  30. 30. Pen ($2)</asp:LinkButton> <a href="purchase.aspx">Purchase</a> </form> </body></HTML>Listing 10-7: Session State Shopping Page Example—Code-Behind// File: Purchase.aspx.cspublic class PurchasePage : Page{ private void AddItem(string desc, int cost) { ArrayList cart = (ArrayList)Session["Cart"]; cart.Add(new Item(desc, cost)); } // handler for button to buy a pencil private void BuyPencil_Click(object sender, EventArgs e) { // add pencil ($1) to shopping cart AddItem("pencil", 1); } // handler for button to buy a pen private void BuyPen_Cick(object sender, EventArgs e) { // add pen ($2) to shopping cart AddItem("pen", 2); }}Listing 10-8: Session State Checkout Page Example<!— File: Checkout.aspx —><%@ Page language="c#" Codebehind="Checkout.aspx.cs" Inherits="CheckoutPage" %><HTML> <body> <form runat="server"> <asp:Button id=Buy runat="server" Text="Buy"/> <a href="purchase.aspx">Continue shopping</a> </form> </body></HTML>Listing 10-9: Session State Checkout Page Example—Code-Behind// File: Checkout.aspx.cspublic class CheckOutPage : Page{ private void Page_Load(object sender, System.EventArgs e) { // Print out contents of cart with total cost // of all items tallied int totalCost = 0; ArrayList cart = (ArrayList)Session["Cart"];
  31. 31. foreach (Item item in cart) { totalCost += item.Cost; Response.Output.Write("<p>Item: {0}, Cost: ${1}</p>", item.Description, item.Cost); } Response.Write("<hr/>"); Response.Output.Write("<p>Total cost: ${0}</p>", totalCost); }}The key features to note about session state are that it keeps state on behalf of a particular clientacross page boundaries in an application, and that the state is retained in memory on the server inthe default session state configuration.10.3.1 Session Key ManagementTo associate session state with a particular client, it is necessary to identify an incoming requestas having been issued by a given client. A mechanism for identifying a client is not built into theessentially connectionless HTTP protocol, so client tracking must be managed explicitly. Intraditional ASP, this was always done by setting a client-side cookie with a session key on thefirst client request. This technique is still supported in ASP.NET (in fact, it is the default technique) and is demonstrated in Figure 10-1. Figure 10-1: Session Key Maintained with Cookies Because session keys are used to track clients and maintain potentially sensitive information on their behalf, they must not only be unique, they must also be next to impossible to guess. This has been a problem in the past whenprogrammers used Globally Unique Identifiers (GUIDs) as session keys. Because the originalalgorithm for generating GUIDs was deterministic, if you knew one of the GUIDs generated by aserver machine, you could guess subsequent GUIDs and thus access the session state associatedwith another client. Although GUIDs are no longer generated this way, ASP.NET takes theprecaution of generating its own session keys by using the cryptographic service provider and itsown encoding algorithm. Listing 10-10 shows some pseudocode demonstrating the techniqueused by ASP.NET for creating session keys.Listing 10-10: Session Key Generation in ASP.NET// Generate 15-byte random number using the crypto providerRNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();byte[] key = new byte[15];rng.GetBytes(key);// Encode the random number into a 24-character string// (SessionId is a private class - not accessible)string sessionKey = SessionId.Encode(key);
  32. 32. Using cookies to track session state can be problematic. Clients can disable cookie support intheir browsers, and some browsers do not support cookies. As an alternative to using cookies,ASP.NET also supports a technique called URL mangling to track session keys without usingclient-side cookies. This technique works by intercepting the initial request made by a client,inserting the session key into the URL, and redirecting the client to the original page requested.When this page receives the request, it extracts the encoded session key from the request URLand initializes the current session state pointer to the correct block of memory. This technique isdemonstrated in Figure 10-2. This technique works even with clients that have disabled cookiesupport in their browsers. On any subsequent navigation, either via anchor tags or explicitprogrammatic redirections, ASP.NET will alter the target URL to embed the session key as well.This implicit URL mangling works only for relative URLs, however, so care must be taken withall links in an application using cookieless session key management to avoid absolute URLs. Figure 10-2: Session Key Maintained with URL Mangling Controlling whether cookies or URL mangling is used to manage your sessionkeys (along with several other session state–related features) is performed through thesessionState element in your applications web.config file. Table 10-2 lists the variousconfiguration settings available for the sessionState element of web.config. Listing 10-11shows a sample web.config file that enables cookieless session key management for anapplication.Table 10-2: sessionState AttributesAttribute Possible Values Meaningcookieless True, False Pass SessionID via cookies or URL manglingmode Where to store session state (or whether it is disabled) Server name and port for StateServer SQLServer connection string excluding database (tempdb is implied)timeout Example: 40 Session state timeout value (in minutes)Listing 10-11: Sample web.config File Enabling Cookieless Session Key Management<configuration> <system.web> <sessionState cookieless="true" /> </system.web></configuration>
  33. 33. The choice of whether to use cookie-based or mangled URL–based session key managementmust be made at the application level. It is not possible to specify that the application should usecookie-based management if the client supports cookies, and otherwise default to mangled URL–based management. The trade-offs to consider when making this decision include efficiency,universal client support, and dealing with relative URLs. Cookies are more efficient because theyavoid the redirection necessary to perform the URL mangling, although only one redirection persession will occur with URL mangling. Mangled URLs work with clients that dont have cookiesenabled (or that dont support them). The mangled URL technique requires that your applicationavoid absolute URLs so that the mangling can take place properly. Finally, URL mangling alsoprevents easy bookmarking and thus may be an inconvenience for your users.10.3.2 Storing Session State out of ProcessIn addition to requiring cookies to track session state, traditional ASP only supported the notionof in-process session state. Confining session state to a single process means that any applicationthat relies on session state must always be serviced by the same process on the same machine.This precludes the possibility of deploying the application in a Web farm environment, wheremultiple machines are used to service requests independently, potentially from the same client. Italso prevents the application from working correctly on a single machine with multiple hostprocesses, sometimes referred to as a Web garden. If session state is tied to the lifetime of theWeb server process, it is also susceptible to disappearing if that process goes down for somereason. To build traditional ASP applications that scale to Web farms and/or maintain persistentclient-specific state, developers must avoid session state altogether and rely on other techniquesfor tracking client-specific state. The most common approach is maintaining client-specific statein a database running on a network-accessible server. To distinguish one clients state fromanother, the table (or tables) used to store state is indexed by the session key, as shown in Figure 10-3. Figure 10-3: Maintaining Client-Specific State in a Web Farm Deployment ASP.NET introduces the ability to store session state out of process, without resorting to a custom database implementation. The sessionState element in an ASP.NET applications web.config file controls where session state isstored (see Table 10-2). The default location is in-process, as it was in traditional ASP. If themode attribute is set to StateServer or SqlServer, however, ASP.NET manages the details ofsaving and restoring session state to another process (running as a service) or to an SQL Serverdatabase installation. This is appealing because it is possible to build ASP.NET applications thataccess session state in the normal way, and then by switching the sessionState mode in aconfiguration file, that same application can be deployed safely in a Web farm environment.Whenever out-of-process session state is specified, it is also important to realize that anythingplaced into session state is serialized and passed out of the ASP.NET worker process. Thus, anytype that is stored in session state must be serializable for this to work properly. In our earliersession state example, we stored instances of a locally defined Item class, which, if left in itsexisting form, would fail any attempts at serialization. The ArrayList class we used to store theinstances of the Item class does support serialization, but since our class does not, the
  34. 34. serialization will fail. To correct this, we would need to add serialization support to our class.Listing 10-12 shows the Item class correctly annotated to support serialization, which is nowcompatible with storage in out-of-process session state.Listing 10-12: Adding Serialization Support to a Class[Serializable]public class Item{ private string _description; private int _cost; // ...}For session state to be transparently housed out of process, ASP.NET must assume that a pagehas all of its session state loaded before the page is loaded, and then flushed back to the out-of-process state container when the page completes its processing. This is inefficient when a pagemay not need this level of state access (although it is somewhat configurable, as we will see), sothere is still a valid case to be made for implementing your own custom client-specific statemanagement system, even with ASP.NET.The first option for maintaining session state out of process is to use the StateServer mode forsession state. Session state is then housed in a running process that is distinct from the ASP.NETworker process. The StateServer mode depends on the ASP.NET State Service to be up andrunning (this service is installed when you install the .NET runtime). By default the servicelistens over port 42424, although you can change that on a per-machine basis by changing thevalue of the HKLMSystemCurrentControlSetServicesaspnet_stateParametersPortkey in the registry. Figure 10-4 shows the ASP.NET State Service in the local machine servicesviewer. Figure 10-4: The ASP.NET State Service The State Service can run either on the same machine as the Web application or on a dedicated server machine. Using the State Service option is useful when you want out-of-process session state management but do not want to have toinstall SQL Server on the machine hosting the state. Listing 10-13 shows an exampleweb.config file that changes session state to live on server over port 42424, andFigure 10-5 illustrates the role of the state server in a Web farm deployment scenario. Figure 10.5: Using a State Server in a Web Farm Deployment Listing 10-13: web.config File Using State Server <configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="" /> </system.web></configuration>
  35. 35. The last option for storing session state outside the server process is to keep it in an SQL Serverdatabase. ASP.NET supports this through the SQLServer mode in the sessionStateconfiguration element. Before using this mode, you must run the InstallSqlState.sql scripton the database server where session state will be stored. This script is found in the mainMicrosoft.NET directory.15 The primary purpose of this script is to create a table that can storeclient-specific state indexed by session ID in the tempdb of that SQL Server installation. Listing10-14 shows the CREATE statement used to create the table for storing this state. The ASP statetable is created in the tempdb database, which is not a fully logged database, thus increasing thespeed of access to the data. In addition to storing the state indexed by the session ID, this tablekeeps track of expiration times and provides a locking mechanism for exclusive acquisition ofsession state. The installation script also adds a job to clean out all expired session state daily.Listing 10-14: ASPStateTempSession TableCREATE TABLE tempdb..ASPStateTempSessions ( SessionId CHAR(32) NOT NULL PRIMARY KEY, Created DATETIME NOT NULL DEFAULT GETDATE(), Expires DATETIME NOT NULL, LockDate DATETIME NOT NULL, LockCookie INT NOT NULL, Timeout INT NOT NULL, Locked BIT NOT NULL, SessionItemShort VARBINARY(7000) NULL, SessionItemLong IMAGE NULL,)Listing 10-15 shows a sample web.config file that has configured session state to live in anSQL Server database on server Notice that the sqlConnectionString attributespecifies a data source, a user ID, and a password but does not explicitly reference a database,because ASP.NET assumes that the database used will be tempdb.Listing 10-15: web.config File Using SQL Server<configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString= "data source=;user id=sa;password=" /> </system.web></configuration>Both the state server and the SQL Server session state options store the state as a byte stream—ininternal data structures in memory for the state server, and in a VARBINARY field (or an IMAGEfield if larger than 7KB) for SQL Server. While this is space-efficient, it also means that itcannot be modified except by bringing it into the request process. This is in contrast to a customclient-specific state implementation, where you could build stored procedures to update sessionkey–indexed data in addition to other data when performing updates. For example, consider ourshopping cart implementation shown earlier. If, when the user added an item to his cart, wewanted to update an inventory table for that item as well, we could write a single storedprocedure that added the item to his cart in a table indexed by his session key, and then updatedthe inventory table for that item in one round-trip to the database. Using the ASP.NET SQL
  36. 36. Server session state feature would require two additional round-trips to the database toaccomplish the same task: one to retrieve the session state as the page was loaded and one toflush the session state when the page was finished rendering.This leads us to another important consideration when using ASP.NETs out-of-process sessionstate feature: how to describe precisely the way each of the pages in your application will usesession state. By default, ASP.NET assumes that every page requires session state to be loadedduring page initialization and to be flushed after the page has finished rendering. When you areusing out-of-process session state, this means two round-trips to the state server (or databaseserver) for each page rendering. You can potentially eliminate many of these round-trips by morecarefully designing how each page in your application uses session state. The session managerthen determines when session state must be retrieved and stored by querying the currenthandlers session state requirements. There are three options for a page (or other handler) withrespect to session state. It can express the need to view session state, to view and modify sessionstate, or no session state dependency at all. When writing ASP.NET pages, you express thispreference through the EnableSessionState attribute of the Page directive. This attributedefaults to true, which means that session state will be retrieved and saved with each requesthandled by that page. If you know that a page will only read from session state and not modify it,you can save a round-trip by setting EnableSessionState to readonly. Furthermore, if youknow that a page will never use session state, you can set EnableSessionState to false.Internally, this flag determines which of the tagging interfaces your Page class will derive from(if any). These tagging interfaces are queried by the session manager to determine how tomanage session state on behalf of a given page. Figure 10-6 shows the various values ofEnableSessionState and their effect on your Page-derived class.Easy way to create secure ASP.NET login using SessionBy Abdallah Fayez | 28 Nov 2007 | Article.NET1.0.NET1.1.NET2.0VS.NET2003C#1.0.NET3.0ASP.NETWindowsDevWebForms, +It an easy and secure way for begginer ASP.NET developer to create secure login WebForms usingSessionsSee AlsoMore like thisMore by this authorArticle Browse Code StatsRevisionsAlternatives 1.82 (10 votes)
  37. 37. 10 Download - 21.5 KBIntroductionAs an ASP.NET developer, I needed to create a secure login WebForm, but I also needed it to beeasy to implement, not so complicated, and also accomplish the missionSessionsSessions are a real important thing, that used in many things we cant even imagine. You can usesessions in passing variables between WebForms instead of query-strings when passing securevalues, it can also be used to create secure, and easy login.Defining our SessionsIn the file "Global.asax", Well define our sessions in the function "Session_Start()" Collapse | Copy Codeprotected void Session_Start(Object sender, EventArgs e){ //The first Session "Logged" which is an indicator to the //status of the user Session["Logged"]="No"; //The second Session "User" stores the name of the current user Session["User"]=""; //The third Session "URL" stores the URL of the //requested WebForm before Logging In Session["URL"]="Default.aspx";}In the "Page_Load" of the Secured files, or the files which needed the user first to LogIn beforeseeing them, we add just check if the user is Logged or not. Collapse | Copy Codeprivate void Page_Load(object sender, System.EventArgs e){ if(Session["Logged"].Equals("No")) { .... } else
  38. 38. { .... }}In the "Login.aspx" file, Ive made checking the UserName and password with a regular ifcondition, with no database usage. But this code can be modified easily to check the Usernameand Password from a table in a database Collapse | Copy Codeif(UserNametxt.Text.Trim()=="Abdallah" && Passwordtxt.Text.Trim()=="Fayez"){ ....}else{ ....}The Code is available to download, with a sample "Login.aspx", and "Default.aspx" WebFormswhich make it easier for you to modify the code in best shape for you.LicenseThis article has no explicit license attached to it but may contain usage terms in the article text orthe download files themselves. If in doubt please contact the author via the discussion boardbelow.A list of licenses authors might use can be found hereAbout the AuthorAbdallah FayezWeb DeveloperEgyptian Banks Co. United StatesMember