Feb 1, 2012

Using Session State in a Web Service

Introduction
In ASP.NET, there are two places in which we can store state information.
  • Application 
  • Session
In this article I am going to describe only session.
Session
Session stores data for each web user. The data about a user is also stored server side, but it can only be retrieved with a user GUID, which is stored client side using a cookie or modified URL. If the client application does not store the GUID persistently, then when the client application terminates, this state data is lost.
We have three ways to store session data.
  1. InProc : The default way; session data is stored in memory within the IIS process. Such an application does not scale – all the following user requests must be sent to the same server where the session data is stored. But it is the fastest.
  2. StateServer : Session data is stored in memory by a Windows service separate from IIS. Can be on a different server. This way the application is scalable. The second fastest.
  3. SqlServer : Store the session data in SQL server. Slowest but most reliable.
The mode can be InProcStateServer or SqlServerstateConnectionString is the URL of the machine running the state server, and sqlConnectionString is only used when you choose SqlServer option for mode. Timeout is the life span of the session data.
<=""             cookieless="false"             mode="InProc"             sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=yes"             stateconnectionstring="tcpip=127.0.0.1:42424"             timeout="10"     ="" <="" sessionstate ="" span="">
First we need a Web Service. I created a basic Web Service as.
Creating XML Web Service in .Net
Here is sample code I use to create and consume ASP.NET Web Services.
Example of Testing Web Service in .NetStep 1 : Create the ASP.NET Web Service Source File.
Open Visual Studio 2010 and create  a new web site.->Select .Net Framework 3.5. ->Select ASP.NET Web Service page -> Then, you have to give the name of your service. In this example I am giving it the name "MySessionEnabledWebService". Then click the OK Button. A screenshot of this activity is shown below.
img1.gif
Step 2 : Click on the "OK" button; you will see the following window.
img2.gif
Here (in the above figure), you will note that there is a predefined method "HelloWorld" which returns the string "Hello World". You can use your own method and can perform other operations.
Here I made a simple method "GetPerUserClickCount()" which returns an integer value.
Service.cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;namespace MySessionEnabledWebService
{
    /// 






    /// Summary description for Service1
    /// 

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod(EnableSession = true)]
        public int GetPerUserClickCount()
        {
            int count;
            if (Session["ConnectCount"] == null)
                count = 1;
            else
                count = (int)Session["ConnectCount"] + 1;
            Session["ConnectCount"] = count;
            return count;
        }
    }
}
Note: The key thing to do is to add (EnableSession = True) to the WebMethod tag. The rest of the code simply keeps track of how many times each client has called the Web Service method.
Side Note: I am using a Nullable Type to simplify the retrieving of Count from the Session collection.
if (Session["ConnectCount"] == null)
                count = 1;
            else
                count = (int)Session["ConnectCount"] + 1;
            Session["ConnectCount"] = count;
           
Step 3 : Build the Web Service and Run the Web Service for testing by pressing the F5 function key.
img3.gif
Copy the url of this web service for further use.
Step 4 : Click on the "GetPerUserClickCount" Button to test the web service.
img4.gif
Click on Invoke button to test the Web Service.
img5.gif
Refresh the browser or run again and again; in this Web Service we get the value in each hit from the user as.
img6.gif
img7.gif
and so on 4,5,6,7...
Step 5 : Create a Test Web Site by File > New > Web Site > ASP.Net Web Site.
img8.gif
Give a name to the web site; for example here I have chosen the name "MySessionTestWebApplication" and clicked on the "ok" button.
Step 6 : Right-click in the Solution Explorer and Choose "Add Web Reference":
img9.gif
Step 7 : Past the url of the web service and click on "Green arrow" button and then "Add reference".
img10.gif
Step 8 : Now your web service is ready for use. You can see it in the Solution Explorer.
img11.gif
Step 9 : Go to the design of the Default.aspx page; drag and drop one TextBox and one Button.
img12.gif
Rename the Button as PressMe.
Step 10 : Go to the Default.cs page and on the button click event use the following code:
protected void Button1_Click(object sender, EventArgs e)
    {
        localhost.Service1 Myservice = new localhost.Service1();
        TextBox1.Text=Myservice.GetPerUserClickCount().ToString();
    }
Step 11 : Pressing the F5 function key to run the website, you will see:
img13.gif
Hit the PressMe; we click the button a few times, but instead counting, we get this:
img14.gif
Discription
When an object is put into the Session collection, Asp.Net gives the caller an indentifying cookie behind the scene the SessionID. This is like when you check your coat at an expensive restaurant (I've heard) and you get a coat check ticket. When you go to get your coat back, you must have the ticket. So why isn't the proxy storing the SessionID as a cookie?
Point to Remember
The proxy generated doesn't have a CookieContainer.
Solution
Create a CookieContainer in the proxy (it already has a reference for it)
Here's the modified code.
protected void Button1_Click(object sender, EventArgs e)
{
    localhost.Service1 Myservice=new localhost.Service1();
    Myservice = Session["myservice"] as localhost.Service1;
    if (Myservice == null)
    {
        // create the proxy
        Myservice = new localhost.Service1();
        // create a container for the SessionID cookie
        Myservice.CookieContainer = new System.Net.CookieContainer();
        // store it in Session for next usage
        Session["myservice"] = Myservice;
    }
    TextBox1.Text=Myservice.GetPerUserClickCount().ToString();
}
All right, we hope the problem is solved because this is getting tiring. Fire up the web page Pressing the F5 function key, click the PressMe button a few times and...
img13.gif
img14.gif
img15.gif
img16.gif

And so on 4,5,6,7....
I hope you found this informative and helpful.

No comments:

Post a Comment

Search for