|
|
For years, active server pages have used the Application object to store application-based data, such as site-visit counters, database information (perhaps the name and location of a target database), and other application-specific settings, such as the page’s authentication requirements.
As you know, a web-based application often consists of multiple active server pages. The Application object lets a developer tie the pages together by storing data that is accessible to scripts on each of the application’s pages. In contrast to the Session object (discussed in the next section) that stores data for individual users, the Application object stores data that the application shares among all the users.
Web developers store values within the Application object by defining one or more variables the values for which the Application object stores. The following statement, for example, creates an Application object variable named ApplicationName and assigns the variable the value “Sample Page Demo”:
Application("Name") = "Sample Page Demo"
In a similar way, the following statement assigns the current date and time to an Application variable named StartDateTime:
Application("StartDateTime") = Now()
To retrieve a value stored within an Application object, you again simply specify the corresponding variable’s name. The following statement, for example, would display the name, date, and time values stored in the StartDateTime variable:
Response.Write(Application("StartDateTime"))
Likewise, the following statement assigns the value of the Application object’s name variable to a variable named ProgramName:
ProgramName = Application("Name")
You must keep in mind that all the users at a site share the Application object. To prevent two or more users who are accessing the site’s pages from trying to access the Application object’s variables at the same time—a situation that could lead to errors that are difficult to debug—developers use the Application object’s lock and unlock methods to control access to the object’s variables. Before a script accesses an Application object variable, the script should lock the object by calling the Application.Lock method. After the script is done with the object, it should call the Application.Unlock method as shown here:
Application.Lock() Application("Name") = "Sample Page Demo" Application.Unlock()
If another user runs a script that tries to access the Application object after the object has been locked, the script will suspend its processing until the script that locked the object unlocks it.
For example, the active server page in Listing 5.1, VisitCounter.asp, uses the Application object to implement a simple Web counter.
Listing 5.1 VisitCounter.asp
<html> <head> <title>Application Object Demo</title> </head> <body> <center><h1>Site Visit Counter Demo</h1></center> <h2> <% Application.Lock() Application("VisitCount") = Application("VisitCount") + 1 Response.Write("Number of visitors to this site is: " & _ Ä Application("VisitCount" )) Ä Application.Unlock() %> </h2> </body> </html>
Each time a visitor “hits” the page, the script retrieves and increments the value VisitCount variable, which the program has stored within the Application object. The script then displays the variable’s value, as shown in Figure 5.1.
Figure 5.1: Using the Application object to implement a site counter
When an active server page uses the Application to store data, the web server (such as Microsoft Internet Information Services, or IIS) stores the application’s data within memory. Should you restart the server, the information stored within the Application object would be lost.
To save and restore the Application object’s data, active server pages make use of a special file name global.asa (which resides in the same folder as the application), which contains the OnStart and OnEnd subroutines that define the processing the application performs each time it begins and ends. In addition, the global.asa contains similar subroutines that the application executes each time a user starts or ends a session. The file also contains optional directives that specify settings that control the script’s language, session and transaction support, and codepage information, as well as information regarding static objects created by the <Object> tag. Using the global.asa subroutines, an application might store (within a database or file) the Application object’s entries each time the application ends, and later restore the settings when the application starts. The statements in Listing 5.2 illustrate the contents of a typical global.asa file.
Listing 5.2 Global.asa
<SCRIPT LANGUAGE=VBScript RUNAT=Server> Sub Application_OnStart Application.Lock() Server("VisitCounter") = 0 Application.Unlock() End Sub ' Sub Application_OnEnd ' Put statements here 'End Sub Sub Session_OnStart Session("DateTime") = Now() End Sub 'Sub Session_OnEnd 'Put statements here 'End Sub </SCRIPT>
In this case, the global.asa file defines statements the application executes when it starts, which in this case initialize the VisitCounter variable, and statements the application executes each time a user creates a new session.
Within a web service, your code can access the Application object in a similar way. For example, the following Visual Basic .NET code fragment retrieves and increments a site counter using the Application object:
Dim Counter As Integer Application.Lock() Counter = Application.Item("VisitCount") Counter = Counter + 1 Application.Item("VisitCount") = Counter Application.UnLock()
To simplify program access to the Application object, the .NET environment defines the Application object. In other words, the .NET environment predefines an Application object and initializes the object’s members to values that correspond to the current application. As you can see, before the code accesses the VisitCount variable within Application object, the code uses the Lock method to prevent two or more uses of the code from accessing the object’s variables at the same time.
The following AppStateDemo web service tracks the total number of visitors over time who have used the service. The service supports the GetCounter method, which returns an integer value that corresponds to the use count:
integer GetVisitCount()
To create the AppStateDemo web service, perform these steps:
Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.
Within the New Project dialog box Project Types list, click Visual Basic Projects. Then, within the Templates field, click ASP.NET Web Service. Finally, within the Location field, specify the folder within which you want to store the program and the program name AppStateDemo. Select OK. Visual Studio .NET will display a page onto which you can drag and drop the service’s components.
Select the View menu Code option. Visual Studio .NET will display the program’s source code. Within the source code add the program statements in Listing 5.3.
Listing 5.3 AppStateDemo.asmx.vb
<WebMethod()> Public Function GetCounter() As Integer Dim Counter As Integer Application.Lock() If (Application.Item("VisitCount") Is Nothing) Then Application.Add("VisitCount", "1") Counter = 1 Else Counter = CType(Application.Item("VisitCount"), Integer) Counter = Counter + 1 Application.Item("VisitCount") = Counter End If Application.UnLock() GetCounter = Counter End Function
In this case, the code uses the If statement to determine whether or not the Application object has a VisitCount variable defined. If the variable does not exist, the code calls the Application object’s Add method to create the variable.
To retrieve the value of the VisitCount variable, the code calls the Application object’s Item method, passing to the method the variable’s name. The code uses CType to convert the string value the method returns to an integer value.
Next, the C# program, ViewApplicationData.cs, calls the ApplicationState web service methods and displays the current settings within a form, as shown in Figure 5.2.
Figure 5.2: Displaying a web service’s use count
To create the ViewApplicationData.cs program, perform these steps:
Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.
Within the New Project dialog box Project Types list, click C# Projects. Then, within the Templates field, click Windows Application. Within the Name and Location fields, type ViewApplicationData. Select OK. Visual Studio .NET will display a form onto which you can drag and drop the program’s controls.
Using the Toolbox, drag and drop the text box, label, and button previously shown in Figure 5.2 onto the form.
Select the Project menu Add Web Reference option. Visual Studio .NET will display the Add Web Reference dialog box.
Within the Address field, type localhost/AppStateDemo/Service1.asmx?WSDL and press Enter. The dialog box will load the file’s contents. Click the Add Reference button.
Select the View menu Code option. Visual Studio .NET will display the program’s source code. Within the source code add the program statements in Listing 5.4.
Listing 5.4 ViewAppData.cs
private void button1_Click(object sender, System.EventArgs e) { localhost.Service1 WS = new localhost.Service1(); try { textBox1.Text = WS.GetCounter().ToString(); } catch (Exception Ex) { textBox1.Text = Ex.Message; } }
The program’s processing is actually quite simple. The code creates the WS object that corresponds to the web service and then uses the object to call the GetCounter method, displaying the method’s result within a text box. The program uses a try-catch block to detect any exceptions the service may generate.
As you create programs that interact with a web service, there may be times when the program must retrieve the value of a variable the service stores within the Application object. The following ApplicationStateInfo web service provides methods a program can use to query a service. The first method, AllData, returns an array of character strings that contains the names of all the variables the service has stored within the Application object. The second method, GetData, returns the value of a specific variable:
String() AllData() String GetData(ByVal Key As String)
To create the ApplicationStateInfo web service, perform these steps:
Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.
Within the New Project dialog box Project Types list, click Visual Basic Projects. Then, within the Templates field, click ASP.NET Web Service. Finally, within the Location field, specify the folder within which you want to store the program and the program name ApplicationStateInfo. Select OK. Visual Studio .NET will display a page onto which you can drag and drop the service’s components.
Select the View menu Code option. Visual Studio .NET will display the program’s source code. Within the source code add the program statements in Listing 5.5.
Listing 5.5 ApplicationStateInfo.asmx.vb
<WebMethod()> Public Function AllData() As String() AllData = Application.AllKeys End Function <WebMethod()> Public Function GetData(ByVal Key As String) _ Ä As String Dim Found As Boolean = False Dim KeyName As String For Each KeyName In Application.AllKeys If (KeyName.ToUpper() = Key.ToUpper()) Then Found = True End If Next If (Found) Then GetData = Application.Get(Key) Else GetData = "Not Found" ' Generate exception End If End Function
The AllData method uses the Application object’s AllKeys property to return the array of strings that contains the names of all the variables the application has assigned to the Application object. By passing a variable’s name to the GetData method, a program can retrieve a specific variable’s value. Within the GetData method, the code converts the value passed to the method and each variable name to uppercase to simplify the matching processing. For simplicity, the code converts the KeyName variable to uppercase with each iteration of the loop. In practice, to improve performance, you should convert the contents of the KeyName variable to uppercase outside of the loop.
Earlier in this chapter, you learned that active server pages often use a special file named global.asa to specify code for the OnStart and OnEnd subroutines an application executes each time the application starts and ends. Within the .NET environment, the file has been renamed to global.asax to indicate the file’s support for ASP.NET pages that use the .aspx extension and web services that use the .asmx extension. The ServerVariable web service uses the OnStart subroutine within the global.asax file to assign several initial values to the ServerVariable object, as shown in Listing 5.6.
Listing 5.6 Global.asax
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the application is started Application.Add("Name", "ApplicationStateInfo") Application.Add("Publisher", "Sybex Computer Books") Application.Add("Author", "Kris Jamsa") Application.Add("Chapter", "5") End Sub
To edit the web service’s global.asax file, perform these steps:
Within Visual Studio .NET, open the Solution Explorer window.
Within the Solution Explorer window, double-click the Global.asax entry. Visual Studio .NET will display a page for the global.asax file.
Within the page, click the code view option. Visual Studio .NET will display the file’s contents as shown in Figure 5.3.
Figure 5.3: Editing a service’s global.asax file within Visual Studio .NET
The following Visual Basic .NET program, QueryApplicationData.vb, uses the ApplicationStateInfo web service to display the values the application has currently assigned to the Application variable and then to let the user query a specific variable’s value, as shown in Figure 5.4.
Figure 5.4: Querying a web service’s Application object’s variables
To create the QueryApplicationData.vb program, perform these steps:
Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.
Within the New Project dialog box Project Types list, click Visual Basic Projects. Then, within the Templates field, click Windows Application. Within the Name and Location fields, type QueryApplicationData. Select OK. Visual Studio .NET will display a form onto which you can drag and drop the program’s controls.
Using the Toolbox, drag and drop the text boxes, labels, and buttons previously shown in Figure 5.4 onto the form.
Select the Project menu Add Web Reference option. Visual Studio .NET will display the Add Web Reference dialog box.
Within the Address field, type localhost/ApplicationStateInfo/Service1.asmx?WSDL and press Enter. The dialog box will load the file’s contents. Click the Add Reference button.
Select the View menu Code option. Visual Studio .NET will display the program’s source code. Within the source code add the program statements in Listing 5.7.
Listing 5.7 QueryApplicationData.vb
Private Sub Button1_Click(ByVal sender As System.Object, _ Ä ByVal e As System.EventArgs) Handles Button1.Click Dim WebService As New localhost.Service1() Try If (TextBox2.Text.Length > 0) Then TextBox3.Text = WebService.GetData(TextBox2.Text) End If Catch Ex As Exception TextBox3.Text = Ex.Message End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ Ä ByVal e As System.EventArgs) Handles MyBase.Load Dim WebService As New localhost.Service1() Try Dim Entry As String For Each Entry In WebService.AllData() TextBox1.Text = TextBox1.Text & Entry & vbCrLf Next TextBox1.Select(1, 0) Catch Ex As Exception TextBox1.Text = Ex.Message End Try End Sub
Each time the program runs, the Form1_Load method will connect to the web service and retrieve and display the names of variables the service has assigned to the Application object. To display the value of a specific Application object variable, the user simply types the variable’s name within the second text box and clicks the button. The code, in turn, will call the service’s GetData method with the corresponding variable name, displaying the method’s result within a text box.
|
|