Exploring State Management In WebService

In this article, we will learn the common or most important state management techniques in WebService.

In this article, we will focus on the following things in detail.
  1. Introduction to state management.
  2. State Management in a Web Service.
  3. Session state management in a Web Service.
  4. Application state management in a Web Service.
  5. Caching in Web Service.
Introduction

In traditional Web programming, all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, the information would be lost in the round trip from the Browser or client device to the Server. Similarly if we want to store some internal information, data inside the Application will also be lost in each round trip or when we refresh the page.
 
To overcome this limitation of the traditional Web programming, ASP.NET includes several options that help you preserve data on both a client side as well as server side.

These techniques are commonly known as state Management.

As per my understanding "
State management is nothing but a temporary memory storage to store state of a page or imformation of a page against various Postback".

In ASP.NET, there are two types of state management techniques: Client side and Server side but in Web Service, we can have very limited state management techniques. Here in Web Services, we have only Server side State Management.

We have mainly three options of state management in the Web Services, which are shown below.
  • Session
  • Application
  • Caching
Session State Management in Web Service

The Web is stateless, which means a new instance of the Web page class is re-created, each time the page is posted to the Server. As we all know, HTTP is a stateless protocol, it can't hold the client information on a page. If the user inserts some information and moves to the next page or clicks any button or does any kind of Postback, the data will be lost and the user will not be able to retrieve the information. What do we need here? We need to store the information.
 
Hence, Session provides a facility to store the information on the Server memory. It can support any type of object to store along with our own custom objects. For every client, Session data is stored separately, which means Session data is stored on a per client basis.
For each session we have a unique block of memory allocated in the server. Session object is per client, which mean that different clients generate different Session objects.

To use ASP.NET Session object in a Web Service, there are two things, which we need to do which are shown below.
  1. The WebService class should inherit from System.Web.Services.WebService class.
  2. The EnableSession property of the WebMethod attribute should be set to true.
Hence, to work with Session state, let's create an empty ASP.NET project, as shown below.



Now, the second step is to add a Web Service file (.asmx) to the project, as shown below.



Now to work with Session, create a new method first and decorate it with the attribute [webMethod], as shown below.

Here, I will create a method, which will accept some product name and store it in Session, as shown below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6.   
  7. /// <summary>  
  8. /// Summary description for WebService  
  9. /// </summary>  
  10. [WebService(Namespace = "http://tempuri.org/")]  
  11. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  12. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  13. // [System.Web.Script.Services.ScriptService]  
  14. public class WebService : System.Web.Services.WebService  
  15. {  
  16.   
  17.     public WebService()  
  18.     {  
  19.   
  20.         //Uncomment the following line if using designed components   
  21.         //InitializeComponent();   
  22.     }  
  23.   
  24.     [WebMethod(EnableSession = true)]  
  25.     public string saveName(string pname)  
  26.     {  
  27.         List<string> li;  
  28.         if (Session["Name"] == null)  
  29.         {  
  30.             Session["Name"] = pname;  
  31.             return "Data saved successfully.";  
  32.   
  33.         }  
  34.   
  35.         else  
  36.         {  
  37.             Session["Name"] = Session["Name"] + "," + pname;  
  38.             return "Data saved successfully.";  
  39.         }  
  40.   
  41.   
  42.     }  
  43. }  
Here, I have described each line of the code, as shown below.



Now, we will create one more method to read all the products stored in the Session.
  1. [WebMethod(EnableSession = true)]  
  2.    public List<string> Display()  
  3.    {  
  4.        List<string> li1 = new List<string>();  
  5.        if (Session["Name"] == null)  
  6.        {  
  7.   
  8.            li1.Add("No record to display");  
  9.            return li1;  
  10.        }  
  11.   
  12.        else  
  13.        {  
  14.            string[] names = Session["Name"].ToString().Split(',');  
  15.            foreach (string s in names)  
  16.            {  
  17.                li1.Add(s);  
  18.            }  
  19.   
  20.            return li1;  
  21.        }  
  22.   
  23.    }  
Now, in this method, we are splitting all the data stored in the Session and showing each data, using foreach loop.

Here, the two Webservice methods are shown below.



Now, just click on saveName and insert some product name, as shown below.

 

After adding each product, please click Invoke button to store these products in the Session.

Now, we want to retrieve these products from the Session, so we will click Display Service, as shown below and press invoke button.


In this way, we can use a Session  in  the Web Service.

Application Object
  1. Web Server allocates a block of memory, which is common to all the users or clients, called an Application object.
  2. Application object does not timeout.
  3. The Application object  provides a mechanism to store the data and access the data throughout the Application.
By default, in the Web Service, the Application is Enabled, there is no need to enable it like Session.

Thus, let's try to work with the same example with an Application object in the Web Service. Here, I am creating the Web Method to save the data in an Application state, as shown below.
  1. [WebMethod]  
  2.     public string saveName(string pname)  
  3.     {  
  4.         List<string> li;  
  5.         if (Application["Name"] == null)  
  6.         {  
  7.             Application["Name"] = pname;  
  8.             return "Data saved successfully.";  
  9.   
  10.         }  
  11.   
  12.         else  
  13.         {  
  14.             Application["Name"] = Application["Name"] + "," + pname;  
  15.             return "Data saved successfully.";  
  16.         }  
  17.   
  18.   
  19.     }  
Now, here is the Web method to retrieve the data from an Application.
  1. [WebMethod]  
  2.   public List<string> Display()  
  3.   {  
  4.       List<string> li1 = new List<string>();  
  5.       if (Application["Name"] == null)  
  6.       {  
  7.   
  8.           li1.Add("No record to display");  
  9.           return li1;  
  10.       }  
  11.   
  12.       else  
  13.       {  
  14.           string[] names = Application["Name"].ToString().Split(',');  
  15.           foreach (string s in names)  
  16.           {  
  17.               li1.Add(s);  
  18.           }  
  19.   
  20.           return li1;  
  21.       }  
  22.   
  23.   }  
Here, we have used Application object in place of session. Please check it.

Thus, this Application data will appear until your WebServer is running because it does not have any timeout. Thus, it is mainly recommended to use when saving the data which is used .

Application object maintains its data till the Web Application is shut down.

CACHING IN Web Service
  1. It is a concept of storing frequently used data in local memory for faster access.This will reduce the time to regenerate the data once again.
  2. It is mainly used to improve the performance of the Application.
  3. If you want to cache a Web method in Webservice, we have a option of using  "CacheDuration" to cache the content.
  4. In cacheDuration attribute, we have to mention the duration in number of seconds for which we want to cache the content.
    1. [WebMethod(CacheDuration =60)]  
    2. public List<int> Display()  
    3. {  
    4.     List<int> li1 = new List<int>();  
    5.      
    6.   
    7.     for(int i=0;i<10000;i++)  
    8.     {  
    9.         li1.Add(i);  
    10.     }  
    11.   
    12.         return li1;  
    13.     }  
    Here is a simple Web method to have cache duration of 60 seconds in the WebService.
For more knowledge on caching in the Web Service, please click here. I hope you liked this article. If you know any new state management techniques, please update me, so that I will include it in the article.