State Management Part 2 - Session

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

Last week, I wrote an article concerning View State. This week I' m going to talk about Session. Session is one of the most powerful and common ways to store information in an ASP.NET application. We are going to take a look at the benefits and choices we can get.

 

Getting Started

Session is another way to store information and, actually, a very handy one.  It comprises of the following aspects.
1) Session can be used in every page/ control within your website (unlike view state where every control had its own variables).
2) Every client has its own session.
3) Session is quite secure.
4) Session is stored in the server.
 
These aspects make session a widely used state management tool.
 

Session's Attributes

We'll do a proper session example later on. For the time being let's say that session stores values like a dictionary, similar to the way view state does. That is, like Session["Name"] = Value;
 
Suppose a user inserts its name on a TextBox ( "John" ) in the InsertUsernamePage.aspx and we store it in Session using Session["Username"] = "John"; When the user requests ShowUsernamePage.aspx or ShowUsernameOneMoreTimePage.aspx, these pages (and every other page our website contains) has access to the value "John".
 
Session has a timout attribute. This is by default set to 20 minutes. If the client makes no request during these 20 minutes, the session is cleared. The session will also be deleted if the client closes its browser or opens the same page from a different browser ( while the first is still open).
 
Every client has access to a unique session. To accomplish this, a cookie named ASP.NET_SessionId is stored in the client's browser. Using this SessionId the server can pick the part of the session assigned to the client. If we do not wish to use cookies, we can insert the attribute cookieless="UseUri" in the sessionState tag of our web.config file. Doing so, will cause the SessionID to be inserterd in the url. eg DotNetHintsBlog/(S(vsunqt5p1ntg00a3ka0x124g))/Session/Session.aspx
 
Stored in the server, session info is quite safely stashed as it cannot be the target of eavesdroppers during the communication part between the client and the server. However there is a small problem as we have to use a session ID and this can be stolen away. If a person got hold of that he could try to persuade the server he is you. To avoid this you should use encryption techniques in this cookie.
 
Session is stored in server. This way session can cause no overweight to the traffic between client and server but may affect the server's performance. This can be caused by an increased number of visitors in combination with with an increment to the session's timeout.
 
 

How to use session

Having said how session works let's give an example to make things clear. We are going to create three pages, part of a flight company which is well known for giving away tickets to customers for free as long as they pick their favourite travel location out of the company's website. In order to get the their tickets they have to go through two pages. In the first page they must pick the country and in the second page they must pick the city. Doing so, the third page will show a congratulations message announcing their travel destination. We will use session to store the selected values from the first and second page.
 
We create the first page containing the following aspx code
 
    Select the country you wish to visit:
    <br />
 
    <asp:DropDownList runat="server" ID="CountriesListID"  AutoPostBack="true"  OnSelectedIndexChanged="CountrySelected">
    <asp:ListItem Text="" Value="0" />
    <asp:ListItem Text="Italy" Value="1" />
    <asp:ListItem Text="France" Value="2" />
    <asp:ListItem Text="Greece" Value="3" />
    <asp:ListItem Text="United Kingdom" Value="4" />
    </asp:DropDownList>
 
In the cs file we insert the following method which will be called when we select the country.
   
   protected void CountrySelected(object sender, EventArgs e)
    {
        //Save value to Session and redirect to next page
        Session["Country"] = CountriesListID.SelectedItem.Text;
        Response.Redirect("CitiesSession.aspx");
    }
 
 
So, now we have stored the country value in session. We are now redirected to the CitiesSession.aspx page.
 
    Select the city you wish to visit:
    <br />
    <asp:DropDownList runat="server" ID="CitiesListID" AutoPostBack="true" OnSelectedIndexChanged="CitySelected">
        <asp:ListItem Text="" Value=""/>
    </asp:DropDownList>
 
containing the following cs code. To use a value from session we'll have to use casting first. In this example we are using the alternate method ToString().
 
protected void Page_Load(object sender, EventArgs e)
    {
        //Checking for postback is often used so that DropDownList controls are filled with ListItems only the first time they are requested 
        if (!IsPostBack)
            if(Session["Country"] != null)
            {
                // Page gets value that was inserted to Session in CountriesSession.aspx
                // Shows cities available to selected country
                string countryValue = Session["Country"].ToString();
                if(countryValue == "Italy")
                {
                    CitiesListID.Items.Add(new ListItem("Rome", "1_1"));
                    CitiesListID.Items.Add(new ListItem("Florence", "1_2"));
                }
                else if(countryValue == "France")
                {
                    CitiesListID.Items.Add(new ListItem("Paris", "2_1"));
                    CitiesListID.Items.Add(new ListItem("Cannes", "2_2"));
                }
                else if (countryValue == "Greece")
                {
                    CitiesListID.Items.Add(new ListItem("Athens", "3_1"));
                    CitiesListID.Items.Add(new ListItem("Mykonos", "3_2"));
                }
                else if (countryValue == "United Kingdom")
                {
                    CitiesListID.Items.Add(new ListItem("London", "4_1"));
                    CitiesListID.Items.Add(new ListItem("Birmingham", "4_2"));
                }
            }
    }
 
    protected void CitySelected(object sender, EventArgs e)
    {
        //Save value to Session and redirect to final page
        Session["City"] = CitiesListID.SelectedItem.Text ;
        Response.Redirect("CheckOut.aspx");
    }
 
 
The page will load only the cities located to the selected country. Ater selecting the city, its value will also be stored in session and we will be redirected to the final page CheckOut.aspx.
 
CheckOut.aspx contains the following piece of code.
 
    Congratulations, next week you are flying to 
    <asp:Literal runat="server" ID="CheckOutLitID" />
 
protected void Page_Load(object sender, EventArgs e)
    {
        string location = "";
 
        //Get Session values
        if (Session["City"] != null)
            location += Session["City"].ToString();
 
        if (Session["Country"] != null)
            location += " , " +  Session["Country"].ToString();
 
        CheckOutLitID.Text = location;
 
    }
 
 
 Since the company has become a major success as there are many people who like free tickets, it is a good idea to release some session space when we no longer need it. To do this we can use either Session.Abandon() or Session.Clear(). Using Abandon will let loose the session ID and thus remove the connection between the server session and the client, while Clear will simply empty the session.
 
 If we wanted to remove a single part of the session we could use Session.Remove("Country") or Session["Country"] = null which will do about the same thing. Remove will delete the reference while nullifying, will turn that session's content into null. 
 
 

 Why Session?

 Since all we wanted to do in the example, was to keep a small piece of information for a limited amount of time, session would be the best thing to choose. Session can also be effective to store trivia info like a user's ID when he is logged. If we wished to store info for a long time or to keep it safe for the user until next time he visited our website, session would not be a good idea. On the contrary, using cookies would be much more efficient. We' ll look at the way cookies work next time.
 
 

 Conclusion

 Session can become a very effective way to store state if used properly. It can be used in all pages and is quite safe to store info. It is one of the most common state management tools. Session is stored in the server.
 
 
 
 
 

Back to BlogPreviousNext

Comments



    Leave a comment
    Name: