Saturday, November 15, 2008

More on WS State Management

I tried to consume the Web service using a simple C# client by adding a web reference.

The code to call “PerSessionServiceUsage” was similar to follows:

private void buttonStateMgmtWithSession_Click(object sender, EventArgs e)

        {

            WebServiceRef.Service webService = new WebServiceRef.Service();

           

            int result;

 

            for (int i = 0; i <>

            {

                            

                result = webService.PerSessionServiceUsage();

 

                MessageBox.Show(result.ToString());

            }

        }

I was expecting the output to be equal to value of ( “variable i” + 1). But I was always getting result as 1!

Maintaining the session using cookies:

The Web service code does not see a valid session ID with the request, so it creates a brand new HttpSessionState object for each call, and returns the initial value of 1. The reason for this is that the client proxy class, which inherits from the System.Web.Services.Protocols.SoapHttpClientProtocol class does not have an instance of the System.Net.CookieContainer class associated with it. Basically, there is no place to store cookies that are returned.

Modifying the code as follows does the trick:

private void buttonStateMgmtWithSession_Click(object sender, EventArgs e)

        {

            WebServiceRef.Service webService = new WebServiceRef.Service();

            System.Net.CookieContainer Cookies = null;

 

            int result;

 

            for (int i = 0; i <>

            {

                if (Cookies == null)

                {

                    Cookies = new System.Net.CookieContainer();

                }

                webService.CookieContainer = Cookies;

                result = webService.PerSessionServiceUsage();

                MessageBox.Show(result.ToString());

            }

        }

Now, the result will be displayed as value of ( “variable i” + 1).

Default cookie container is not automatically associated with an instance of the SoapHttpClientProtocol class.

The same “CookieContainer” instance could be used by multiple instances of “SoapHttpClientProtocol” class.

No comments: