|
|
Across the Internet, browsers, proxy servers, and web servers make extensive use of caching to improve performance. Browsers, for example, will place the contents of the web pages that you visit into cache files on your hard drive. Should you revisit a site as you surf the Web, your browser can quickly retrieve the site’s contents from the disk cache, eliminating the browser’s need to again download the contents from across the Internet—a time-consuming operation. Most users understand the benefits of browser caching.
Across the Web, active server pages automate specific processing that controls the information a site displays. A simple active server page, for example, might display different content based on the time of day or the day of the week. Assume, for example, that such a website receives several hundred thousand hits per day. Rather than requiring the server to process the active server page contents for each hit, most web servers will instead cache the active server page’s first result and then use the cached contents to service subsequent requests.
When a server caches contents in this way, the server can specify a period of time for which the content in the cache is valid. If, for example, a site’s content changes daily, the server might invalidate (expire) the cache contents each night at midnight. After the content expires, the server will no longer return the data. Instead, the server will require that the active server page perform its processing to produce a new result.
To better understand server-side caching, consider the simple ASP.NET page in Listing 14.5, OneMinute.aspx. When you access the page for the first time, the page will take one minute to display its result (possibly a little longer than one minute depending on factors such as your connection speed); that’s because the page suspends its processing for 60 seconds before it returns its result. The second time you connect to the page, however, the server can quickly return the page’s contents because the server can return the cached contents without having to perform the page’s processing.
Listing 14.5 OneMinute.aspx
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As _ Ä System.EventArgs) Handles MyBase.Load Dim Start As Long Start = Now.Ticks While (Now.Ticks - Start) < 600000000 ' 60 seconds End While Response.Cache.SetCacheability(HttpCacheability.Public) Response.Cache.SetExpires(DateTime.Now.AddSeconds(600)) Response.Write("Page output at " & Now()) End Sub
To create the OneMinute.aspx ASP.NET page, 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 Application. Finally, within the Location field, specify the folder within which you want to store the program and the program name OneMinute. Select OK. Visual Studio .NET will display a page onto which you can drag and drop the program’s controls (label, buttons, and text box).
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 14.5.
To begin, the code delays for 60 seconds using a While loop. Next, the code issues the following statement to enable caching of its output:
Response.Cache.SetCacheability(HttpCacheability.Public)
Then, the code issues the following statement that directs the server to cache the page’s output for 10 minutes (600 seconds):
Response.Cache.SetExpires(DateTime.Now.AddSeconds(600))
Just as caching lets a server eliminate the need to execute an active server page’s contents each time users visit a site, caching can also reduce the server’s need to execute web service code.
The DelayedOuput web service in Listing 14.6, for example, provides the GetMessage method that returns a Hello message. Before the method returns the message, however, the method suspends its processing for 60 seconds. To create the DelayedOutput 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 DelayedOutput. 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 14.6.
Listing 14.6 DelayedOuput web service
<WebMethod()> Public Function GetMessage() As String Dim Start As Long Start = Now.Ticks While (Now.Ticks - Start) < 600000000 ' 60 seconds End While GetMessage = "Hello, at " & Now End Function
Next, the Visual Basic .NET program in Listing 14.7, GetMessage.vb, provides the form shown in Figure 14.4 that you can use to call the DelayedOutput web service. When you click the button, the program will call the service’s GetMessage method. After the method returns its result, the program will display the message within a text box.
Figure 14.4: Using the DelayedOutput web service to demonstrate the effects of not caching a web service’s output
In this case, because the web service does not direct the server to cache the web service’s output, each call to the GetMessage method requires the client program to wait 60 seconds. To create the GetMessage.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. Finally, within the Location field, specify the folder within which you want to store the program, and in the Name field type the program name GetMessage. Select OK. Visual Studio .NET will display a form onto which you can drag and drop the program’s controls (label, buttons, and text box).
Using the Toolbox, drag and drop the button and text box previously shown in Figure 14.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/DelayedOutput/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 14.7.
Listing 14.7 GetMessage.vb
Private Sub Button1_Click(ByVal sender As System.Object, _ Ä ByVal e As System.EventArgs) Handles Button1.Click Try Dim WS As New localhost.Service1() Button1.Enabled = False TextBox1.Text = WS.GetMessage() Button1.Enabled = True Catch Ex As Exception TextBox1.Text = Ex.Message End Try End Sub
To enable cached output for a web service, you must include the CacheDuration attribute within the Webmethod entry that precedes the code for a web service method. The CacheDuration attribute lets you specify, in seconds, the length of time a server can cache the method’s output. Because you can place or omit the CacheDuration attribute for each method, you can control web service caching on a method-by-method basis. The following statements, for example, direct the server to cache the output of the GetMessage method for 3 minutes (180 seconds):
<WebMethod(CacheDuration:=180)> Public Function GetMessage() As String Dim Start As Long Start = Now.Ticks While (Now.Ticks - Start) < 600000000 ' 60 seconds End While GetMessage = "Hello, at " & Now End Function
Change the DelayedOutput web service (Listing 14.6) code and recompile the service. Then, again run the GetMessage.vb program (Listing 14.7) and use the program to call the GetMessage method. Because the server will not cache the method’s output, the first call to the method will require 60 seconds to complete, but subsequent calls will immediately return a result.
Although caching a web service’s output can improve performance, depending on the processing a web service performs, disabling caching may make sense. For example, the CacheData web service in Listing 14.8 provides two methods that return a string that contains the server’s current date and time. The first method, OneMinuteCache, lets the server cache the method’s result for up to one minute. The second method, NoCache, returns the data without caching. To create the CacheData 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 CacheData. 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 14.8.
Listing 14.8 CacheData web service
<WebMethod()> Public Function NoCache() As String NoCache = "Server date and time is " & Now End Function <WebMethod(CacheDuration:=60)> Public Function OneMinuteCache() _ Ä As String OneMinuteCache = "Server date and time is " & Now() End Function
As you can see, the OneMinuteCache method uses the CacheDuration attribute to direct the server to cache its output for 60 seconds.
The Visual Basic .NET program in Listing 14.9, TestCache.vb, displays the form shown in Figure 14.5 that you can use to call each of the CacheData web service methods. When you click the Use Cached Data button, the program will call the OneMinuteCache method, the output of which the server caches for one minute. If you repeatedly click the button, the program will continue to call the method and the server will return the cached result, which will not correspond to the server’s current date and time.
Figure 14.5: Caching the results of a web service may lead to errant results.
In contrast, if you click the Don’t Use Cache button, the program will call the NoCache method, which does not use caching. As a result, each time you click the button, the server will execute the method and will return the server’s current date and time.
As you can see, in this case caching the web service’s data resulted in errant results being returned by server. Before you enable caching, you need to fully understand how caching a method’s output truly affects the output a client program will receive.
To create the TestCache.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. Finally, within the Location field, specify the folder within which you want to store the program, and in the Name field, type the program name TestCache. Select OK. Visual Studio .NET will display a form onto which you can drag and drop the program’s controls (label, buttons, and text box).
Using the Toolbox, drag and drop the button and text box previously shown in Figure 14.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/CacheData/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 14.9.
Listing 14.9 TestCache.vb
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ Ä System.EventArgs) Handles Button1.Click Try Dim WS As New localhost.Service1() Button1.Enabled = False TextBox1.Text = WS.OneMinuteCache() Button1.Enabled = True Catch Ex As Exception TextBox1.Text = Ex.Message End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As _ Ä System.EventArgs) Handles Button2.Click Try Dim WS As New localhost.Service1() Button2.Enabled = False TextBox2.Text = WS.NoCache() Button2.Enabled = True Catch Ex As Exception TextBox2.Text = Ex.Message End Try End Sub
The MathDemo web service in Listing 14.10 provides the Square and Cube methods. Both methods use a parameter to specify the value the calling program wants to manipulate. Again, to better demonstrate the effect of caching, the web service lets each method suspend its processing for 60 seconds before it returns the result. To create the MathDemo 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 MathDemo. 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 14.10.
Listing 14.10 MathDemo.asmx.vb
<WebMethod(CacheDuration:=180)> Public Function Square(ByVal Value _ Ä As Double) As Double Dim Start As Long Start = Now.Ticks While (Now.Ticks - Start) < 600000000 ' 60 seconds End While Square = Value * Value End Function <WebMethod(CacheDuration:=180)> Public Function Cube(ByVal Value _ Ä As Double) As Double Dim Start As Long Start = Now.Ticks While (Now.Ticks - Start) < 600000000 ' 60 seconds End While Cube = Value * Value * Value End Function
As you can see, both methods support caching. However, when a method uses parameters, how the server caches the method’s result will differ. In this case, if a program calls the Square method with the value 2, the method will perform its processing and return the value 4, which the server will cache. Should the program (or a different program) call the method with the value 2, the server will return the previously cached result. In contrast, if a program calls the Square method with a different parameter value, such as the value 3, the server will execute the method, which will return the value 9, which the server will then cache. At that time, the server will have values cached for the parameter value 2 and the parameter value 3.
The C# program in Listing 14.11, UseMathMethods.cs, provides the form shown in Figure 14.6 that you can use to invoke the Square and Cube methods with a specific value.
Figure 14.6: Understanding the effect of caching for methods that use parameters
To create the UseMathMethods.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. Finally, within the Location field, specify the folder within which you want to store the program, and in the Name field type the program name UseMathMethods. Select OK. Visual Studio .NET will display a form onto which you can drag and drop the program’s controls (label, buttons, and text box).
Using the Toolbox, drag and drop the buttons and text boxes previously shown in Figure 14.6 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/MathDemo/Service1.asmx?WSDL and press Enter. The dialog box will load the file’s contents. Click your mouse on 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 14.11.
Listing 14.11 UseMathMethods.cs
private void button1_Click(object sender, System.EventArgs e) { try { localhost.Service1 WS = new localhost.Service1(); double value = double.Parse(textBox1.Text); button1.Enabled = false; button2.Enabled = false; textBox2.Text = WS.Square(value).ToString(); button1.Enabled = true; button2.Enabled = true; } catch (Exception Ex) { MessageBox.Show(Ex.Message); } } private void button2_Click(object sender, System.EventArgs e) { try { localhost.Service1 WS = new localhost.Service1(); double value = double.Parse(textBox1.Text); button1.Enabled = false; button2.Enabled = false; textBox2.Text = WS.Square(value).ToString(); button1.Enabled = true; button2.Enabled = true; } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }
Throughout the previous sections, your programs have benefited from the use of output caching on the server side. In general, output caching is the process of storing the output of an active server page or the result of a web service for a specified duration.
Depending on the processing your programs perform, you may also want to take advantage of data caching, which places commonly used data items (such as a database table) into a cache from which a program or web service can quickly retrieve the data values (as opposed to having to perform a slower database operation).
The .NET environment provides library routines you can use to implement data caching. Because data caching is application specific, this chapter will not cover the steps you must perform to cache data. For more information on .NET support for data caching, visit the Microsoft website at www.Microsoft.com and then search for “.NET caching.”
Experiment with the UseMathMethods program, calling the Square and Cube methods with the same and different values. As you will see, if you call the service with a value you have previously passed, you will quickly receive your result. That’s because the server has cached the corresponding result. In contrast, if you call the methods with a new value, the methods will first delay 60 seconds before returning their result.
|
|