12.1 Avoid Hard-Coding the XML Web Service URL


Problem

You need to use an XML Web service located at a URL that might change after you deploy the client application.

Solution

Use a dynamic URL, which will be retrieved automatically from the client application's configuration file. You can configure a dynamic URL in the URL Behavior section of a Web Reference's Properties in Microsoft Visual Studio .NET, or by using the /appsettingurlkey parameter with the Web Services Description Language tool (Wsdl.exe).

Discussion

By default, when you create a proxy class, the XML Web service URL is hard- coded in the constructor of the proxy class. You can override this setting in your code by manually modifying the Url property of the proxy class after you instantiate it. However, there's another option: configure the proxy class to use a dynamic URL endpoint.

In Visual Studio .NET, you can make this change by selecting the Web reference in the Visual Studio .NET Solution Explorer and changing the URL Behavior option in the Properties window, as shown in Figure 12.1.

click to expand
Figure 12.1: Configuring a dynamic XML Web service URL.

After you make this change, the XML Web service URL will be automatically added to the client application's configuration file. The configuration file is Web.config for all Web applications and [AppName].exe.config for all other applications, in which case the source appears in the design environment as simply App.config (and is renamed automatically by Visual Studio .NET). An example of the automatically generated configuration file setting is shown here:

 <?xml version="1.0" encoding="utf-8"?> <configuration>   <appSettings>   <  add key="AppName.ServerName.ServiceName"   value="http://localhost/WebServices/MyService.asmx"/  >   </appSettings> </configuration> 

You can also use a dynamic URL with a proxy class generated by Wsdl.exe. In this case, you use the /appsettingurlkey parameter to identify the name of the configuration setting where the URL will be stored. You must create the configuration file manually.

 wsdl /out:Proxy.cs http://localhost/WebServices/MyService.asmx?WSDL   /appsettingurlkey:MyService 

In either case, the code in the proxy class is modified so that it attempts to read the URL from the configuration file. If it doesn't find the required value, it defaults to the URL that was used during development. This approach allows you to modify the XML Web service URL after compiling and deploying the application, simply by editing the configuration file.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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