Saturday, November 15, 2008

State Management in XML Web Service

A webservice may need to store data per session so that the data could be used in consequent calls by the same client.

XML Web services have access to state management options similar to ASP.NET applications when the XML Web service class derives from the “WebService” class. The common objects like Application and Session are included in “WebService” class.

To access and store state specific to the Web application hosting the XML Web service:

1.      Derive the XML web service class from “WebService”. A class deriving from “WebService” automatically has access to the “Application” object.

2.      In a web method, the state name and value could be stored in Application as follows:

Application["appMyServiceUsage"] = 1;

 

3.      The value of state stored in Application could be modified as follows:

Application ["appMyServiceUsage "] = ((int) Application ["appMyServiceUsage "]) + 1;

 

Code will look similar to follows:

 

using System.Web.Services;

public class ServerUsage : WebService

{

 

[WebMethod(Description = "Number of times this service has been accessed.")]

    public int ServiceUsage()

    {

        // If the Web service method hasn't been accessed,

        // initialize it to 1.

        if (Application["appMyServiceUsage"] == null)

        {

            Application["appMyServiceUsage"] = 1;

        }

        else

        {

            // Increment the usage count.

 Application["appMyServiceUsage"] = ((int)Application["appMyServiceUsage"]) + 1;

        }

        return (int)Application["appMyServiceUsage"];

    }

}

 

To access and store state specific to a particular client session:

 

1.      Derive the XML web service class from “WebService”

 

2.      Set “EnableSession” property of the “WebMethod” attribute to true

e.g. [ WebMethod(EnableSession=true) ]

 

3.      Store state name and value in the session

e.g. Session["MyServiceUsage"] = 1;

 

4.      The value could be accessed and modified as follows:

Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;

 

Code will look similar to follows:

 

using System.Web.Services;

public class ServerUsage : WebService

{

 

[WebMethod(Description = "Number of times a particular client session has accessed this Web service method.", EnableSession = true)]

    public int PerSessionServiceUsage()

    {

        // If the Web service method hasn't been accessed, initialize

        // it to 1.

        if (Session["MyServiceUsage"] == null)

        {

            Session["MyServiceUsage"] = 1;

        }

        else

        {

            // Increment the usage count.

            Session["MyServiceUsage"] = ((int)Session["MyServiceUsage"]) + 1;

        }

        return (int)Session["MyServiceUsage"];

    }

}

The web methods could be tested by navigating to .asmx page.

No comments: