Maintaining State with the Application Object

In contrast to the Session object, which provides a mechanism for storing data on a per-client basis, the Application object can be used to store and access any data that is specific to the Web application to which the Web Service belongs.

The Application object is very similar to the Session object with the exception that is does not manage Session IDs. Like the Session object, the Application object stores data in key-value pairs. Data stored in the Application object can be retrieved throughout the life of the Web application. This benefit is also a potential downfall of using the Application object—any data stored there will be kept in memory for the entire life of the application, therefore not allowing other processes to use the memory allocated.

The following is the syntax used to store data in the application object:

Application("Key") = Value

The following is the syntax used to retrieve data from the application object:

Value = Application("Key")

To see how the Application object is used within a Web Service, we will create a simple Web to store the number of searches that users have performed on specific criteria.

Add the following method to the StatefulService Web service created earlier:

<WebMethod()> _
Public Function Search (ByVal Criteria As String) As String
    If Application(Criteria) Is Nothing Then
        Application(Criteria) = 1
    Else
        Application(Criteria) = CInt(Application(Criteria)) + 1
    End If
    Search = Application(Criteria)
End Function

Notice that the implementation is very similar to the way Session State is managed. In fact, besides replacing all of the references to the Session object with a reference to the Application object, only one other change was made. The EnableSession attribute does not appear here. Because this WebMethod only uses the Application object, enabling the session for this WebMethod is unnecessary.

The method starts by checking whether a variable, with a key identical to criteria that was passed into the WebMethod, has already been stored in the Application object. Based on the outcome, the method either initializes the variable with the value of 1 or increments that variable by 1.

The following is a WebMethod that retrieves a specific search count from the Application object:

<WebMethod()> _
Public Function GetCount(ByVal Criteria As String) As Integer
    If Application(Criteria) Is Nothing Then
        GetCount = 0
    Else
        GetCount = CInt(Application(Criteria))
    End If
End Function

If you are familiar with traditional ASP or ASP.NET, you will have noticed that this is identical to the way the Application object is accessed within traditional ASP and ASP.NET Web forms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.93.20