Maintaining Sessions in .NET Framework

Session in C#

This article will explain how to create sessions for your website, web portal or any other dynamic stuff using the .NET Framework along with Visual Studio and Microsoft SQL Server (any version; I am using VS 2010 and SQL Server 8).

Session | Basics

In general a session can be defined as the link or interface between our database and any dynamic content in the internet or networking.

A Session satifies the following requirements:

  • User Info
  • Maintenance
  • User Interaction with module
  • Some Security aspects
  • and so on

Session | Procedure

There are generally two steps in it (you need to have already created a database):

  • Coding in a .CS file page
  • Coding in page label



Session | Reference Example

Step 1

First of all we need to open a .cs file in Visual Studio, by following the process as shown below and then do the coding in it then save the file with the name ABC.cs.

Use the following procedure to start.



After clicking on the website option, a window like this will open:



In this window you have 2 choices; either you can go with Visual Basic or C#. My domain is C# so I prefer it. Now use the following procedure.



After clicking on OK, a blank page will open. On that blank page click on Solution Explorer and follow this:

  • On clicking Solution Explorer a window like this will appear:



  • Now right-click on C:\...\Website\
  • Then click on "Add" -> "New item ...".

An Add New Item window will appear as in the following:



Here search for the Class template and click on that. A “.cs” file will get generated. Now start coding there as in the following.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
   }
   protected void Button1_Click(object sender, EventArgs e)
   {
      Session.Add("Response",TextBox1.Text);
      Response.Redirect("profile.aspx");
   }
}

Step 2

Now create a .cs file for the label page. You can do that by extracting it from the Solution Explorer.

  • Click on Solution Explorer
  • Right-click on the .cs file
  • Extract file or label page

Now perform these coding steps in that label page.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class profile : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      // Label1.Text = Session["Response"].ToString();
      Label1.Text = Session["Response"].ToString();
   }
}

That’s all.


Similar Articles