Using Asynchronous Web Services

Throughout this book, each time a program has called a web service method, the program has suspended its execution until the method returned its result. Depending on the processing the web service performs, there may be times when such “synchronous” processing significantly degrades a program’s performance.

In the sections that follow, you will learn how to call a web service method asynchronously, meaning, the program can call the web service method and then continue its processing without having to wait for the method’s result. When the method later completes its processing, the method can signal the program by calling a specified function to notify the program that the processing is complete. The program, in turn, can then retrieve the method’s result (the return value).

As you will learn, the .NET environment makes it very easy for programs to call web service methods asynchronously. In fact, your programs can call any of the web services you have previously created using asynchronous operations!

Making Your First Asynchronous Call to a Web Service Method

The Delay web service in Listing 14.12 provides the DelayAndReturn method that receives a parameter that specifies the number of seconds the method should delay before returning its result. The method will return an integer value that corresponds to the delay interval. For example, if you pass the method the value 10 (for 10 seconds), the method will return the value 10.

To create the Delay web service, perform these steps:

  1. Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.

  2. 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 Delay. Select OK. Visual Studio .NET will display a page onto which you can drag and drop the service’s components.

  3. 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.12.

Listing 14.12 Delay web service

start example
<WebMethod()> Public Function DelayAndReturn(ByVal Seconds _ Ä   As Integer) As Integer    Dim Start As Long    Start = Now.Ticks    While (Now.Ticks - Start) < (Seconds * 10000000)    End While    DelayAndReturn = Seconds End Function
end example

The Visual Basic .NET program in Listing 14.13, CallDelay.vb, displays the form shown in Figure 14.7 that you can use to specify the delay interval (in seconds) and then to call the DelayAndReturn method either synchronously (the traditional method) or asynchronously (the callback method).

click to expand
Figure 14.7: Using a program to call web service methods synchronously or asynchronously

To create the CallDelay.vb program, perform these steps:

  1. Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.

  2. 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 CallDelay. 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).

  3. Using the Toolbox, drag and drop the buttons and text boxes previously shown in Figure 14.7 onto the form.

  4. Select the Project menu Add Web Reference option. Visual Studio .NET will display the Add Web Reference dialog box.

  5. Within the Address field, type localhost/Delay/Service1.asmx?WSDL and press Enter. The dialog box will load the file’s contents. Click your mouse on the Add Reference button.

  6. 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.13.

Listing 14.13 CallDelay.vb

start example
Dim WS As New localhost.Service1() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ Ä  System.EventArgs) Handles Button1.Click    Try      Dim DelayPeriod As Integer      DelayPeriod = Int32.Parse(TextBox1.Text)      Button1.Enabled = False      Button2.Enabled = False      TextBox3.Text = "Blocked, waiting for result"      Form1.ActiveForm.Refresh()      TextBox2.Text = WS.DelayAndReturn(DelayPeriod)      TextBox3.Text = "Waiting for user input"      Button1.Enabled = True      Button2.Enabled = True    Catch Ex As Exception      TextBox2.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 DelayPeriod As Integer     DelayPeriod = Int32.Parse(TextBox1.Text)     Button1.Enabled = False     Button2.Enabled = False     WS.BeginDelayAndReturn(DelayPeriod, AddressOf CallBackHandler, _     ÄNothing)     TextBox3.Text = "Off doing other processing"     Form1.ActiveForm.Refresh()   Catch Ex As Exception     TextBox2.Text = Ex.Message   End Try End Sub Private Sub CallBackHandler(ByVal Result As System.IAsyncResult)   TextBox2.Text = WS.EndDelayAndReturn(Result)   TextBox3.Text = "Received and processed asynchronous result"   Button1.Enabled = True   Button2.Enabled = True End Sub
end example

When you call a web service method asynchronously, you use a BeginMethodName method (such as BeginDelayAndReturn) to call the method. When you call the method, you must specify the method’s parameters followed by the address of the callback method that the web service will use to notify the program that it has completed its processing. In addition, you can specify a context object that provides the web service with additional information about the calling program (if you do not need to provide context information, you can pass the NULL or Nothing value):

WS.BeginDelayAndReturn(DelayPeriod, AddressOf CallBackHandler, _       Nothing)

Calling the LocateFile Web Service Asynchronously

In Chapter 13, “Unlocking Remote Access,” you created the LocateFile web service, shown in Listing 14.14, which you can use to search a remote disk for a specific file.

Listing 14.14 LocateFile.asmx.vb

start example
Imports System.IO Sub FindFile(ByVal Dir As String, ByVal File As String)    Dim DirObj As New DirectoryInfo(Dir)    Dim Files As FileInfo() = DirObj.GetFiles("*.*")    Dim Dirs As DirectoryInfo() = DirObj.GetDirectories("*.*")    Dim Filename As FileInfo    For Each Filename In Files      If (UCase(Filename.Name) = File) Then        FileLocation = Dir & "\" & File      End If    Next    If (FileLocation = "") Then      Dim DirectoryName As DirectoryInfo      For Each DirectoryName In Dirs        Try          FindFile(DirectoryName.FullName, File)        Catch E As Exception        End Try      Next    End If End Sub <WebMethod()> Public Function LocateFile(ByVal File As String) _ Ä  As String      FileLocation = ""    FindFile("C:\", UCase(File))    LocateFile = FileLocation End Function
end example

Depending on the number of files on the remote disk, the search operations may take considerable time. The Visual Basic .NET program in Listing 14.15, AsynchSearch.vb, displays the form shown in Figure 14.8 that you can use to call the LocateFile web service methods synchronously or asynchronously.

click to expand
Figure 14.8: Comparing synchronous and asynchronous operations for the time-consuming operations

If you click the Search Synchronously button, depending on the number of files on the server’s drive, the program may actually time out. Should a timeout occur, the form provides a text box that you can use to increase the timeout period. If you click the Search Asynchronously button, the program will call the method and immediately return. After the method locates the file or completes its search, the method will call back the program. To create the AsynchSearch.vb program, perform these steps:

  1. Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.

  2. 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 AsynchSearch. 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).

  3. Using the Toolbox, drag and drop the buttons and text boxes previously shown in Figure 14.8 onto the form.

  4. Select the Project menu Add Web Reference option. Visual Studio .NET will display the Add Web Reference dialog box.

  5. Within the Address field, type localhost/LocateFile/Service1.asmx?WSDL and press Enter. The dialog box will load the file’s contents. Click your mouse on the Add Reference button.

  6. 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.15.

Listing 14.15 AsynchSearch.vb

start example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ Ä System.EventArgs) Handles Button1.Click   If (TextBox1.Text.Length > 0) Then     Try       Button1.Enabled = False       Button2.Enabled = False       If (TextBox2.Text.Length > 0) Then         WS.Timeout = Int32.Parse(TextBox2.Text)       End If       TextBox3.Text = "Searching . . ."       Form1.ActiveForm.Refresh()       TextBox3.Text = WS.LocateFile(TextBox1.Text)       If (TextBox3.Text = "") Then         TextBox3.Text = "File not found"       End If       Button1.Enabled = True       Button2.Enabled = True     Catch Ex As Exception       TextBox3.Text = Ex.Message     End Try    Else      TextBox3.Text = "Must specify a target filename"    End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As _ Ä System.EventArgs) Handles Button2.Click   If (TextBox1.Text.Length > 0) Then     Try       Button1.Enabled = False       Button2.Enabled = False       WS.BeginLocateFile(TextBox1.Text, AddressOf CallBackHandler, _       Ä Nothing)       TextBox3.Text = "Off doing other processing"       Form1.ActiveForm.Refresh()     Catch Ex As Exception       TextBox2.Text = Ex.Message     End Try   Else     TextBox3.Text = "Must specify a target filename"   End If End Sub Private Sub CallBackHandler(ByVal Result As System.IAsyncResult)   TextBox3.Text = WS.EndLocateFile(Result)   If (TextBox3.Text = "") Then     TextBox3.Text = "File not found"   End If   Button1.Enabled = True   Button2.Enabled = True End Sub
end example

Again the processing the program performs to asynchronously call the web service method is the same as that just discussed. To begin, the program uses the BeginLocateFile method to call the remote method, passing the filename for which the method should search, the address of the callback method, and in this case, the value Nothing to signify that the program does not need to specify a context object:

WS.BeginLocateFile(TextBox1.Text, AddressOf CallBackHandler, _     Nothing)




. NET Web Services Solutions
.NET Web Services Solutions
ISBN: 0782141722
EAN: 2147483647
Year: 2005
Pages: 161
Authors: Kris Jamsa

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net