1. Trang chủ
  2. » Công Nghệ Thông Tin

The book of visual basic 2005 net insight for classic vb developers 2006 - phần 10 docx

49 351 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 49
Dung lượng 919,62 KB

Nội dung

442 Chapter 13 Sometimes, a web service might move to a new URL after you create a client for it. In Visual Studio you can easily change the URL you use by selecting the web reference (under the Web References node in the Solution Explorer) and changing the Web Reference URL in the Properties window. But what do you if you’ve already deployed your client, and you don’t want to recompile it? Fortunately, .NET has the answer. Just look for the configuration file, which has the same name as your client (such as MyClient.exe.config). You can edit the configuration file with any text editor. Inside you’ll find the current setting, looking something like this: <setting name="PostalClient_localhost_PostalWebService" serializeAs="String"> <value>http://localhost/NoStarchWeb/PostalWebService.asmx</value> </setting> You can change this setting to update the web reference URL, without recompiling a lick of code. When you launch your client, it always uses the URL in the configuration file. Of course, if the web service changes more drastically—for example, the name of the web methods changes—you’ll need to modify your client application and recompile. Inspecting the Proxy Class Visual Basic 2005 hides the proxy class that it creates from you, because you don’t really need to see it or modify it directly. However, it’s always a good idea to peek under the hood of an application and get a better understanding of what’s really happening along the way. To see the proxy class, select Project Show All Files from the menu. Then, expand the Web References node, which contains all your web refer- ences. Expand the node with the web reference you just added (which is named localhost by default). Finally, look for a file named Reference.map. Once you expand this node, you’ll see the Visual Basic proxy file, which is named Reference.vb, as shown in Figure 13-12. This Reference.vb file includes a proxy class with all the code needed to call the methods of your web service. It also includes the ClientPackageInfo class that you need to use to retrieve the information from the GetPackageInfo() method. It’s important to understand that the Reference.vb file is constructed out of the public information about your web service. This information, which includes the method names, their parameters, and the data types they use, is drawn from the WSDL file. It’s impossible for a client to snoop out the internal details of a web service. For example, you won’t see the private GetPackageRecordFromDB() method in the proxy class, and you won’t find the Package class in the Reference.vb file, because they are only used internally. Similarly, you won’t be able to see (or learn anything about) the code inside your web service. If you could, that would constitute a significant security risk. bvb_02.book Page 442 Thursday, March 30, 2006 12:39 PM Web Services 443 Figure 13-12: The hidden proxy class Take a quick look at the modified version of the GetPackageInfo() function contained in the proxy class. (To simplify the display, the information in the SoapDocumentMethodAttribute is not included here.) <SoapDocumentMethodAttribute( )> _ Public Function GetPackageInfo(ByVal TrackID As String) As ClientPackageInfo Dim results() As Object = Me.Invoke("GetPackageInfo", _ New Object() {TrackID}) Return CType(results(0), ClientPackageInfo) End Function This function converts the TrackID input string into a generic object, retrieves the result as a generic object, and then converts it into the appropri- ate ClientPackageInfo object. In between, it accesses the web service through the appropriate SOAP request and waits for the response, although all this is taken care of automatically in the Me.Invoke() method, with the help of the .NET attributes that provide additional information to the Common Language Runtime. Using the Proxy Class The proxy class is the key to using a web service. Essentially, you create an instance of this class, and call the appropriate methods on it. You treat the proxy class as though it were a local class that contained the same functions and methods as the web service. bvb_02.book Page 443 Thursday, March 30, 2006 12:39 PM 444 Chapter 13 To try out the PostalWebService, add the following code to the Click event handler of a button: Private Sub cmdCallService_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCallService.Click Dim ServiceInstance As New localhost.PostalWebService() Dim PackageInfo As New localhost.ClientPackageInfo() PackageInfo = ServiceInstance.GetPackageInfo("221") MessageBox.Show("Received the delivery date: " & _ PackageInfo.DeliveryDate) End Sub Now run the application and click the button. If Visual Studio loads up the web service test page, you have a configuration problem. Stop the project, right-click the Windows application in the Solution Explorer, and select Set As Startup Project. If you have configured everything correctly, you’ll see the window in Figure 13-13. Figure 13-13: Calling a web service Once again, the technical details are pretty sophisticated, but the actual implementation is hidden by the .NET framework. Calling a web service is as easy as creating one, once you have set up the web reference. TIP There’s a handy shortcut for using the proxy class without needing to explicitly create it yourself. You can use VB’s built-in My.WebServices object. For example, to call the GetPackageInfo() method from the PostalWebService, you could use My.WebServices .PostalWebService.GetPackageInfo() . The proxy class is used in exactly the same way; the only difference is that you don’t need to instantiate it. Debugging a Web Service Project When debugging a solution that includes a web service project and client, you will find that any breakpoints or watches you set for the web service code are ignored. That’s because, by default, Visual Studio only loads the debug symbols for the startup project, which is the client. To solve this problem, you need to configure Visual Studio to load both projects at once. Right-click the solution name in the Solution Explorer (the first node), and select Properties. Then, browse to the Common Properties Startup Project tab and specify Multiple Startup Projects, so that both your client and the web service will be built when you click the Start button (Figure 13-14). Also, make sure that the Action column is set to Start for both projects. Then click OK. bvb_02.book Page 444 Thursday, March 30, 2006 12:39 PM Web Services 445 Figure 13-14: Starting the web service and client at the same time You still need to make one more change. By default, Visual Studio starts the web service project by displaying the web service test page. In this case, however, you don’t want any action to be taken other than loading the debug symbols so that the web service code is available for debugging. You don’t want to see the test page. To set this up, right-click the web service project, and select Property Pages. In the Start Options section, select “Don’t open a page. Wait for a request . . .” as your start action (Figure 13-15). Figure 13-15: Loading the web service debug symbols Click OK. You can now use the full complement of debugging tools, including breakpoints, with your web service and client code. bvb_02.book Page 445 Thursday, March 30, 2006 12:39 PM 446 Chapter 13 TIP You’re free to change your web service without breaking your client. As long as you only change the code inside an existing method, there’s no problem. However, if you add a new method, or change the signature of an existing method (for example, by renaming it or adding new parameters), the client won’t see your changes automatically. Instead, you need to rebuild your web service and then rebuild the proxy class. To rebuild the proxy class at any time, right-click the web reference in the Solution Explorer, and choose Update Web Reference. Asynchronous Web Service Calls You may have noticed that the proxy class actually contains more than just the GetPackageInfo() method. It also includes a GetPackageInfoAsync() method that allows you to retrieve a web service result asynchronously. For example, your code can submit a request with GetPackageInfoAsync(). That request will start processing on another thread. Meanwhile, your application can perform some other time-consuming tasks. When the result is ready, the proxy class will fire an event to notify you. This allows your program to remain responsive, even when waiting for a response over a slow Internet connection. Before going any further, you should modify the GetPackageInfo() web method so it runs more slowly. This makes the asynchronous behavior much easier to test. The easiest way to make this change is to add the following line of code to the GetPackageInfo() web method, which artificially delays execu- tion for 20 seconds: System.Threading.Thread.Sleep(TimeSpan.FromSeconds(20)) Now you’re ready to forge on and see how it all works. Asynchronous Support in the Proxy Class As you learned in Chapter 11, you can perform any task in .NET on a separate thread. However, the built-in support for asynchronous web services is a lot more convenient. When your web service finishes its work, you’re notified on the main application thread, which makes it safe to update controls and change variables. In other words, the asynchronous support in the proxy class allows you to dodge many of the threading headaches discussed in Chapter 11. In order for this system to work, the proxy class also adds an event for each web method. This event is fired when the asynchronous method is finished. Here’s what the event looks like for the GetPackageInfoAsync() method: Public Event GetPackageInfoCompleted As GetPackageInfoCompletedEventHandler And here’s the delegate that defines the event signature, which the proxy class also creates: Public Delegate Sub GetPackageInfoCompletedEventHandler( _ ByVal sender As Object, ByVal e As GetPackageInfoCompletedEventArgs) bvb_02.book Page 446 Thursday, March 30, 2006 12:39 PM Web Services 447 But wait, there’s more. The proxy class simplifies your life by creating a custom EventArgs object for every web method. This EventArgs object exposes the result from the method as a Result property. That way, when the asynch- ronous processing is finished and the completion event fires, you can use the GetPackageInfoCompletedEventArgs object and check its Result property to get the ClientPackageInfo object you’re interested in. If an error occurred contact- ing the web service (or in the web service code), you’ll receive an exception as soon as you try to retrieve this result, so be ready with some exception handl- ing code. An Asynchronous Client Example The easiest way to understand this pattern is to see it in action in an appli- cation. You can use your existing Windows client, and modify it to have asynchronous support. The first step is to attach the event handler so that you can receive the completion event. You should attach this event handler when the form first loads: Private Sub ClientForm_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Attach the event handler. AddHandler My.WebServices.PostalWebService.GetPackageInfoCompleted, _ AddressOf GetPackageInfoCompleted End Sub This example uses the default instance of the proxy class that’s exposed through the My.WebServices object. This is useful, because you need to make sure you use the same proxy object in all your event handlers. Another option is to create your own default instance as a form-level variable. NOTE It’s easy to make the mistake of attaching the event handler just before you make the call (for example, in the Click event handler for a button). Don’t do this. If you do, you’ll wind up attaching the same event handler multiple times, which means your event- handling code will be repeated several times in a row. You still need two more methods to complete this example. First, you need the event handler that triggers the asynchronous task when the user clicks a button. This is fairly straightforward. You simply need to tweak your code so it uses the asynchronous GetPackageInfoAsync() instead of GetPackageInfo(). Here’s what your code should look like: Private Sub cmdCallService_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCallService.Click ' Disable the button so that only one asynchronous ' call will be allowed at a time (this is optional). cmdCallService.Enabled = False ' Start the asynchronous call. ' This method does not block your code. bvb_02.book Page 447 Thursday, March 30, 2006 12:39 PM 448 Chapter 13 ' The second parameter can be any object you want. You must use the ' same parameter if you choose to cancel the request. ServiceInstance.GetPackageInfoAsync("Call001", "Call001") MessageBox.Show("Call001 has been started") End Sub Notice that when you call GetPackageInfoAsync() you need to supply a track- ing ID as a string. This allows you to uniquely identify the call, if multiple calls are taking place at once. You can generate a unique ID in your program using a random number or a GUID, but in this example there’s only one call, so the ID is hard-coded. The ID isn’t too useful at this point, but it becomes very handy when we consider cancellation in the next section. The last detail is the event handler that responds to the completion event, which is named GetPackageInfoCompleted() in this example. To complete this example, you’ll need to add that event handler to your form. Here’s the code you need: Private Sub GetPackageInfoCompleted(ByVal sender As Object, _ ByVal e As localhost.GetPackageInfoCompletedEventArgs) MessageBox.Show("Received the delivery date: " & e.Result.DeliveryDate) ' Re-enable the button for another call. cmdCallService.Enabled = True End Sub TIP Have no fear—web service completion events are always fired on the same form as the rest of your application. That means you don’t need to worry about interacting with other controls or synchronizing your code. Behind the scenes, the proxy class uses the BackgroundWorker component that you considered in Chapter 11. Now you’re ready to try out this example. When you click the button, the code will use the GetEmployeesAsync() method to start the asynchronous process. In the meantime, the form will remain responsive. You can try moving the form, minimizing and resizing it, or clicking other buttons to verify that your code is still running while the web service request is taking place. Finally, when the results are in, the proxy class fires the completion event, and a message box will appear alerting the user. (A more common action might be to use the information to update a portion of the user interface.) Canceling an Asynchronous Request The web service proxy class has one more feature in store—cancellation. It’s possible for you to halt a request in progress at any time using the CancelAsync() method. The trick is that you need to have the proxy object handy in order to call the method, and you need to use the tracking ID that you supplied when you first called the method. bvb_02.book Page 448 Thursday, March 30, 2006 12:39 PM Web Services 449 To change the current example to support cancellation, add a new button for cancellation. When this button is clicked, call the CancelAsync() method, using the same tracking ID: ServiceInstance.CancelAsync("Call001") There’s one catch. As soon as you call CancelAsync(), the proxy class fires its completion event. To prevent an error, you need to explicitly test for cancellation in your event handler, as shown here: Private Sub GetPackageInfoCompleted(ByVal sender As Object, _ ByVal e As localhost.GetPackageInfoCompletedEventArgs) If Not e.Cancelled Then MessageBox.Show("Received the delivery date: " & _ e.Result.DeliveryDate) End If ' Either way, re-enable the button for another call. cmdCallService.Enabled = True End Sub What Comes Next? This chapter has provided an overview of how web services work and how to use them. Leading-edge companies and developers have invented all kinds of imaginative web services. One example includes Microsoft’s Passport, which allows other companies to provide authentication using the engine that powers the Hotmail email system. If you want to continue learning about and working with web services, here are some interesting places to start: Microsoft provides a web services portal that provides such information as low-level technical information about the SOAP and WSDL standards, code samples of professional web services, and white papers discussing the best ways to design web services. Be warned—it’s highly technical. Check it out at http://msdn.microsoft.com/webservices. Eager to create a client for some sample web services? Try playing with the examples on www.xmethods.com, which provide currency exchange rates, stock quotes, and prime numbers. Most aren’t written in .NET, but you can still add a web reference to them and use them just as easily. Have some classic VB 6 applications kicking around? Remarkably, they don’t have to be left out of the party. Microsoft includes the SOAP Toolkit—a COM component that allows other applications (like VB 6) to contact web services (like those you create in .NET) and get the same information a .NET client would. Check it out by surfing to www.microsoft.com/downloads and searching for SOAP Toolkit. bvb_02.book Page 449 Thursday, March 30, 2006 12:39 PM 450 Chapter 13 Web services isn’t the only distributed object technology on the block. .NET also introduces a feature called remoting, which allows two .NET applications to interact over a network. Remoting is a strictly .NET solu- tion—cross-platform applications need not apply. It also doesn’t use IIS—instead, you need to launch an application that hosts the remotable object, and make sure it keeps running. However, remoting also adds a few features that web services doesn’t have, such as the ability for any application to act like a web server and receive requests from others. Also unlike web services, configuring remoting can be fiendishly diffi- cult (and forget about peer-to-peer applications on the Internet, because there’s no built-in way to get around firewalls and proxy servers). To learn more, check out a dedicated book or head to the Visual Studio Help. bvb_02.book Page 450 Thursday, March 30, 2006 12:39 PM 14 SETUP AND DEPLOYMENT If you’ve read through the last few chap- ters, you’ve gained the knowledge you need to make a professional, useful application in Visual Basic 2005. In fact, you may already have created one or more programs that you want to share with others, deploy internally, or even market to the world. But how does a .NET application make the transition from your workstation to a client’s computer? To answer that question, you need to have an understanding of assemblies, the .NET way of packaging files. You also need to understand file dependencies, or, “What does my program need to be able to run?” Both of these subjects were tackled in Chapter 7. Once you’ve learned which files you need, you can copy and set up your program on another computer. If the program is only being used internally (for example, from a company server), or if your only goal is to transfer the program from one development computer to another, you won’t need to do bvb_02.book Page 451 Thursday, March 30, 2006 12:39 PM [...]... that provide information about the destination computer All of these built-in properties are described in the Visual Studio Help Some of the most useful are COMPANY and USERNAME (which correspond to the information entered in the CustomerInformation window, if you are using it), LogonUser (the username of the currently logged-on user), ComputerName, PhysicalMemory (the number of megabytes of installed... You can burn them to a CD or copy them to some other location later Click Next 3 Choose the From A CD-ROM Or DVD-ROM option, which turns off the online-only features Click Next 4 In the last step, choose The Application Will Not Check For Updates to turn off the automatic updating feature (If, on the other hand, you want to make an application that is deployed by CD but can be updated via the web, you... (Figure 1 4-1 0) Figure 1 4-1 0: The setup designers Set up an d De pl oyme nt 463 bvb_02 .book Page 464 Thursday, March 30, 2006 12:39 PM NOTE You can also jump from one designer to another quickly by clicking one of the buttons in the Solution Explorer As long as you’ve selected your setup project, you’ll see one button for each designer In the next few sections, we’ll quickly explore each of these setup... all the metadata they need to identify themselves and their dependencies, they will still only work on another computer with the NET Framework If you copy your application to a computer that does not have the NET runtime, it won’t work And because you’re creating your application with NET 2.0, you need the NET 2.0 runtime—earlier versions are no help The easiest way to ensure that a computer is NET- ready... your application For example, add a new button Republish your application to the same location 4 5 460 Select the Before The Application Starts update mode 2 3 Run the application from the Start menu The application will detect the new version, and ask you if you’d like to install it (see Figure 1 4-7 ) If you accept the update, the new version will be installed and then launched bvb_02 .book Page 461 Thursday,... you can use the From A CD-ROM Or DVD-ROM option, which is described later in this chapter If you supplied a URL in Step 2, Visual Studio assumes that’s the final destination for your files Figure 1 4-2 : Specifying the final setup location 456 C h ap te r 1 4 bvb_02 .book Page 457 Thursday, March 30, 2006 12:39 PM 4 The next window (Figure 1 4-3 ) asks whether you want an online or an online/offline application... online/offline application runs whether or not the user can connect to the published location after the initial setup With this option, a user heads to the automatically generated install page (named publish.htm) and runs the setup A shortcut for the application is then added to the Start menu, and the user can subsequently run the application from there However, if you choose to create an online-only... March 30, 2006 12:39 PM Figure 1 4-1 6 shows a complete File Type entry To add a file type association like this, begin by right-clicking anywhere in the File Types designer and choosing Add File Type Before the file extension is considered complete, you must specify the following details: The name of the type of document (Name) The associated extension (Extension) The program to launch for the extension... administrative install To access the administrative install, you run the msi setup file with the /a command-line parameter Usually the administrative install is used if you need to provide a network setup To customize your setup, there are four tasks you can perform: Modifying options for a window, using the Properties window Rearranging the order of windows by right-clicking one of them and choosing Move Up... of SELECTEDBUTTON, and assigned the value 1 to one of the buttons (for example, Button1Value) This condition will only evaluate to true if the user chose the SELECTEDBUTTON with the value of 1 Conditions and choice windows provide a fairly crude way to manage user selections, but they are ideal for the simplified Setup Wizard application Always make sure that the choice window is displayed before the . default instance as a form-level variable. NOTE It’s easy to make the mistake of attaching the event handler just before you make the call (for example, in the Click event handler for a button). Don’t. runs the setup. A shortcut for the application is then added to the Start menu, and the user can subse- quently run the application from there. However, if you choose to create an online-only. Choose the From A CD-ROM Or DVD-ROM option, which turns off the online-only features. Click Next. 4. In the last step, choose The Application Will Not Check For Updates to turn off the automatic

Ngày đăng: 13/08/2014, 08:21

TỪ KHÓA LIÊN QUAN