Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » How to create Session

How to create Session

This artical show that what is session and how it create and reside on server.

Author Rank :
Page Views : 24817
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Session overview:

 

Session object is use to maintain the session state onto the server. Server creates unique session id for each browser. It executes on server and also resides on server. So the data stored into session will be secure. We can store object type (any type, any amount) data in the session. Default time for a session is 20 minutes but it can be change using the session state tag time out property in web config file.

 

For example-Suppose we want to set the time out property equals to forty then session will expire after forty minutes. Session tag use as follows:
 

<session state timeout=40/>.

 

Session variables are declared on fly that is no need for prior declaration. Session variable are used to maintain the session. By default session state managed in the IIS server known as inproc mode. Inproc sessions are very fast due to the existence in the same process domain. But we can also create the out process session having three possible modes. These are as follows:
 

  • Custom.
  • State secure.
  • Sql server.

We can also create the cookie less session. In which the session id is send back to the client with the help of the URL that is session id is pervaded into the URL Values are store in the session on bases of key.

 

Note: In .NET 2.0 by default session state is not manage by the server until we do not store any data in session state.

 

To manage the session:

 

We can see how the server manages the session id as follows:

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Button1_Click(object sender, EventArgs e)

    {

        Response.Write(Session.SessionID);

    }

}

This code is representing new session id at every time on button click or click on refresh the page and that will different each and every time

 

What is Postback property?

 

Postback is used to send back the web form on the web server with the data in its control for further processing. After processing on the server the page will be again loading into the memory. This whole process is known as the round tripping of the page.

 

For example:

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            Session["xx"] = "MCN";

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        Response.Write(Session.SessionID);

    }

}

 

This code is generating the unique session id. Here post back is send back the web form on the server for further processing. By default ispotstback property is false so is not postback is true.

 

Methods for removing item from session:

 

  • Session.Remove("xx");//delete an item from session state collection 
  • Session.RemoveAll();//remove all keys and values from the session state collection.
  • Session.RemoveAt(); //delete an item at specified index from the session state collection

Global.aspx:

For trapping the session we have .aspx file. global.aspx is used to trap the globaly event of the application. It contain eight methods used to trp the session.these are as follows:

  1.  Application_start()
  2.  Application_end()
  3. Session_start()
  4. Session_end()
  5. Application_begin request()
  6. Application_end request()
  7. Application_authentication request()
  8. Application_error() 
Create session:

 

Webform1.aspx: 

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <table cellpadding="0" cellspacing="0" border="2" width="60%" height="200px"><tr><td align="center" valign="top" style="padding-top:20px;">

    <asp:Label ID="lblname" runat="server" Text="Enter Name">

    </asp:Label>

    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>

    <br /><br />

    <asp:Label ID="lbladress" runat="server" Text="Enter Address"></asp:Label>

    <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>

   

    <br /><br />

    <asp:Button ID="btnsubmit" runat="server" Text="Submit"  OnClick="btnsubmit_Click"/>

    </td></tr></table>

    </div>

    </form>

</body>

</html>


 

Webform1.aspx.cs:

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class _Default : System.Web.UI.Page

{

    protected void btnsubmit_Click(object sender, EventArgs e)

    {

        Session["xx"] = txtname.Text;

        Session["yy"]=txtaddress.Text;

        Response.Redirect("Webform2.aspx");

    }

}

 

Webform2.aspx: 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Webform2.aspx.cs" Inherits="Webform2" %>

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

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div><table cellpadding="0" cellspacing="0" border="2" width="60%" height="200px"><tr><td align="center" valign="top" style="padding-top:20px;">

    <asp:Label ID="lblname" runat="server" Text="Name"></asp:Label>

    <asp:TextBox ID="txtaccessname" runat="server"></asp:TextBox>

    <br /><br></br>

    <asp:Label ID="address" runat="server" Text="Addres"></asp:Label>

    <asp:TextBox ID="txtaccessaddress" runat="server"></asp:TextBox>

    <br /><br />

   

    <asp:Button ID="btnaccessvalue" runat="server" Text="Click to Access value" OnClick="btnaccessvalue_Click" />

    </td></tr></table>

    </div>

    </form>

</body>

</html>


 

Webform2.aspx.cs:

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class Webform2 : System.Web.UI.Page

{

    protected void btnaccessvalue_Click(object sender, EventArgs e)

    {

        txtaccessname.Text = Session["xx"].ToString();

        txtaccessaddress.Text = Session["yy"].ToString();       

    }

}

   

This program is create for storing the name and address of the person in session.webform one is used for submit the information and another is used for access the information.we can store the large amount of data in the session. 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Purushottam Rathore

I am working as a Software Developer and has 4 years of experience on Microsoft Technology and having a Master Degree in Computer Application. I really like to work in the .NET platform. and working with ASP.NET 2.0/3.5, Web Services, WPF, WCF, Silverlight, AJAX, JavaScript, JQuery, Ado.net, MsAccess, SQL Server 2005/2008.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
hi by suhail On January 25, 2011
its really helpfull
Reply | Email | Modify 
this by bhagender On February 9, 2011
can u help me mujhe default.aspx page se navigate kartey huey default3.aspx page par sesison ke through data le jaana hai
Reply | Email | Modify 
Re: this by Purushottam On February 10, 2011
Hello dear Write the code on first page (Defult.aspx). Here I am taking a button (ButtonPage2) for redirect to another page. <div> <h3> Hi This is my first page.</h3> <asp:Button ID="ButtonPage2" runat="server" Text="Go on Second page" OnClick="ButtonPage2_Click" /> </div> Defult.aspx.cs: On the button's click event I am creating to two session Session["MyName"] and Session["PageName"] and redirect to second page. protected void Page_Load(object sender, EventArgs e) { } protected void ButtonPage2_Click(object sender, EventArgs e) { Session["MyName"] = "Hello! Puru"; Session["PageName"] = "This is my Second page"; Response.Redirect("~/Default2.aspx"); } Now Add new page as default2.aspx: Here I am taking two labels for bind the session's value. <div> <asp:HyperLink ID="HyperLinkHome" runat="server" NavigateUrl="~/Default.aspx">Home</asp:HyperLink><br /> <br /> <div> <asp:Label ID="LabelMyName" runat="server"></asp:Label><br /> <asp:Label ID="LabelPageName" runat="server"></asp:Label> </div> </div> Default2.aspx.cs: On the page load I am checking the session is not null and assign the values of the session to the labels. protected void Page_Load(object sender, EventArgs e) { if (Session["PageName"] != null) LabelPageName.Text = Session["PageName"].ToString(); if (Session["MyName"] != null) LabelMyName.Text = Session["MyName"].ToString(); } if you go direct on second page session will null so you will see nothing in these lables and if you will click on button of first page you will see the values of session in the labels.
Reply | Email | Modify 
bhagender singh by bhagender On February 11, 2011
sir meri niche di gayi coding work nahi kar rahi hai i odn knwo y can u pls help me out plsssss ///////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Mail; namespace smtp { public partial class Form1 : Form { public SmtpClient client = new SmtpClient(); public MailAddress msg = new MailAddress(); public System.Net.NetworkCredential smtcred = new System.Net.NetworkCredential("yuvrajprinceofheart@gmail.com","***********"); public Form1() { InitializeComponent(); } public void sendmail(string sentTo,string sendFrom,string subject,string body) { try { //smtp hostsetup client.Host = "smtp.gmail.com"; client.Port = 465; client.UseDefaultCredentials = false; client.Credentials = smtcred; client.EnableSsl = true; //convert string to mailaddress MailAddress to = new MailAddress(sentTo); MailAddress from = new MailAddress(sendFrom); //setupp message setting msg.Subject = subject; msg.Body = body; msg.From = from; msg.To.Add(to); //send mail client.Send(msg); } catch (Exception ex) { MessageBox.Show(ex.Message,"ERROR"); } } private void Form1_Load(object sender, EventArgs e) { } private void snd_email_Click(object sender, EventArgs e) { sendmail("yuvrajprinceofheart@gmail.com","yuvrajsingh@hotmail.co.in","hello dear i m yuvraj","yah it's works"); } } }
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.