SlideShare une entreprise Scribd logo
1  sur  38
protected void SendMail()
{
    // Gmail Address from where you send the mail
    var fromAddress = "aralourenalagazon.com";
    // 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.gmail.com";
        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) { }
}


       }


Introduction
For sending mail through ASP.NET and C# website:
Background
This code is tested and running well on gmail account.

Using the code
HTML

The 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="*"
ControlToValidate="YourEmail" ValidationGroup="save" /><br />
          <asp:TextBox ID="YourEmail" runat="server" Width="250px" />
          <asp:RegularExpressionValidator runat="server"
ID="RegularExpressionValidator23"
              SetFocusOnError="true" Text="Example: username@gmail.com"
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 Code
protected void SendMail()
{
    // Gmail Address from where you send the mail
    var fromAddress = "Gmail@gmail.com";
    // 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.gmail.com";
         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 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.NET

By Peter Todorov | March 3, 2003 | .NET

2




         Email
         Print

One of the most common functionalities used in Web development is sending email from a
Web page. Before you ask, I’ll give you a couple of reasons why you might want to send
email 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
Of course there are many more situations where it’s appropriate to send email from your Web
applications, and it’s up to you to determine exactly how and where you’re going to implement
this functionality.

Enter: .NET

The .NET framework makes the task of sending email from a Web page unbelievably easy and
I’ll show you how to do it in a matter of minutes. This article presumes that you have a basic
understanding of how .NET and ASP.NET works.

1. Import the namespace, and create instances of required classes

We are going to use the SmtpMail and MailMessage classes, which belong to the
System.Web.Mail namespace. In order to use them, we will need to import the
System.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. To
build 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 object

Next, we have to set all the properties of the objMail object:

view plainprint?

    1.    ' The email address of the sender <br>
    2.    objMail.From = "yourname@yourdomain.com" <br>
    3.     <br>
    4.    ' The email address of the recipient <br>
    5.    objMail.To = "recipientname@somedomain.com" <br>
    6.     <br>
    7.    ' The email address of the Cc recipient <br>
    8.    objMail.Cc = "name1@anotherdomain.com" <br>
    9.     <br>
    10.   ' The email address of the Bcc recipient <br>
    11.   objMail.Bcc = "name2@anotherdomain.com" <br>
    12.    <br>
    13.   ' The format of the message - it can be MailFormat.Text <br>
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 Message

If you have experience sending email from classic ASP script with CDONTS you might think that
the MailMessage class has method Send or something similar. Well, the way ASP.NET sends
email 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 associated
with an instance of a type. An example of an instance of a type is our objMail object. It is illegal
to 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 the
SmtpServer property of the SmtpMail class:

view plainprint?

    1. SmtpMail.SmtpServer = "smtp.your-server.com"

Summary

In 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
set all the properties of the MailMessage instance

  send the message with SmtpMail.Send method

And finally, to get you started, here’s the complete, functional code for an ASP.NET page that
sends 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 = "your_name@yourdomain.com" <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 = " smtp.your-server.com" <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>
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 demo

Guys I am stuck with a problem and want your genuine suggestion..
Actually the problem is that i am trying to send a mail using c#.net..
There is no issues while sending mail but when i try to include an attachment with it is not taking
the path of the concerned directory.. But when i am attaching the file from the root directory here
i 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)

               {
try

          {

                MailMessage mail = new MailMessage();




                 mail.To.Add(txtTo.Text);

                mail.From = new
MailAddress("orangesoftech2012@gmail.com");




                 mail.Subject = txtSubject.Text;

                 mail.Body = txtBody.Text;

                 System.Net.Mail.Attachment attachment;

                attachment = new
System.Net.Mail.Attachment(FileUpload1.FileName);

                 mail.Attachments.Add(attachment);




                 mail.IsBodyHtml = true;

                 SmtpClient smtp = new SmtpClient();

                 smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server
Address




                 smtp.Credentials = new System.Net.NetworkCredential

                 ("orangesoftech2012@gmail.com", "orangeorange");

                 //Or your Smtp Email ID and Password

                 smtp.EnableSsl = true;

                 smtp.Send(mail);

                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;




                       }

                }

geniusvishal

Junior Poster in Training

58 posts since Jan 2012



Ads by Google

Ajax Control Toolkit

Ajax Server and Client Controls Check it out! Video tutorials. mrbool.com/Ajax-Control-Toolkit

4 Months Ago

0

Needless to say i am using demo gmail id over here so better try with your own id while
debugging changing the webconfig as well...

geniusvishal

Junior Poster in Training

58 posts since Jan 2012



4 Months Ago

0
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("orangesoftech2012@gmail.com");




                        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 = "smtp.gmail.com"; //Or Your SMTP Server
      Address

                          smtp.Credentials = new System.Net.NetworkCredential

                          ("orangesoftech2012@gmail.com", "********");

                          //Or your Smtp Email ID and Password

                          smtp.EnableSsl = true;

                          smtp.Send(mail);
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;




                       }

                  }

geniusvishal

Junior Poster in Training

58 posts since Jan 2012



4 Months Ago

0

hii..

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...

kamilacbe

Junior Poster in Training

77 posts since Jun 2010



4 Months Ago

0
Then post the code for your project... Lets see what is the problem....

geniusvishal

Junior Poster in Training

58 posts since Jan 2012



4 Months Ago

0

hi..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 = "smtp.gmail.com"; //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.           }

kamilacbe

Junior Poster in Training

77 posts since Jun 2010



4 Months Ago

0
Have you changed the configuration in web.config??

geniusvishal

Junior Poster in Training

58 posts since Jan 2012



4 Months Ago

0

1> IF not then configure the settings for system.net... mention the network credentials over dere
alongwith the port number....

2> Change the IMAP/POP settings in your userid...

3> If still getting error paste the error msg with error img...

geniusvishal

Junior Poster in Training

58 posts since Jan 2012



4 Months Ago

0

hii..

I forgot to update my username in webconfig file ...thank you soo much for your prompt
reply...got fixed it ..:-)

kamilacbe

Junior Poster in Training

77 posts since Jun 2010



Related Article: Unable to send mail In silverlight
10 Things ASP.NET Developers Should Know About
Web.config Inheritance and Overrides
The 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 of
the child directories below it. Settings in child directories can optionally override or modify
settings that are specified in parent directories. Configuration settings in a Web.config file
can optionally be applied to individual files or subdirectories by specifying a path in a location
element.

The root of the ASP.NET configuration hierarchy is the
systemrootMicrosoft.NETFrameworkversionNumberCONFIGWeb.config file, which
includes settings that apply to all ASP.NET applications that run a specific version of the .NET
Framework. Because each ASP.NET application inherits default configuration settings from the
root Web.config file, you need to create Web.config files only for settings that override the
default settings.

For a lot of sites, you don't really need to know about that - you can get by with one Web.config
file for the site. But, knowing how the inheritance works - and how to control it - can really help
out.

I've noticed that a lot of the questions I answer questions on forums, StackOverflow, and internal
e-mail lists can be solved by better understanding how ASP.NET configuration inheritance and
overrides work. And so, a bunch of tips about how ASP.NET configuration inheritance and
overrides work! I'll start with some basics, but there are some towards the end I'll bet most
ASP.NET developers don't know.

Tip 1: Using Web.config files in site subfolders
And ASP.NET website's Web.config is part of an inheritance chain. Your website's subfolders
can have Web.config - an example is the Web.config file in an ASP.NET MVC application's
View folder which does things like preventing directly viewing the View templates:
This allows for setting general settings at the site level and overriding them when necessary. Any
settings in the base Web.config that aren't 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-subfolders
can get their own Web.config if needed. Some of the most common uses of subfolders are to
restrict permission (e.g. requiring authentication or restricting access to resources), but you can
also use them to do things like include default namespaces in Views, toggle handlers, etc.

Tip 2: Understand how your site Web.config inherits its
settings
But there's an inheritance chain above the site, too. Here's a simplified version from the MSDN
docs:

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
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 contains
Root 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 inherit
Web site          Web.config
                                           downward through all of the ASP.NET applications
                                           and subdirectories of the site.
                                           The Web.config file for a specific ASP.NET
ASP.NET                                    application is located in the root directory of the
application root Web.config                application and contains settings that apply to the Web
directory                                  application and inherit downward through all of the
                                           subdirectories in its branch.
                                           The Web.config file for an application subdirectory
ASP.NET
                                           contains settings that apply to this subdirectory and
application       Web.config
                                           inherit downward through all of the subdirectories in
subdirectory
                                           its branch.

So your website's configuration's actually inherited a bunch of settings that were set at the server
level. That's nice for a few reasons:

   1. It allows the ASP.NET / IIS teams to migrate settings that aren't 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 they'll 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
      they're 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 version's Machine.config. For a
      default installation of ASP.NET 4, that's found in
      C:WindowsMicrosoft.NETFramework64v4.0.30319Configmachine.config with a
      quick search for <membership>.
Tip 3: Understand how your Web.config inherits IIS
configuration settings
This overlaps a bit of Tip 2, but it bears repeating. Long-time ASP.NET developers (myself
included) are prone to thinking of ASP.NET and IIS configuration separately, but that all
changed with IIS 7. This is all pretty old news, as IIS 7 has been out for a while, but it hasn't
been completely absorbed by ASP.NET developers.

CarlosAg summed this up well in a post from 2006(!) which explained The New Configuration
System in IIS 7. I'm not going to rehash his post here - go read it. Some important takeaways are
that both the ApplicationHost.config and Machine.config feed into the configuration settings in
your site's 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 override
them in your application's Web.config. This is why you can do pretty advanced things like
configure rules on for the URL Rewrite Module in your application's web.config.

Of course, server administrators don't necessarily want to allow any application on the server to
modify settings via Web.config, so there are configurable policies in the ApplicationHost.config
which state whether individual applications can override settings. There's also an
Administration.config file which controls things like Module registration.

There's one kind of new update to this list - using aspnet.config for Application Pool
tuning. It's found in the same directory as Machine.config, and it's been around since .NET 2.0.
However, as of ASP.NET 4 it's been expanded to handle things like concurrency and threading,
as explained in Scott Forsyth's post, Setting an aspnet.config File per Application Pool. While
not something most ASP.NET developers will need to use, it's good to know that you can control
things like maxConcurrentRequestsPerCPU, maxConcurrentThreadsPerCPU and
requestQueueLimit at the application pool level.

Tip 4: Location, location
While it's nice to be able to override settings in a subfolder using nested Web.config files, that
can become hard to manage. In a large application, it can be difficult to manage settings because
you can't 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 this
to allow large file uploads to a specific directory in an ASP.NET application using the location
element:

<location path="Upload">
    <system.web>

        <httpRuntime executionTimeout="110"
                     maxRequestLength="20000" />
    </system.web>
</location>


Tip 5: Clearing parent settings when adding to a collection
Sometimes you want to remove all inherited settings and start fresh. A common place you'll see
this is in handler, module, connection string and provider registration - places where
configuration is used to populate a collection. Scott Guthrie blogged about an example in which
just adding a new Membership Provider causes problems, because you end up with two
providers - the default, and the one you just added. It's important to clear the collection before
adding your new provider using the <clear/> element, like this:

<membership>
      <providers>
          <clear/>
          <add name="AspNetSqlMembershipProvider"
              type="System.Web.Security.SqlMembershipProvider,
                    System.Web, Version=2.0.0.0,
                    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 to
handle membership, which probably isn't what you intended.

Tip 6: Locking settings with with allowOverride and
inheritInChildApplications
You may need to prevent sub-applications from overriding or extending settings. You can do that
with the allowOverride attribute, which does exactly what the name suggests - the same way a
sealed class prevents changes via a derived class. The MSDN documentation summarizes this
well:
You can lock configuration settings in ASP.NET configuration files (Web.config files) by adding
an 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 any
configuration section that is defined within this locked location element.

Using a location element with an allowOverride=false attribute locks the entire configuration
section. 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 among
the general attributes inherited by section elements.

Tip 7: Disinheriting your child applications with
inheritInChildApplications="false"
If you've got settings that should only apply to the parent application and shouldn't be inherited,
you can use the inheritInChildApplications attribute on any section or location element. That
makes the settings at the current level, but inheriting applications and subfolders don't have to
bother 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 from
a child application

Since Web.config is so heavily built on the concept of inheritance, it's not surprising that turning
it 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 aware
of.

       SOLVED: Breaking parent web.config dependencies in sub applications
       SOLVED: IIS7, validateIntegratedModeConfiguration and inheritInChildApplications
       clash

Tip 8: Use configSource to separate configuration into
separate files
While I've been discussing modification of Web.config settngs through inheritance, it only
makes 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 configSource
attribute to a file reference. I've mostly used this for handling connection strings, since it
allows you a lot more flexibility over versioning and and deployment. Instead of having different
Web.config files for each environment ("Oops! Just deployed the staging Web.config to
production!!!"). It looks like this:
<configuration>
  <connectionStrings configSource="connectionStrings.config" />
  ...

Then your connectionStrings.config file only needs to change between environments, and can
contain specific settings. It holds the contents of the element you're referring to, so it looks like
this:

<connectionStrings>
  <add name="subtextData"
    connectionString="Server=.;Database=staging;Trusted_Connection=True;" />
</connectionStrings>

Another way I've seen this done is to have differently named connection strings config files for
each environment (e.g. dev.config, staging.config, production.config). That allows you to check
them all in to source control and not worry about getting files with the same name but different
contents mixed up, but the tradeoff is that your Web.config in each environment needs to be
updated to point to the right config source.

So, this is a handy trick, but isn't quite perfect. A better option is to use Web.config File
Transformations.

Tip 9: Use Web.config Transforms to handle environmental
differences
I don't hear as much about Web.config Transforms as I'd expect. Maybe they just work and
everyone just quietly uses them and doesn't talk about it. But from the questions I see coming up
over and over again, I'm not sure that's the case.

I love Web.config Transforms. At my first ASP.NET MVP summit, I was part of a feedback
group discussing frustrations with deploying ASP.NET applications. Two themes that came up
over and over were difficulties with packaging and managing configuration. That team later
produced Web Deployment Packages (a nice format that packages files and settings for a site in a
way 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 expand
the Web.config node, you'll see that it's configured to create different settings for Debug and
Release mode.
It's really easy to use - your main Web.config has the base settings for your site, and
whenever you build, the transforms for the appropriate build configuration (e.g. Debug or
Release) are automatically applied. If you had a Test database that you wanted to use by
default, but wanted your Release builds to run against the Production database, you could set it
up 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="http://schemas.microsoft.com/XML-Document-
Transform">
  <connectionStrings>
    <add name="ApplicationServices"
        connectionString="[ProductionDatabase]"
        xdt:Transform="Replace" xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>

The syntax is pretty straightforward, but you don't need to worry about that because the
comments 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, not
runtime.
I recently ran into an issue where I wanted to deploy something to AppHarbor and wanted to
switch between a local SQL Compact database and the hosted database server, and Web.config
Transforms worked just great there.

There's a lot more to talk about with Web.config Transforms that's beyond the scope here, such
as:

       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 Hanselman's 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 who's 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 you're going to deploy to a specific
       environment.

There's 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 You're Using XCopy, You're
       Doing It Wrong

Tip 10: Managing Application Restarts on Configuration
Changes
There are a lot of moving parts in figuring out the configuration for a website, as illustrated
above. For that reason, ASP.NET computes the effective settings for the site and caches them. It
only recomputes them (and restarts the application) when a file in the sites configuration
hierarchy is modified. You can control that on a section by section level using the
restartOnExternalChanges property.

One place where configuration changes don't automatically get recomputed is for external config
files set using configSource (as shown in Tip 8). You can control that by setting
restartOExternalChanges="true" for that section. There's an example on MSDN that shows this
in more detail by creating an external configuration file which is loaded via the configuration
API (not referenced via configSource), then toggling the restartOnExternalChanges property and
showing the differences in operation.
Summary
The ASP.NET Configuration system does quite a bit - I didn't even mention big topics like using
the API for reading and writing values to both local and external config files or creating custom
configuration sections. This post focuses on one aspect: getting things done by understanding
and leveraging inheritance and overrides. Hopefully this gives you both some new tools for
effectively handling configuration and some background that helps in troubleshooting when
configuration is working as you'd 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 because
of can't 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.config
From Wikipedia, the free encyclopedia

Jump to: navigation, search

Web.config is the main settings and configuration file for an ASP.NET web application. The file
is an XML document that defines configuration information regarding the web application.This
file stores the information about how the web application will act. The web.config file contains
information that control module loading, security configuration, session state configuration, and
application language and compilation settings. Web.config files can also contain application
specific items such as database connection strings.

Contents
        1 Inheritance
        2 See also
        3 References
        4 External links



Inheritance
Each web application in ASP.NET inherits their base web.config from the machine's web.config
located in System RootMicrosoft.NETFrameworkVersion Numbermachine.Config

<!-- Web.Config Configuration File -->
<configuration>
<system.web>
        <customErrors mode="off"/>
    </ System.web>
</ Configuration>



ASP.NET Password Protected Login using the Session Object

Although ASP.NET offers forms authentication for creating a password protected login system
you 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 and
password. When the asp button 'LoginButton' is clicked the click event is raised and the event
handler 'Login' is called.

This subroutine checks the text property of the Username and Password textbox controls to see if
they match 'admin' and 'admin' respectively. If they do then a session Session("Admin") is
created and set to True and the user is redirected to the 'default.aspx' page. If not then the Session
is 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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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 If
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Admin Log In</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<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 whether
the session Session("Admin") is true or false. If it's false then redirect the user back to the
login.aspx file.

Default.aspx

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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 If
End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Area</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Welcome to the Admin Area.</p>
</div>
</form>
</body>
</html>

Learn how to create an ASP.NET login with Forms Authentication.

10.3 Session State
Maintaining state on behalf of each client is often necessary in Web applications, whether it is
used 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 most
flexible and, in general, the most efficient. ASP.NET has enhanced session state to address some
of the problems associated with it in previous versions of ASP, including the abilities to host
session 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 new
client begins to interact with the application, a new session ID (or session key) is generated and
associated with all subsequent requests from that same client (either using a cookie or via URL
mangling). By default, the session state is maintained in the same process and AppDomain as
your application, so you can store any data type necessary in session state. If you elect to house
session state in another process or in a database, however, there are restrictions on what can be
stored, as we will discuss shortly. Session state is maintained in an instance of the
HttpSessionState class and is accessible through the Session property of both the Page and
HttpContext classes. When a request comes in to an application, the Session properties of the
Page and HttpContext class used to service that request are initialized to the current instance of
HttpSessionState that is associated with that particular client. Listing 10-3 shows the primary
methods and properties of the HttpSessionState class, along with the property accessors in
both the Page and HttpContext classes.

Listing 10-3: HttpSessionState Class
public 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
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 be
populated and accessed using the standard array access notation that most developers are familiar
with from traditional ASP. There are some new properties, however, including flags for whether
the session key is being maintained with cookies or with mangled URLs (IsCookieless) and
whether the session state is read-only (IsReadOnly). Also note that although the CodePage
property is accessible through session state, this is for backward compatibility only. The proper
way to access the response's encoding is through Response.ContentEncoding.CodePage.

For an example of using session state, let's consider an implementation of the classic shopping
cart for a Web application. As a user navigates among the pages of an application, she selects
items to be retained in a shopping cart for future purchase. When the user is done shopping, she
can navigate to a checkout page, review the items she has collected in her cart, and purchase
them. This requires the Web application to retain a collection of items the user has chosen across
request boundaries, which is exactly what session state provides. Listing 10-4 shows the
definition of a class called Item. Instances of this class are used to represent the selected items in
our shopping cart.

Listing 10-4: Item Class
public class Item
{
  private string _description;
  private int     _cost;

    public Item(string description, int cost)
    {
      _description = description;
      _cost = cost;
    }

    public string Description
    {
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 state
and 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 is
the place to do so. Listing 10-5 shows a sample handler for the Session_Start event in our
application object, which in our case is creating a new ArrayList and adding it to the session
state property bag indexed by the keyword "Cart".

Listing 10-5: Initializing Session State Objects
// in global.asax
public 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, two
handlers are defined: one for purchasing a pencil and another for purchasing a pen. To keep
things simple, the items and their costs have been hard-coded, but in a real application this
information would normally come from a database lookup. When the user elects to add an item
to her cart, the AddItem method is called. This allocates a new instance of the Item class and
initializes it with the description and cost of the item to be purchased. That new item is then
added 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 client's cart
along 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">
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.cs
public 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.cs
public 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"];
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 client
across page boundaries in an application, and that the state is retained in memory on the server in
the default session state configuration.

10.3.1 Session Key Management

To associate session state with a particular client, it is necessary to identify an incoming request
as having been issued by a given client. A mechanism for identifying a client is not built into the
essentially connectionless HTTP protocol, so client tracking must be managed explicitly. In
traditional ASP, this was always done by setting a client-side cookie with a session key on the
first 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 when
programmers used Globally Unique Identifiers (GUIDs) as session keys. Because the original
algorithm for generating GUIDs was deterministic, if you knew one of the GUIDs generated by a
server machine, you could guess subsequent GUIDs and thus access the session state associated
with another client. Although GUIDs are no longer generated this way, ASP.NET takes the
precaution of generating its own session keys by using the cryptographic service provider and its
own encoding algorithm. Listing 10-10 shows some pseudocode demonstrating the technique
used by ASP.NET for creating session keys.

Listing 10-10: Session Key Generation in ASP.NET
// Generate 15-byte random number using the crypto provider
RNGCryptoServiceProvider 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);
Using cookies to track session state can be problematic. Clients can disable cookie support in
their 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 using
client-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 URL
and initializes the current session state pointer to the correct block of memory. This technique is
demonstrated in Figure 10-2. This technique works even with clients that have disabled cookie
support in their browsers. On any subsequent navigation, either via anchor tags or explicit
programmatic 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 with
all 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 session
keys (along with several other session state–related features) is performed through the
sessionState element in your application's web.config file. Table 10-2 lists the various
configuration settings available for the sessionState element of web.config. Listing 10-11
shows a sample web.config file that enables cookieless session key management for an
application.

Table 10-2: sessionState Attributes
Attribute              Possible Values         Meaning
cookieless             True, False                     Pass SessionID via cookies or URL mangling


mode                                                   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>
The choice of whether to use cookie-based or mangled URL–based session key management
must be made at the application level. It is not possible to specify that the application should use
cookie-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 they
avoid the redirection necessary to perform the URL mangling, although only one redirection per
session will occur with URL mangling. Mangled URLs work with clients that don't have cookies
enabled (or that don't support them). The mangled URL technique requires that your application
avoid absolute URLs so that the mangling can take place properly. Finally, URL mangling also
prevents easy bookmarking and thus may be an inconvenience for your users.

10.3.2 Storing Session State out of Process

In addition to requiring cookies to track session state, traditional ASP only supported the notion
of in-process session state. Confining session state to a single process means that any application
that 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, where
multiple machines are used to service requests independently, potentially from the same client. It
also prevents the application from working correctly on a single machine with multiple host
processes, sometimes referred to as a Web garden. If session state is tied to the lifetime of the
Web server process, it is also susceptible to disappearing if that process goes down for some
reason. To build traditional ASP applications that scale to Web farms and/or maintain persistent
client-specific state, developers must avoid session state altogether and rely on other techniques
for tracking client-specific state. The most common approach is maintaining client-specific state
in a database running on a network-accessible server. To distinguish one client's state from
another, 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 application's web.config file controls where session state is
stored (see Table 10-2). The default location is in-process, as it was in traditional ASP. If the
mode attribute is set to StateServer or SqlServer, however, ASP.NET manages the details of
saving and restoring session state to another process (running as a service) or to an SQL Server
database installation. This is appealing because it is possible to build ASP.NET applications that
access session state in the normal way, and then by switching the sessionState mode in a
configuration 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 anything
placed into session state is serialized and passed out of the ASP.NET worker process. Thus, any
type that is stored in session state must be serializable for this to work properly. In our earlier
session state example, we stored instances of a locally defined Item class, which, if left in its
existing form, would fail any attempts at serialization. The ArrayList class we used to store the
instances of the Item class does support serialization, but since our class does not, the
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 now
compatible 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 page
has 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 page
may not need this level of state access (although it is somewhat configurable, as we will see), so
there is still a valid case to be made for implementing your own custom client-specific state
management system, even with ASP.NET.

The first option for maintaining session state out of process is to use the StateServer mode for
session state. Session state is then housed in a running process that is distinct from the ASP.NET
worker process. The StateServer mode depends on the ASP.NET State Service to be up and
running (this service is installed when you install the .NET runtime). By default the service
listens over port 42424, although you can change that on a per-machine basis by changing the
value of the HKLMSystemCurrentControlSetServicesaspnet_stateParametersPort
key in the registry. Figure 10-4 shows the ASP.NET State Service in the local machine services
viewer.

                 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 to
install SQL Server on the machine hosting the state. Listing 10-13 shows an example
web.config file that changes session state to live on server 192.168.1.103 over port 42424, and
Figure 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="192.168.1.103:42424"
    />
  </system.web>
</configuration>
The last option for storing session state outside the server process is to keep it in an SQL Server
database. ASP.NET supports this through the SQLServer mode in the sessionState
configuration element. Before using this mode, you must run the InstallSqlState.sql script
on the database server where session state will be stored. This script is found in the main
Microsoft.NET directory.15 The primary purpose of this script is to create a table that can store
client-specific state indexed by session ID in the tempdb of that SQL Server installation. Listing
10-14 shows the CREATE statement used to create the table for storing this state. The ASP state
table is created in the tempdb database, which is not a fully logged database, thus increasing the
speed of access to the data. In addition to storing the state indexed by the session ID, this table
keeps track of expiration times and provides a locking mechanism for exclusive acquisition of
session state. The installation script also adds a job to clean out all expired session state daily.

Listing 10-14: ASPStateTempSession Table
CREATE 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 an
SQL Server database on server 192.168.1.103. Notice that the sqlConnectionString attribute
specifies 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=192.168.1.103;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—in
internal data structures in memory for the state server, and in a VARBINARY field (or an IMAGE
field if larger than 7KB) for SQL Server. While this is space-efficient, it also means that it
cannot be modified except by bringing it into the request process. This is in contrast to a custom
client-specific state implementation, where you could build stored procedures to update session
key–indexed data in addition to other data when performing updates. For example, consider our
shopping cart implementation shown earlier. If, when the user added an item to his cart, we
wanted to update an inventory table for that item as well, we could write a single stored
procedure that added the item to his cart in a table indexed by his session key, and then updated
the inventory table for that item in one round-trip to the database. Using the ASP.NET SQL
Server session state feature would require two additional round-trips to the database to
accomplish the same task: one to retrieve the session state as the page was loaded and one to
flush the session state when the page was finished rendering.

This leads us to another important consideration when using ASP.NET's out-of-process session
state feature: how to describe precisely the way each of the pages in your application will use
session state. By default, ASP.NET assumes that every page requires session state to be loaded
during page initialization and to be flushed after the page has finished rendering. When you are
using out-of-process session state, this means two round-trips to the state server (or database
server) for each page rendering. You can potentially eliminate many of these round-trips by more
carefully designing how each page in your application uses session state. The session manager
then determines when session state must be retrieved and stored by querying the current
handler's session state requirements. There are three options for a page (or other handler) with
respect to session state. It can express the need to view session state, to view and modify session
state, or no session state dependency at all. When writing ASP.NET pages, you express this
preference through the EnableSessionState attribute of the Page directive. This attribute
defaults to true, which means that session state will be retrieved and saved with each request
handled 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 you
know 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 to
manage session state on behalf of a given page. Figure 10-6 shows the various values of
EnableSessionState and their effect on your Page-derived class.



Easy way to create secure ASP.NET login using Session
By 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 using
Sessions



See Also

More like this
More by this author

Article    Browse Code StatsRevisionsAlternatives

                      1.82 (10 votes)
10

            Download SessionLogin.zip - 21.5 KB


Introduction
As an ASP.NET developer, I needed to create a secure login WebForm, but I also needed it to be
easy to implement, not so complicated, and also accomplish the mission

Sessions
Sessions are a real important thing, that used in many things we can't even imagine. You can use
sessions in passing variables between WebForms instead of query-strings when passing secure
values, it can also be used to create secure, and easy login.

Defining our Sessions
In the file "Global.asax", We'll define our sessions in the function "Session_Start()"

    Collapse | Copy Code

protected 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 before
seeing them, we add just check if the user is Logged or not.

    Collapse | Copy Code

private void Page_Load(object sender, System.EventArgs e)
{
    if(Session["Logged"].Equals("No"))
    {
         ....
    }
    else
{
              ....
       }
}


In the "Login.aspx" file, I've made checking the UserName and password with a regular if
condition, with no database usage. But this code can be modified easily to check the Username
and Password from a table in a database

    Collapse | Copy Code

if(UserNametxt.Text.Trim()=="Abdallah" && Passwordtxt.Text.Trim()=="Fayez")
{
    ....
}

else
{
       ....
}

The Code is available to download, with a sample "Login.aspx", and "Default.aspx" WebForms
which make it easier for you to modify the code in best shape for you.

License
This article has no explicit license attached to it but may contain usage terms in the article text or
the download files themselves. If in doubt please contact the author via the discussion board
below.

A list of licenses authors might use can be found here

About the Author
Abdallah Fayez

Web Developer
Egyptian Banks Co.
   United States

Member

Contenu connexe

Tendances

Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajaxs_pradeep
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with RailsJames Gray
 
Crud tutorial en
Crud tutorial enCrud tutorial en
Crud tutorial enforkgrown
 
Esposito Ajax Remote
Esposito Ajax RemoteEsposito Ajax Remote
Esposito Ajax Remoteask bills
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programmingFulvio Corno
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksRandy Connolly
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletMitchinson
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4DEVCON
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects WebStackAcademy
 
Send Sms To India
Send Sms To IndiaSend Sms To India
Send Sms To Indiasumeetha
 

Tendances (19)

Ajax
AjaxAjax
Ajax
 
Mashup
MashupMashup
Mashup
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
Crud tutorial en
Crud tutorial enCrud tutorial en
Crud tutorial en
 
Chat php
Chat phpChat php
Chat php
 
Esposito Ajax Remote
Esposito Ajax RemoteEsposito Ajax Remote
Esposito Ajax Remote
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
Mvc Mailer
Mvc MailerMvc Mailer
Mvc Mailer
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET Works
 
AJAX
AJAXAJAX
AJAX
 
Pushing the Web: Interesting things to Know
Pushing the Web: Interesting things to KnowPushing the Web: Interesting things to Know
Pushing the Web: Interesting things to Know
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutlet
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 
Send Sms To India
Send Sms To IndiaSend Sms To India
Send Sms To India
 

En vedette (20)

Bibliotecasocial buh bloque_i
Bibliotecasocial buh bloque_iBibliotecasocial buh bloque_i
Bibliotecasocial buh bloque_i
 
Curso Taller Universidad Integra
Curso Taller Universidad IntegraCurso Taller Universidad Integra
Curso Taller Universidad Integra
 
Ismt Renovavel
Ismt RenovavelIsmt Renovavel
Ismt Renovavel
 
Trabalho de sensoriamento remoto 2
Trabalho de sensoriamento remoto 2Trabalho de sensoriamento remoto 2
Trabalho de sensoriamento remoto 2
 
Apt. niños y la tele
Apt. niños y la teleApt. niños y la tele
Apt. niños y la tele
 
Teoria CinéTica E GáS Ideal
Teoria CinéTica E GáS IdealTeoria CinéTica E GáS Ideal
Teoria CinéTica E GáS Ideal
 
Processo Eletrônico e Hipetexto
Processo Eletrônico e HipetextoProcesso Eletrônico e Hipetexto
Processo Eletrônico e Hipetexto
 
Gestão de preços a+b+c+d grupo 3 g2 na
Gestão de preços a+b+c+d grupo 3 g2 naGestão de preços a+b+c+d grupo 3 g2 na
Gestão de preços a+b+c+d grupo 3 g2 na
 
Inadi
InadiInadi
Inadi
 
Plantas indrustrial
Plantas indrustrialPlantas indrustrial
Plantas indrustrial
 
Ismt Renovavel
Ismt RenovavelIsmt Renovavel
Ismt Renovavel
 
Roberto BeltráN 1
Roberto BeltráN 1Roberto BeltráN 1
Roberto BeltráN 1
 
Relatório Proppi
Relatório ProppiRelatório Proppi
Relatório Proppi
 
Apresentação ABEC
Apresentação ABECApresentação ABEC
Apresentação ABEC
 
TiCs UniBoyaca
TiCs  UniBoyacaTiCs  UniBoyaca
TiCs UniBoyaca
 
Entrada 5. plagio. power point.
Entrada 5. plagio. power point.Entrada 5. plagio. power point.
Entrada 5. plagio. power point.
 
Brochure frederik van eedenlaan
Brochure frederik van eedenlaanBrochure frederik van eedenlaan
Brochure frederik van eedenlaan
 
Libro de resumenes_del _xxv_cnf
Libro de resumenes_del _xxv_cnfLibro de resumenes_del _xxv_cnf
Libro de resumenes_del _xxv_cnf
 
Software libre en la ingeniería. Charla4
Software libre en la ingeniería. Charla4Software libre en la ingeniería. Charla4
Software libre en la ingeniería. Charla4
 
Enangrad 2014 Inep
Enangrad 2014 InepEnangrad 2014 Inep
Enangrad 2014 Inep
 

Similaire à Send email

Node mailer example how to send email using nodemailer with gmail &amp; mailtrap
Node mailer example how to send email using nodemailer with gmail &amp; mailtrapNode mailer example how to send email using nodemailer with gmail &amp; mailtrap
Node mailer example how to send email using nodemailer with gmail &amp; mailtrapKaty Slemon
 
Action Mailer
Action MailerAction Mailer
Action MailerSHC
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideSharebiyu
 
Baocao Web Tech Java Mail
Baocao Web Tech Java MailBaocao Web Tech Java Mail
Baocao Web Tech Java Mailxicot
 
Validate Email with JavaScript.pdf
Validate Email with JavaScript.pdfValidate Email with JavaScript.pdf
Validate Email with JavaScript.pdfEmailConcern
 
Python session.11 By Shanmugam
Python session.11 By ShanmugamPython session.11 By Shanmugam
Python session.11 By ShanmugamNavaneethan Naveen
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JSMartin Rehfeld
 

Similaire à Send email (20)

Lecture19
Lecture19Lecture19
Lecture19
 
Node mailer example how to send email using nodemailer with gmail &amp; mailtrap
Node mailer example how to send email using nodemailer with gmail &amp; mailtrapNode mailer example how to send email using nodemailer with gmail &amp; mailtrap
Node mailer example how to send email using nodemailer with gmail &amp; mailtrap
 
Postmark
PostmarkPostmark
Postmark
 
AWS SES
AWS SESAWS SES
AWS SES
 
Ruby
RubyRuby
Ruby
 
Send Email In Asp.Net
Send Email In Asp.NetSend Email In Asp.Net
Send Email In Asp.Net
 
Action Mailer
Action MailerAction Mailer
Action Mailer
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
Sending Email
Sending EmailSending Email
Sending Email
 
Javascript
JavascriptJavascript
Javascript
 
Lecture19
Lecture19Lecture19
Lecture19
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Baocao Web Tech Java Mail
Baocao Web Tech Java MailBaocao Web Tech Java Mail
Baocao Web Tech Java Mail
 
Html forms
Html formsHtml forms
Html forms
 
Validate Email with JavaScript.pdf
Validate Email with JavaScript.pdfValidate Email with JavaScript.pdf
Validate Email with JavaScript.pdf
 
PHP 2
PHP 2PHP 2
PHP 2
 
Python session.11 By Shanmugam
Python session.11 By ShanmugamPython session.11 By Shanmugam
Python session.11 By Shanmugam
 
Python session 11
Python session 11Python session 11
Python session 11
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
Tutorial asp.net
Tutorial  asp.netTutorial  asp.net
Tutorial asp.net
 

Dernier

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Dernier (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Send email

  • 1. protected void SendMail() { // Gmail Address from where you send the mail var fromAddress = "aralourenalagazon.com"; // 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.gmail.com"; 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) { } } } Introduction For sending mail through ASP.NET and C# website:
  • 2. Background This code is tested and running well on gmail account. Using the code HTML The 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. ControlToValidate="YourEmail" ValidationGroup="save" /><br /> <asp:TextBox ID="YourEmail" runat="server" Width="250px" /> <asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator23" SetFocusOnError="true" Text="Example: username@gmail.com" 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 Code protected void SendMail() { // Gmail Address from where you send the mail var fromAddress = "Gmail@gmail.com"; // 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.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 20000;
  • 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.NET By Peter Todorov | March 3, 2003 | .NET 2 Email Print One of the most common functionalities used in Web development is sending email from a Web page. Before you ask, I’ll give you a couple of reasons why you might want to send email 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. Of course there are many more situations where it’s appropriate to send email from your Web applications, and it’s up to you to determine exactly how and where you’re going to implement this functionality. Enter: .NET The .NET framework makes the task of sending email from a Web page unbelievably easy and I’ll show you how to do it in a matter of minutes. This article presumes that you have a basic understanding of how .NET and ASP.NET works. 1. Import the namespace, and create instances of required classes We are going to use the SmtpMail and MailMessage classes, which belong to the System.Web.Mail namespace. In order to use them, we will need to import the System.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. To build 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 object Next, we have to set all the properties of the objMail object: view plainprint? 1. ' The email address of the sender <br> 2. objMail.From = "yourname@yourdomain.com" <br> 3. <br> 4. ' The email address of the recipient <br> 5. objMail.To = "recipientname@somedomain.com" <br> 6. <br> 7. ' The email address of the Cc recipient <br> 8. objMail.Cc = "name1@anotherdomain.com" <br> 9. <br> 10. ' The email address of the Bcc recipient <br> 11. objMail.Bcc = "name2@anotherdomain.com" <br> 12. <br> 13. ' The format of the message - it can be MailFormat.Text <br>
  • 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 Message If you have experience sending email from classic ASP script with CDONTS you might think that the MailMessage class has method Send or something similar. Well, the way ASP.NET sends email 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 associated with an instance of a type. An example of an instance of a type is our objMail object. It is illegal to 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 the SmtpServer property of the SmtpMail class: view plainprint? 1. SmtpMail.SmtpServer = "smtp.your-server.com" Summary In 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. set all the properties of the MailMessage instance send the message with SmtpMail.Send method And finally, to get you started, here’s the complete, functional code for an ASP.NET page that sends 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 = "your_name@yourdomain.com" <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 = " smtp.your-server.com" <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. 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 demo Guys I am stuck with a problem and want your genuine suggestion.. Actually the problem is that i am trying to send a mail using c#.net.. There is no issues while sending mail but when i try to include an attachment with it is not taking the path of the concerned directory.. But when i am attaching the file from the root directory here i 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. try { MailMessage mail = new MailMessage(); mail.To.Add(txtTo.Text); mail.From = new MailAddress("orangesoftech2012@gmail.com"); mail.Subject = txtSubject.Text; mail.Body = txtBody.Text; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(FileUpload1.FileName); mail.Attachments.Add(attachment); mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential ("orangesoftech2012@gmail.com", "orangeorange"); //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail); Response.Write("<script language='javascript'>alert('MAIL SENT');</script>");
  • 10. Response.Write("<script language='javascript'>alert('Thank You for using VishalMail');</script>"); } catch (Exception ex) { labelError.Text = ex.Message; } } geniusvishal Junior Poster in Training 58 posts since Jan 2012 Ads by Google Ajax Control Toolkit Ajax Server and Client Controls Check it out! Video tutorials. mrbool.com/Ajax-Control-Toolkit 4 Months Ago 0 Needless to say i am using demo gmail id over here so better try with your own id while debugging changing the webconfig as well... geniusvishal Junior Poster in Training 58 posts since Jan 2012 4 Months Ago 0
  • 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("orangesoftech2012@gmail.com"); 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 = "smtp.gmail.com"; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential ("orangesoftech2012@gmail.com", "********"); //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail);
  • 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; } } geniusvishal Junior Poster in Training 58 posts since Jan 2012 4 Months Ago 0 hii.. 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... kamilacbe Junior Poster in Training 77 posts since Jun 2010 4 Months Ago 0
  • 13. Then post the code for your project... Lets see what is the problem.... geniusvishal Junior Poster in Training 58 posts since Jan 2012 4 Months Ago 0 hi..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 = "smtp.gmail.com"; //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. } kamilacbe Junior Poster in Training 77 posts since Jun 2010 4 Months Ago 0
  • 14. Have you changed the configuration in web.config?? geniusvishal Junior Poster in Training 58 posts since Jan 2012 4 Months Ago 0 1> IF not then configure the settings for system.net... mention the network credentials over dere alongwith the port number.... 2> Change the IMAP/POP settings in your userid... 3> If still getting error paste the error msg with error img... geniusvishal Junior Poster in Training 58 posts since Jan 2012 4 Months Ago 0 hii.. I forgot to update my username in webconfig file ...thank you soo much for your prompt reply...got fixed it ..:-) kamilacbe Junior Poster in Training 77 posts since Jun 2010 Related Article: Unable to send mail In silverlight
  • 15. 10 Things ASP.NET Developers Should Know About Web.config Inheritance and Overrides The 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 of the child directories below it. Settings in child directories can optionally override or modify settings that are specified in parent directories. Configuration settings in a Web.config file can optionally be applied to individual files or subdirectories by specifying a path in a location element. The root of the ASP.NET configuration hierarchy is the systemrootMicrosoft.NETFrameworkversionNumberCONFIGWeb.config file, which includes settings that apply to all ASP.NET applications that run a specific version of the .NET Framework. Because each ASP.NET application inherits default configuration settings from the root Web.config file, you need to create Web.config files only for settings that override the default settings. For a lot of sites, you don't really need to know about that - you can get by with one Web.config file for the site. But, knowing how the inheritance works - and how to control it - can really help out. I've noticed that a lot of the questions I answer questions on forums, StackOverflow, and internal e-mail lists can be solved by better understanding how ASP.NET configuration inheritance and overrides work. And so, a bunch of tips about how ASP.NET configuration inheritance and overrides work! I'll start with some basics, but there are some towards the end I'll bet most ASP.NET developers don't know. Tip 1: Using Web.config files in site subfolders And ASP.NET website's Web.config is part of an inheritance chain. Your website's subfolders can have Web.config - an example is the Web.config file in an ASP.NET MVC application's View folder which does things like preventing directly viewing the View templates:
  • 16. This allows for setting general settings at the site level and overriding them when necessary. Any settings in the base Web.config that aren't 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-subfolders can get their own Web.config if needed. Some of the most common uses of subfolders are to restrict permission (e.g. requiring authentication or restricting access to resources), but you can also use them to do things like include default namespaces in Views, toggle handlers, etc. Tip 2: Understand how your site Web.config inherits its settings But there's an inheritance chain above the site, too. Here's a simplified version from the MSDN docs: 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. 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 contains Root 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 inherit Web site Web.config downward through all of the ASP.NET applications and subdirectories of the site. The Web.config file for a specific ASP.NET ASP.NET application is located in the root directory of the application root Web.config application and contains settings that apply to the Web directory application and inherit downward through all of the subdirectories in its branch. The Web.config file for an application subdirectory ASP.NET contains settings that apply to this subdirectory and application Web.config inherit downward through all of the subdirectories in subdirectory its branch. So your website's configuration's actually inherited a bunch of settings that were set at the server level. That's nice for a few reasons: 1. It allows the ASP.NET / IIS teams to migrate settings that aren't 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 they'll 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 they're 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 version's Machine.config. For a default installation of ASP.NET 4, that's found in C:WindowsMicrosoft.NETFramework64v4.0.30319Configmachine.config with a quick search for <membership>.
  • 18. Tip 3: Understand how your Web.config inherits IIS configuration settings This overlaps a bit of Tip 2, but it bears repeating. Long-time ASP.NET developers (myself included) are prone to thinking of ASP.NET and IIS configuration separately, but that all changed with IIS 7. This is all pretty old news, as IIS 7 has been out for a while, but it hasn't been completely absorbed by ASP.NET developers. CarlosAg summed this up well in a post from 2006(!) which explained The New Configuration System in IIS 7. I'm not going to rehash his post here - go read it. Some important takeaways are that both the ApplicationHost.config and Machine.config feed into the configuration settings in your site's 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 override them in your application's Web.config. This is why you can do pretty advanced things like configure rules on for the URL Rewrite Module in your application's web.config. Of course, server administrators don't necessarily want to allow any application on the server to modify settings via Web.config, so there are configurable policies in the ApplicationHost.config which state whether individual applications can override settings. There's also an Administration.config file which controls things like Module registration. There's one kind of new update to this list - using aspnet.config for Application Pool tuning. It's found in the same directory as Machine.config, and it's been around since .NET 2.0. However, as of ASP.NET 4 it's been expanded to handle things like concurrency and threading, as explained in Scott Forsyth's post, Setting an aspnet.config File per Application Pool. While not something most ASP.NET developers will need to use, it's good to know that you can control things like maxConcurrentRequestsPerCPU, maxConcurrentThreadsPerCPU and requestQueueLimit at the application pool level. Tip 4: Location, location
  • 19. While it's nice to be able to override settings in a subfolder using nested Web.config files, that can become hard to manage. In a large application, it can be difficult to manage settings because you can't 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 this to allow large file uploads to a specific directory in an ASP.NET application using the location element: <location path="Upload"> <system.web> <httpRuntime executionTimeout="110" maxRequestLength="20000" /> </system.web> </location> Tip 5: Clearing parent settings when adding to a collection Sometimes you want to remove all inherited settings and start fresh. A common place you'll see this is in handler, module, connection string and provider registration - places where configuration is used to populate a collection. Scott Guthrie blogged about an example in which just adding a new Membership Provider causes problems, because you end up with two providers - the default, and the one you just added. It's important to clear the collection before adding your new provider using the <clear/> element, like this: <membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, 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 to handle membership, which probably isn't what you intended. Tip 6: Locking settings with with allowOverride and inheritInChildApplications You may need to prevent sub-applications from overriding or extending settings. You can do that with the allowOverride attribute, which does exactly what the name suggests - the same way a sealed class prevents changes via a derived class. The MSDN documentation summarizes this well:
  • 20. You can lock configuration settings in ASP.NET configuration files (Web.config files) by adding an 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 any configuration section that is defined within this locked location element. Using a location element with an allowOverride=false attribute locks the entire configuration section. 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 among the general attributes inherited by section elements. Tip 7: Disinheriting your child applications with inheritInChildApplications="false" If you've got settings that should only apply to the parent application and shouldn't be inherited, you can use the inheritInChildApplications attribute on any section or location element. That makes the settings at the current level, but inheriting applications and subfolders don't have to bother 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 from a child application Since Web.config is so heavily built on the concept of inheritance, it's not surprising that turning it 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 aware of. SOLVED: Breaking parent web.config dependencies in sub applications SOLVED: IIS7, validateIntegratedModeConfiguration and inheritInChildApplications clash Tip 8: Use configSource to separate configuration into separate files While I've been discussing modification of Web.config settngs through inheritance, it only makes 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 configSource attribute to a file reference. I've mostly used this for handling connection strings, since it allows you a lot more flexibility over versioning and and deployment. Instead of having different Web.config files for each environment ("Oops! Just deployed the staging Web.config to production!!!"). It looks like this:
  • 21. <configuration> <connectionStrings configSource="connectionStrings.config" /> ... Then your connectionStrings.config file only needs to change between environments, and can contain specific settings. It holds the contents of the element you're referring to, so it looks like this: <connectionStrings> <add name="subtextData" connectionString="Server=.;Database=staging;Trusted_Connection=True;" /> </connectionStrings> Another way I've seen this done is to have differently named connection strings config files for each environment (e.g. dev.config, staging.config, production.config). That allows you to check them all in to source control and not worry about getting files with the same name but different contents mixed up, but the tradeoff is that your Web.config in each environment needs to be updated to point to the right config source. So, this is a handy trick, but isn't quite perfect. A better option is to use Web.config File Transformations. Tip 9: Use Web.config Transforms to handle environmental differences I don't hear as much about Web.config Transforms as I'd expect. Maybe they just work and everyone just quietly uses them and doesn't talk about it. But from the questions I see coming up over and over again, I'm not sure that's the case. I love Web.config Transforms. At my first ASP.NET MVP summit, I was part of a feedback group discussing frustrations with deploying ASP.NET applications. Two themes that came up over and over were difficulties with packaging and managing configuration. That team later produced Web Deployment Packages (a nice format that packages files and settings for a site in a way 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 expand the Web.config node, you'll see that it's configured to create different settings for Debug and Release mode.
  • 22. It's really easy to use - your main Web.config has the base settings for your site, and whenever you build, the transforms for the appropriate build configuration (e.g. Debug or Release) are automatically applied. If you had a Test database that you wanted to use by default, but wanted your Release builds to run against the Production database, you could set it up 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="http://schemas.microsoft.com/XML-Document- Transform"> <connectionStrings> <add name="ApplicationServices" connectionString="[ProductionDatabase]" xdt:Transform="Replace" xdt:Locator="Match(name)"/> </connectionStrings> </configuration> The syntax is pretty straightforward, but you don't need to worry about that because the comments 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, not runtime.
  • 23. I recently ran into an issue where I wanted to deploy something to AppHarbor and wanted to switch between a local SQL Compact database and the hosted database server, and Web.config Transforms worked just great there. There's a lot more to talk about with Web.config Transforms that's beyond the scope here, such as: 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 Hanselman's 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 who's 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 you're going to deploy to a specific environment. There's 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 You're Using XCopy, You're Doing It Wrong Tip 10: Managing Application Restarts on Configuration Changes There are a lot of moving parts in figuring out the configuration for a website, as illustrated above. For that reason, ASP.NET computes the effective settings for the site and caches them. It only recomputes them (and restarts the application) when a file in the sites configuration hierarchy is modified. You can control that on a section by section level using the restartOnExternalChanges property. One place where configuration changes don't automatically get recomputed is for external config files set using configSource (as shown in Tip 8). You can control that by setting restartOExternalChanges="true" for that section. There's an example on MSDN that shows this in more detail by creating an external configuration file which is loaded via the configuration API (not referenced via configSource), then toggling the restartOnExternalChanges property and showing the differences in operation.
  • 24. Summary The ASP.NET Configuration system does quite a bit - I didn't even mention big topics like using the API for reading and writing values to both local and external config files or creating custom configuration sections. This post focuses on one aspect: getting things done by understanding and leveraging inheritance and overrides. Hopefully this gives you both some new tools for effectively handling configuration and some background that helps in troubleshooting when configuration is working as you'd 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 because of can't 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.config From Wikipedia, the free encyclopedia Jump to: navigation, search Web.config is the main settings and configuration file for an ASP.NET web application. The file is an XML document that defines configuration information regarding the web application.This file stores the information about how the web application will act. The web.config file contains information that control module loading, security configuration, session state configuration, and application language and compilation settings. Web.config files can also contain application specific items such as database connection strings. Contents 1 Inheritance 2 See also 3 References 4 External links Inheritance Each web application in ASP.NET inherits their base web.config from the machine's web.config located in System RootMicrosoft.NETFrameworkVersion Numbermachine.Config <!-- Web.Config Configuration File --> <configuration>
  • 25. <system.web> <customErrors mode="off"/> </ System.web> </ Configuration> ASP.NET Password Protected Login using the Session Object Although ASP.NET offers forms authentication for creating a password protected login system you 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 and password. When the asp button 'LoginButton' is clicked the click event is raised and the event handler 'Login' is called. This subroutine checks the text property of the Username and Password textbox controls to see if they match 'admin' and 'admin' respectively. If they do then a session Session("Admin") is created and set to True and the user is redirected to the 'default.aspx' page. If not then the Session is 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <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 If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Admin Log In</title> </head> <body> <form id="form1" runat="server"> <div>
  • 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 whether the session Session("Admin") is true or false. If it's false then redirect the user back to the login.aspx file. Default.aspx <%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <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 If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <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. </body> </html> Learn how to create an ASP.NET login with Forms Authentication. 10.3 Session State Maintaining state on behalf of each client is often necessary in Web applications, whether it is used 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 most flexible and, in general, the most efficient. ASP.NET has enhanced session state to address some of the problems associated with it in previous versions of ASP, including the abilities to host session 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 new client begins to interact with the application, a new session ID (or session key) is generated and associated with all subsequent requests from that same client (either using a cookie or via URL mangling). By default, the session state is maintained in the same process and AppDomain as your application, so you can store any data type necessary in session state. If you elect to house session state in another process or in a database, however, there are restrictions on what can be stored, as we will discuss shortly. Session state is maintained in an instance of the HttpSessionState class and is accessible through the Session property of both the Page and HttpContext classes. When a request comes in to an application, the Session properties of the Page and HttpContext class used to service that request are initialized to the current instance of HttpSessionState that is associated with that particular client. Listing 10-3 shows the primary methods and properties of the HttpSessionState class, along with the property accessors in both the Page and HttpContext classes. Listing 10-3: HttpSessionState Class public 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. 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 be populated and accessed using the standard array access notation that most developers are familiar with from traditional ASP. There are some new properties, however, including flags for whether the session key is being maintained with cookies or with mangled URLs (IsCookieless) and whether the session state is read-only (IsReadOnly). Also note that although the CodePage property is accessible through session state, this is for backward compatibility only. The proper way to access the response's encoding is through Response.ContentEncoding.CodePage. For an example of using session state, let's consider an implementation of the classic shopping cart for a Web application. As a user navigates among the pages of an application, she selects items to be retained in a shopping cart for future purchase. When the user is done shopping, she can navigate to a checkout page, review the items she has collected in her cart, and purchase them. This requires the Web application to retain a collection of items the user has chosen across request boundaries, which is exactly what session state provides. Listing 10-4 shows the definition of a class called Item. Instances of this class are used to represent the selected items in our shopping cart. Listing 10-4: Item Class public class Item { private string _description; private int _cost; public Item(string description, int cost) { _description = description; _cost = cost; } public string Description {
  • 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 state and 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 is the place to do so. Listing 10-5 shows a sample handler for the Session_Start event in our application object, which in our case is creating a new ArrayList and adding it to the session state property bag indexed by the keyword "Cart". Listing 10-5: Initializing Session State Objects // in global.asax public 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, two handlers are defined: one for purchasing a pencil and another for purchasing a pen. To keep things simple, the items and their costs have been hard-coded, but in a real application this information would normally come from a database lookup. When the user elects to add an item to her cart, the AddItem method is called. This allocates a new instance of the Item class and initializes it with the description and cost of the item to be purchased. That new item is then added 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 client's cart along 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. 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.cs public 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.cs public 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. 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 client across page boundaries in an application, and that the state is retained in memory on the server in the default session state configuration. 10.3.1 Session Key Management To associate session state with a particular client, it is necessary to identify an incoming request as having been issued by a given client. A mechanism for identifying a client is not built into the essentially connectionless HTTP protocol, so client tracking must be managed explicitly. In traditional ASP, this was always done by setting a client-side cookie with a session key on the first 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 when programmers used Globally Unique Identifiers (GUIDs) as session keys. Because the original algorithm for generating GUIDs was deterministic, if you knew one of the GUIDs generated by a server machine, you could guess subsequent GUIDs and thus access the session state associated with another client. Although GUIDs are no longer generated this way, ASP.NET takes the precaution of generating its own session keys by using the cryptographic service provider and its own encoding algorithm. Listing 10-10 shows some pseudocode demonstrating the technique used by ASP.NET for creating session keys. Listing 10-10: Session Key Generation in ASP.NET // Generate 15-byte random number using the crypto provider RNGCryptoServiceProvider 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. Using cookies to track session state can be problematic. Clients can disable cookie support in their 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 using client-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 URL and initializes the current session state pointer to the correct block of memory. This technique is demonstrated in Figure 10-2. This technique works even with clients that have disabled cookie support in their browsers. On any subsequent navigation, either via anchor tags or explicit programmatic 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 with all 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 session keys (along with several other session state–related features) is performed through the sessionState element in your application's web.config file. Table 10-2 lists the various configuration settings available for the sessionState element of web.config. Listing 10-11 shows a sample web.config file that enables cookieless session key management for an application. Table 10-2: sessionState Attributes Attribute Possible Values Meaning cookieless True, False Pass SessionID via cookies or URL mangling mode 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. The choice of whether to use cookie-based or mangled URL–based session key management must be made at the application level. It is not possible to specify that the application should use cookie-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 they avoid the redirection necessary to perform the URL mangling, although only one redirection per session will occur with URL mangling. Mangled URLs work with clients that don't have cookies enabled (or that don't support them). The mangled URL technique requires that your application avoid absolute URLs so that the mangling can take place properly. Finally, URL mangling also prevents easy bookmarking and thus may be an inconvenience for your users. 10.3.2 Storing Session State out of Process In addition to requiring cookies to track session state, traditional ASP only supported the notion of in-process session state. Confining session state to a single process means that any application that 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, where multiple machines are used to service requests independently, potentially from the same client. It also prevents the application from working correctly on a single machine with multiple host processes, sometimes referred to as a Web garden. If session state is tied to the lifetime of the Web server process, it is also susceptible to disappearing if that process goes down for some reason. To build traditional ASP applications that scale to Web farms and/or maintain persistent client-specific state, developers must avoid session state altogether and rely on other techniques for tracking client-specific state. The most common approach is maintaining client-specific state in a database running on a network-accessible server. To distinguish one client's state from another, 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 application's web.config file controls where session state is stored (see Table 10-2). The default location is in-process, as it was in traditional ASP. If the mode attribute is set to StateServer or SqlServer, however, ASP.NET manages the details of saving and restoring session state to another process (running as a service) or to an SQL Server database installation. This is appealing because it is possible to build ASP.NET applications that access session state in the normal way, and then by switching the sessionState mode in a configuration 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 anything placed into session state is serialized and passed out of the ASP.NET worker process. Thus, any type that is stored in session state must be serializable for this to work properly. In our earlier session state example, we stored instances of a locally defined Item class, which, if left in its existing form, would fail any attempts at serialization. The ArrayList class we used to store the instances of the Item class does support serialization, but since our class does not, the
  • 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 now compatible 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 page has 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 page may not need this level of state access (although it is somewhat configurable, as we will see), so there is still a valid case to be made for implementing your own custom client-specific state management system, even with ASP.NET. The first option for maintaining session state out of process is to use the StateServer mode for session state. Session state is then housed in a running process that is distinct from the ASP.NET worker process. The StateServer mode depends on the ASP.NET State Service to be up and running (this service is installed when you install the .NET runtime). By default the service listens over port 42424, although you can change that on a per-machine basis by changing the value of the HKLMSystemCurrentControlSetServicesaspnet_stateParametersPort key in the registry. Figure 10-4 shows the ASP.NET State Service in the local machine services viewer. 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 to install SQL Server on the machine hosting the state. Listing 10-13 shows an example web.config file that changes session state to live on server 192.168.1.103 over port 42424, and Figure 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="192.168.1.103:42424" /> </system.web> </configuration>
  • 35. The last option for storing session state outside the server process is to keep it in an SQL Server database. ASP.NET supports this through the SQLServer mode in the sessionState configuration element. Before using this mode, you must run the InstallSqlState.sql script on the database server where session state will be stored. This script is found in the main Microsoft.NET directory.15 The primary purpose of this script is to create a table that can store client-specific state indexed by session ID in the tempdb of that SQL Server installation. Listing 10-14 shows the CREATE statement used to create the table for storing this state. The ASP state table is created in the tempdb database, which is not a fully logged database, thus increasing the speed of access to the data. In addition to storing the state indexed by the session ID, this table keeps track of expiration times and provides a locking mechanism for exclusive acquisition of session state. The installation script also adds a job to clean out all expired session state daily. Listing 10-14: ASPStateTempSession Table CREATE 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 an SQL Server database on server 192.168.1.103. Notice that the sqlConnectionString attribute specifies 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=192.168.1.103;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—in internal data structures in memory for the state server, and in a VARBINARY field (or an IMAGE field if larger than 7KB) for SQL Server. While this is space-efficient, it also means that it cannot be modified except by bringing it into the request process. This is in contrast to a custom client-specific state implementation, where you could build stored procedures to update session key–indexed data in addition to other data when performing updates. For example, consider our shopping cart implementation shown earlier. If, when the user added an item to his cart, we wanted to update an inventory table for that item as well, we could write a single stored procedure that added the item to his cart in a table indexed by his session key, and then updated the inventory table for that item in one round-trip to the database. Using the ASP.NET SQL
  • 36. Server session state feature would require two additional round-trips to the database to accomplish the same task: one to retrieve the session state as the page was loaded and one to flush the session state when the page was finished rendering. This leads us to another important consideration when using ASP.NET's out-of-process session state feature: how to describe precisely the way each of the pages in your application will use session state. By default, ASP.NET assumes that every page requires session state to be loaded during page initialization and to be flushed after the page has finished rendering. When you are using out-of-process session state, this means two round-trips to the state server (or database server) for each page rendering. You can potentially eliminate many of these round-trips by more carefully designing how each page in your application uses session state. The session manager then determines when session state must be retrieved and stored by querying the current handler's session state requirements. There are three options for a page (or other handler) with respect to session state. It can express the need to view session state, to view and modify session state, or no session state dependency at all. When writing ASP.NET pages, you express this preference through the EnableSessionState attribute of the Page directive. This attribute defaults to true, which means that session state will be retrieved and saved with each request handled 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 you know 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 to manage session state on behalf of a given page. Figure 10-6 shows the various values of EnableSessionState and their effect on your Page-derived class. Easy way to create secure ASP.NET login using Session By 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 using Sessions See Also More like this More by this author Article Browse Code StatsRevisionsAlternatives 1.82 (10 votes)
  • 37. 10 Download SessionLogin.zip - 21.5 KB Introduction As an ASP.NET developer, I needed to create a secure login WebForm, but I also needed it to be easy to implement, not so complicated, and also accomplish the mission Sessions Sessions are a real important thing, that used in many things we can't even imagine. You can use sessions in passing variables between WebForms instead of query-strings when passing secure values, it can also be used to create secure, and easy login. Defining our Sessions In the file "Global.asax", We'll define our sessions in the function "Session_Start()" Collapse | Copy Code protected 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 before seeing them, we add just check if the user is Logged or not. Collapse | Copy Code private void Page_Load(object sender, System.EventArgs e) { if(Session["Logged"].Equals("No")) { .... } else
  • 38. { .... } } In the "Login.aspx" file, I've made checking the UserName and password with a regular if condition, with no database usage. But this code can be modified easily to check the Username and Password from a table in a database Collapse | Copy Code if(UserNametxt.Text.Trim()=="Abdallah" && Passwordtxt.Text.Trim()=="Fayez") { .... } else { .... } The Code is available to download, with a sample "Login.aspx", and "Default.aspx" WebForms which make it easier for you to modify the code in best shape for you. License This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here About the Author Abdallah Fayez Web Developer Egyptian Banks Co. United States Member