only for RuBoard |
The .NET SDK offers various tools that fall under four categories: Configuration and Deployment, Debugging, Security, and General Tools. Some command-line tools fall under the Configuration and Deployment category that you will find indispensable while you work with XML applications in the .NET Framework. These tools ease your job by performing some common tasks , such as generating code and deployment. This enables you to concentrate on the logic of your application.
All these tools are installed as part of the .NET, whether you install it as part of Visual Studio .NET or the .NET SDK. You can find the tools in the \Program Files\Microsoft.NET\FrameworkSDK\Bin directory. This path is added to the PATH system variable when you install .NET.
The XML Schema Definition tool generates XML Schema or common language run-time classes from XDR, XML, and XSD files, or from classes in a run-time assembly. It takes an argument to convert the input file. Table 4.1 lists the general tool options that can be used.
Option | Description |
---|---|
/h[elp] or /? | Displays command syntax and options for the tool. |
[/outputdir]:directory | Specifies the directory for output files. This argument can appear only once. The default is the current directory. |
Note
You can use shortcuts; for example, instead of typing /outputdir , you can type /o .
The following file types are accepted as input by the tool with their descriptions and syntax:
.xdr ” xsd.exe converts the XDR Schema file to an XSD Schema file with the same name as the XDR Schema.
xsd filename.xdr [/outputdir:directory]
XML Data Reduced (XDR) is an early XML Schema language proposed by Microsoft. Although earlier Microsoft products and parsers supported this format, now they all provide support for the W3C XML Schema 2001 Proposed Recommendation. Therefore, this option helps you greatly when you need to convert any existing XDR Schema files to XSD files.
.xml ” xsd.exe infers a schema from the data in the file and produces an XSD file with the same name as the XML file:
xsd filename.xml [/outputdir: directory ]
If you have an XML file, you can quickly generate an XML Schema file to validate the XML files. Just follow the same structure as the XML file. The tool tries to infer the parent-child relationship between the complex types in the XML file and generates additional ID columns for a Relation to work correctly. The tool defaults all data types to string .So, you can edit the generated XSD file to provide the specific data types required for your application.
.xsd ” xsd.exe generates source code for run-time objects that correspond to the XML Schema file that is provided as input:
xsd filename. xsd {/classes /dataset} [/element:element] [/language:language] [/namespace:namespace] [/outputdir: direc tory ] [URI: uri ]
Depending on whether you require a DataSet or a class, you can specify only one of the two options, /d or /c , as shown in Table 4.2.
.dll or .exe : xsd.exe generates schemas for one or more types in that assembly.
xsd { filename.dll filename.exe } [/outputdir: directory ] [/type:typename [...]]
Option | Description |
---|---|
/d[ataset] | Generates a class derived from DataSet that corresponds to the specified schema. To read XML data into the derived class, use the System.Data.DataSet.ReadXml method. |
/c[lasses] | Generates classes that correspond to the specified schema. To read XML data into the object, use the System.XML.Serialization.XMLSerializer.Deserializer method. |
/e[lement]:element | Specifies the element in the schema to generate code for. By default all elements are typed. You can specify this argument more than once. |
/l[anguage]:language | Specifies the programming language to use. Choose from CS (default),VB, or JS. You can also specify a fully qualified name for a class by implementing System.CodeDom.Compiler.CodeDomProvider . |
/n[amespace]:namespace | Specifies the run-time namespace for the generated types. The default namespace is Schemas . |
/u[ri]:uri | Specifies the URI for the elements in the schema for which to generate code. This URI, if present, applies to all elements specified with the /element option. |
/t[ype]:typename | Specifies the name of the type for which create a schema. You can specify multiple type arguments. If typename doesn't specify a namespace, xsd.exe matches all types in the assembly with the specified type. If type name specifies a namespace, only that type is matched. If typename ends with an asterisk character (*), the tool matches all types that start with the string preceding the *. If you omit the /type option, xsd.exe generates schemas for all types in the assembly. |
You can use the /type option to specify the types for which to generate schemas. The output schemas are named schema0.xsd , schema1.xsd , and so on. Xsd.exe produces multiple schemas only if the given types specify a namespace using the XMLRoot custom attribute.
Take a look at a few simple examples of using the xsd.exe tool, described in the next section.
Listing 4.1 is a simple XDR file that is passed as an input.
<?xml version="1.0" ?> <Schema xmlns = "urn:schemas-microsoft-com:xml-data" xmlns:dt = "urn:schemas-microsoft-com:datatypes"> <ElementType name = "Customer" content = "eltOnly" order = "seq" > <element type = "CompanyName" minOccurs="1" maxOccurs="1" /> <element type = "ContactName" minOccurs="1" maxOccurs="1" /> </ElementType> <ElementType name = "CompanyName" content = "textOnly" order ="seq" /> <ElementType name = "ContactName" content = "textOnly" order = "seq" /> </Schema>
Running the xsd.exe , as shown in Figure 4.32, generates the Customer.xsd file and writes it to the current directory, which is the default. To specify a different directory, you can use the /o[utputdir] option.
The screenshots in this chapter show the Visual Studio .NET command prompt. You can optionally choose to run the command-line tools in a DOS command window if you do not have the Visual Studio .NET installed. Listing 4.2 is the XSD file generated by the xsd.exe tool.
<?xml version="1.0" encoding="utf-8"?> <xsd:schema id="NewDataset" targetNamespace="" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="NewDataset" msdata:IsDataset="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="Customer"> <xsd:complexType> <xsd:sequence> <xsd:element name="CompanyName" type="xsd:string" /> <xsd:element name="ContactName" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
Listing 4.3 is a simplified form of the Customers.xml file.
<?xml version="1.0" encoding="utf-8" ?> <Customers> <Customer id="ALFKI"> <CompanyName>Alfreds Futterkiste</CompanyName> <Contact> <FirstName>Maria</FirstName> <LastName>Anders</LastName> <Title>Sales Representative</Title> </Contact> </Customer> </Customers>
Running the xsd.exe tool as follows generates an XSD file with the name Customers.xsd :
XsdCustomers.xml
Listing 4.4 is the XSD file that is generated.
<?xml version="1.0" encoding="utf-8"?> <xs:schema id="Customers" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="Customers" msdata:IsDataset="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Customer"> <xs:complexType> <xs:sequence> <xs:element name="CompanyName" type="xs:string" minOccurs="0" msdata:Ordinal="0" /> <xs:element name="Contact" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="FirstName" type="xs:string" minOccurs="0" /> <xs:element name="LastName" type="xs:string" minOccurs="0" /> <xs:element name="Title" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:string" /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema>
The following command generates a DataSet from the XSD file Customers.xsd that was generated from Customers.xml (refer to Listing 4.4):
Xsd Customers.xsd /d /l:VB
This generates the source code for the DataSet with the filename Customers.vb . Refer to Chapter 8 for a detailed discussion on DataSet . Figure 4.33 shows the DataSet class Customers as viewed in the Object browser of a Visual Basic .NET class library project. Note that, for the reason of space, the Customers.vb file was converted into assembly to provide a quick view of the Customers class.
The tool can only process schemas, which reference the www.w3.org, March 16, 2001, XML Schema Specification. Chapter 2, "XML Schemas in .NET," provides more detailed samples of generating classes from an XSD file.
Consider Listing 4.5, which contains the code in the C# file class1.cs . Compile this to have the assembly OrderInvoice.dll . Alternatively, you can create an executable for this example. The following command compiles the class1.cs file into the assembly OrderInvoice.dll :
csc /out:OrderInvoice.dll /target:library class1.cs
using System; using System.Xml.Serialization; /* Applying the XmlTypeAttribute to a class instructs the xsd.exe tool about the XML type's namespace, the XML type name, and whether to include the type in the XML schema document. */ [XmlType(Namespace = "http://www.mydomain.com", TypeName = "USAddress")] public class Address { /* Setting the IsNullable property to false instructs the xsd.exe tool to in turn set the 'nillable' property of the element to false in the generated schema*/ [XmlElementAttribute(IsNullable = false)] public string Street; [XmlElementAttribute(IsNullable = false)] public string City; [XmlElementAttribute(IsNullable = false)] public string State; [XmlElementAttribute(IsNullable = false)] public string Zip; } public class Invoice { [XmlElementAttribute(IsNullable = false)] public Person Customer; [XmlElementAttribute(IsNullable = false)] public Address ShippingAddress; [XmlElementAttribute(IsNullable = false)] public Order[] Orders; } public class Person { [XmlElementAttribute(IsNullable = false)] public string FirstName; [XmlElementAttribute(IsNullable = false)] public string LastName; } public class Order { /* The XmlAttribute instructs the xsd.exe tool to generate the Qty field as an XML attribute instead of an XML element (the default behavior). Secondly, explicitly setting the AttributeName to 'Quantity' specifies that the Qty field should be encoded with the name Quantity*/ [XmlAttribute (AttributeName = "Quantity")] public int Qty; [XmlElement (ElementName = "ProductName", IsNullable = false)] public string ItemName; [XmlElementAttribute(IsNullable = false)] public string ShipDate; }
The comments in the preceding code explain how you can use the different attributes of the System.Xml.Serialization namespace to give some hints to the xsd.exe tool about the schema generation. These attributes are the same that you would use to instruct the XmlSerializer on how objects are encoded into XML. You can find a more detailed discussion on XML serialization and the System.Xml.Serialization. XmlSerializer class in Chapter 10, "XML Serialization."
Pass this assembly file to the xsd.exe tool and the tool generates two schema files, schema0.xsd and schema1.xsd , as shown in Figure 4.34.
Listing 4.6 and Listing 4.7 contain the code for the generated schema files.
<?xml version="1.0" encoding="utf-8"?> <xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:import namespace="http://www.mydomain.com" /> <xs:element name="USAddress" nillable="true" xmlns:q1="http://www.mydomain.com" type="q1:USAddress" /> <xs:element name="Invoice" nillable="true" type="Invoice" /> <xs:complexType name="Invoice"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" name="Customer" type="Person" /> <xs:element minOccurs="0" maxOccurs="1" name="ShippingAddress" xmlns:q2="http://www.mydomain.com" type="q2:USAddress" /> <xs:element minOccurs="0" maxOccurs="unbounded" name="Orders" type="Order" /> </xs:sequence> </xs:complexType> <xs:complexType name="Person"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" name="FirstName" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="1" name="LastName" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:complexType name="Order"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" name="ProductName" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="1" name="ShipDate" type="xs:string" /> </xs:sequence> <xs:attribute name="Quantity" type="xs:int" /> </xs:complexType> <xs:element name="Person" nillable="true" type="Person" /> <xs:element name="Order" nillable="true" type="Order" /> </xs:schema>
<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:tns="http://www.mydomain.com" elementFormDefault="qualified" targetNamespace="http://www.mydomain.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="USAddress"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" name="Street" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="1" name="City" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="1" name="State" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="1" name="Zip" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema>
Web service discovery is the process of locating and interrogating web service descriptions. You can read more about web services and the web services description and discovery process in Chapter 11. Potential web-service clients can learn that a web service exists and how to interact with it by performing a discovery. When you are creating a web service client, this web services discovery tool ( Disco.exe ) helps you to discover these URLs of web services located on a web server and save the documents related to each web service on the local disk. Then you can also use the .wsdl , .xsd , .disco , and .discomap files produced by this tool as input to the web services description language tool ( Wsdl.exe ) to create web-service clients.
This syntax is for use of this command-line tool:
disco [options] URL
The URL in the argument is the discovery document ( .wsdl , .xsd , .disco , and .discomap files) for which the tool needs to discover and produce published discovery documents.
Table 4.3 lists the available options for this tool.
Option | Description |
---|---|
/d[omain]:domain | Specifies the domain name to use when connecting to a proxy server that requires authentication. |
/nosave | Does not save the discovered documents or results ( .wsdl , .xsd , .disco , and .discomap files) to disk. The default is to save these documents. |
/nologo | Suppresses the Microsoft start-up banner display. |
/o[ut]:directoryName | Specifies the output directory in which to save the discovered documents. The default is the current directory. |
/p[assword]:password | Specifies the password to use when connecting to a proxy server that requires authentication. |
/proxy:URL | Specifies the URL of the proxy server to use for HTTP requests . The default is to use the system proxy setting. |
/proxydomain:domain or | Specifies the domain to use when connecting to a proxy server that requires authentication. |
/pd:domain | |
/proxypassword:password or | Specifies the password to use when connecting to a proxy server that requires authentication. |
/pp:password | |
/proxyusername:username or | Specifies the username to use when connecting to a proxy server that requires authentication. |
/pu:username | |
/u[sername]:username | Specifies the username to use when connecting to a proxy server that requires authentication. |
/? | Displays command syntax and options for the tool. |
Assume that your web server exposes the two web services: a news update service described by the Web Services Description Language (WSDL) document available at http://localhost/MyWebServices/NewsService.asmx?wsdl and a stock quote service described by the WSDL document at http://localhost/MyWebServices/StockQuoteService.asmx?wsdl .
Listing 4.8 is an example of a .disco file that contains the links to the preceding two web service descriptions.
<?xml version="1.0" encoding="utf-8" ?> <disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/" xmlns:scl="http://schemas.xmlsoap.org/disco/scl/"> <scl:contractRef ref="http://localhost/MyWebServices/NewsService.asmx?wsdl" docRef="http://localhost/MyWebServices/NewsService.asmx" /> <scl:contractRef ref="http://localhost/MyWebServices/StockQuoteService.asmx?wsdl" docRef="http://localhost/MyWebServices/StockQuoteService.asmx" /> </disco:discovery>
Running the tool, as shown in the following code line, generates and saves the four documents, StockQuoteService.wsdl , NewsService.wsdl , MyWebservices.disco , and results.discomap , to a subfolder named DISCO- FOLDER :
disco /o:DISCOFOLDER http://localhost/MyWebServices/MyWebServices.disco
Figure 4.35 shows the tool in action.
If the tool cannot find discoverable resources at the specified URL, you see an error message displayed in the Command window.
Of the four XML documents generated, the MyWebservices.disco is a copy of the MyWebservices.disco that was provided as an input to the tool; the files StockQuoteService.wsdl and NewsService.wsdl are the WSDL contract files that you will use with the wsdl.exe tool to generate the client proxies for the web service; finally, results.discomap is generated by the tool and contains the mapping between the files saved on the local disk and the original documents on the web server. Listing 4.9 contains the contents of the results.discomap file.
<?xml version="1.0" encoding="utf-8"?> <DiscoveryClientResultsFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Results> <DiscoveryClientResult referenceType="System.Web.Services.Discovery. DiscoveryDocumentReference" url="http://localhost/MyWebservices/MyWebservices.disco" filename="MyWebservices.disco" /> <DiscoveryClientResult referenceType="System.Web.Services.Discovery.ContractReference" url="http://localhost/mywebservices/NewsService.asmx?wsdl" filename="NewsService.wsdl" /> <DiscoveryClientResult referenceType="System.Web.Services.Discovery.ContractReference" url="http://localhost/mywebservices/StockQuoteService.asmx?wsdl" filename="StockQuoteService.wsdl" /> </Results> </DiscoveryClientResultsFile>
A .discomap file is similar to a .disco file published by the web service and contains links to other resources that describe the web service. You can only specify the file path and not a URL to a .discomap discovery document with the Wsdl.exe tool. The document results.discomap , generated by the tool, can only be used on the client as an input to the Wsdl.exe to create web-service clients.
If you have created a web service project using Visual Studio .NET, you can see the < Web Sevice Name> . vsdisco auto-generated by the IDE. You can get the same results by using this file with the disco.exe as an alternative to the .disco file. You can use this on the server to get the .disco file generated for you and publish it for the clients. Listing 4.10 is a sample .vsdisco file that's generated by the IDE.
<?xml version="1.0" ?> <dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17"> <exclude path="_vti_cnf" /> <exclude path="_vti_pvt" /> <exclude path="_vti_log" /> <exclude path="_vti_script" /> <exclude path="_vti_txt" /> <exclude path="Web References" /> </dynamicDiscovery>
When a client requests this file, the server dynamically checks for the available web services and returns the discovery information rather than returning the preceding file contents. This contains the list of web services in the current folder and any .disco files available in the subfolders . You can see the results by typing the URL in the address location of a web browser, as shown in Figure 4.36.
If you are aware of the web service URL and you want the corresponding disco file, you can get it simply by appending ?disco , just as you did to get the WSDL file for a web service.
If you want prospective consumers of your web service to not have to know the name of any discovery documents during the discovery process, you can do so by adding a link to the default page for the Internet Information Server (IIS) application. First, set a default page for the IIS application in the Properties dialog box from the IIS Microsoft Management Console (MMC) snap-in (see Figure 4.37).
You can then add a link to the discovery document in the <HEAD> tag of the default web page for the web server, as shown in the following code:
<HTML> <HEAD> <LINK type='text/xml' rel='alternate' href='MyWebServices.disco' /> </HEAD> <BODY> <H1>My Web Services Default Page</H1> </BODY> </HTML>
Now it is possible for the clients to provide the URL input to the disco.exe tool:
disco http://localhost/MyWebServices
If you set the default page for the web application as an XML document, you need to place the following code at the top of this document:
<?xml-stylesheet type="text/xml" alternate="yes" href="MyWebServices.disco" ?>
The WSDL tool generates code for web services and web-service clients from WSDL contract files, XSD Schemas, and .discomap discovery documents. The following is the syntax to run the wsdl.exe tool:
wsdl [options] {URL path}
The URL or path can be a WSDL contract file ( .wsdl ), XSD schema file ( .xsd ), or discovery document ( .disco ). A .discomap discovery document can be specified only as a path and not as a URL. Table 4.4 lists the available options.
Option | Description |
---|---|
/appsettingurlkey:key or /urlkey:key | Specifies the configuration key to use in order to read the default value for the URL property when generating code. |
/appsettingbaseurl:baseurl or /baseurl:baseurl | Specifies the base URL to use when calculating the URL fragment. The tool calculates the URL fragment by converting the relative URL from the baseurl argument to the URL in the WSDL document. You must specify the /appsettingurlkey option with this option. |
/d[omain]:domain | Specifies the domain name to use when connecting to a server that requires authentication. |
/l[anguage]:language | Specifies the language to use for the generated proxy class. You can specify CS (C#; default),VB (Visual Basic), or JS (JScript) as the language argument. You can also specify the fully qualified name of a class that implements the System .CodeDom.Compiler.CodeDomProvider class. |
/n[amespace]:namespace | Specifies the namespace for the generated proxy or template. The default namespace is the global namespace. |
/nologo | Suppresses the Microsoft start-up banner display. |
/o[ut]:filename | Specifies the file in which to save the generated proxy code. The tool derives the default filename from the web service name. The tool saves generated DataSets in different files. |
/p[assword]:password | Specifies the password to use when connecting to a server that requires authentication. |
/protocol:protocol | Specifies the protocol to implement. You can specify SOAP (default), HttpGet , HttpPost , or a custom protocol specified in the configuration file. |
/proxy:URL | Specifies the URL of the proxy server to use for HTTP requests. The default is to use the system proxy setting. |
/proxydomain:domain or /pd:domain | Specifies the domain to use when connecting to a proxy server that requires authentication. |
/proxypassword:password or /pp:password | Specifies the password to use when connecting to a proxy server that requires authentication. |
/proxyusername:username or /pu:username | Specifies the username to use when connecting to a proxy server that requires authentication. |
/server | Generates an abstract class for a web service based on the contracts. The default is to generate client proxy classes. |
/u[sername]:username | Specifies the username to use when connecting to a server that requires authentication. |
/? | Displays command syntax and options for the tool. |
The following is an example of generation of the source file, StockQuote.cs , by running the wsdl.exe tool from the command prompt with the Microsoft logo suppressed:
wsdl /o:StockQuote.cs /nologo http://localhost/MyWebServices/StockQuoteService.asmx?WSDL
Figure 4.38 shows the source file StockQuote.cs being generated by using the wsdl.exe tool.
Listing 4.11 is the source for the file StockQuote.cs .
// // This source code was auto-generated by wsdl, Version=1.0.2914.16. // using System.Diagnostics; using System.Xml.Serialization; using System; using System.Web.Services.Protocols; using System.Web.Services; [System.Web.Services.WebServiceBindingAttribute(Name="Service1Soap", Namespace="http://tempuri.org/")] public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol { [System.Diagnostics.DebuggerStepThroughAttribute()] public Service1() { this.Url = "http://localhost/MyWebServices/StockQuoteService.asmx"; } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetQuote", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Double GetQuote(string symbol) { object[] results = this.Invoke("GetQuote", new object[] { symbol}); return ((System.Double)(results[0])); } [System.Diagnostics.DebuggerStepThroughAttribute()] public System.IAsyncResult BeginGetQuote(string symbol, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetQuote", new object[] { symbol}, callback, asyncState); } [System.Diagnostics.DebuggerStepThroughAttribute()] public System.Double EndGetQuote(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Double)(results[0])); } }
Notice in the source that the class Service1 does not belong to any namespace. If you want this class to be added to a namespace, you can manually edit the source or alternatively use the namespace option with the wsdl.exe tool. Do not worry if you do not understand the details of the source generated. These are the low-level details for making the SOAP calls to the web ser-vice ”all wrapped up as objects. You are only required to use the GetQuote( ) method in your client application.
The language defaults to C#, so if you want a Visual Basic .NET source file generated, you must run the tool by setting the language option to Visual Basic, as shown here:
wsdl o/StockQuote.vb /l:vb http://localhost/MyWebServices/StockQuoteService.asmx?WSDL
Listing 4.12 is the source for the auto-generated StockQuote.vb file.
Option Strict Off Option Explicit On Imports System Imports System.Diagnostics Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.Xml.Serialization ' 'This source code was auto-generated by wsdl, Version=1.0.2914.16. ' <System.Web.Services.WebServiceBindingAttribute(Name:="Service1Soap", [Namespace]:="http://tempuri.org/")> _ Public Class Service1 Inherits System.Web.Services.Protocols.SoapHttpClientProtocol <System.Diagnostics.DebuggerStepThroughAttribute()> Public Sub New() MyBase.New Me.Url = "http://localhost/MyWebServices/StockQuoteService.asmx" End Sub <System.Diagnostics.DebuggerStepThroughAttribute(), System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetQuote", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _ Public Function GetQuote(ByVal symbol As String) As Double Dim results() As Object = Me.Invoke("GetQuote", New Object() {symbol}) Return CType(results(0),Double) End Function <System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Function BeginGetQuote(ByVal symbol As String, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult Return Me.BeginInvoke("GetQuote", New Object() {symbol}, callback, asyncState) End Function <System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Function EndGetQuote(ByVal asyncResult As System.IAsyncResult) As Double Dim results() As Object = Me.EndInvoke(asyncResult) Return CType(results(0),Double) End Function End Class
You can compile this into a .NET library assembly for use in your client applications. We use the VBC.EXE command-line compiler, as shown here:
vbc /t:library /out:StockClient\bin\VBStockQuote.dll /r:System.dll /r:System.Xml.dll /r:System.Web.dll /r:System.Web.Services.dll StockQuote.vb
This command creates the assembly file VBStockQuote.dll and places it in the \bin directory of your client application so you can create in the \StockClient directory. You can use the following command for the C# source file StockQuote.cs to create the assembly file CSStockQuote.dll :
csc /t:library /out:StockClient\bin\CSStockQuote.dll /r:System.dll /r:System.Xml.dll /r:System.Web.dll /r:System.Web.Services.dll StockQuote.cs
The Soapsuds tool helps you compile client applications that communicate with web services using a technique called .NET Remoting . .NET Remoting provides a framework for objects in different application domains or processes to seamlessly communicate with each other. This infrastructure offers a powerful, yet simple, programming model and run-time support for making these interactions transparent. You can read more about .NET Remoting in Chapter 11, "Creating and Using ASP.NET Web Services."
The Soapsuds tool can be used in the following two ways:
On the server ” .NET Remoting server objects (managed classes and COM objects) use this tool to generate WSDL files or XML Schemas that can serve as metadata, describing the services exposed in a common language run-time assembly. Any client that can read and generate SOAP requests corresponding to the WSDL file can invoke this object and communicate to it by using SOAP.
On the client ” .NET Remoting uses metadata to dynamically create proxy objects on the client (for example, using the Activator.GetObject() method call). The proxy objects that are created at the client side have the same members as the original server class. In the client application, after an instance of the proxy object is handed over to the client, the client application makes method calls on the Remote Object through this local proxy object. The rest of the code assumes that the methods and properties of the Remote Object are available locally on the proxy object. So, the client needs to reference the assembly while he or she compiles the client object.
The following code snippet is from an example in Chapter 11. This first statement gets the proxy object for the Remote Object named AddressEntries dynamically from the GetObject() method. The second statement calls the GetCount() on this proxy.
AddressEntries addrEntires = (AddressEntries)Activator.GetObject(typeof(RemotingAddressBookService.AddressEntries), "http://localhost:8085/AddressEntries.soap"); divAddrCount.InnerHtml = "<B>Total number of Addresses in the" + " Address Book: </B>" + addrEntires.GetCount();
For this code to compile properly, the information about the method name GetCount , which is actually a method exposed by the Remote Object, must be locally available to the compiler on the client.
.NET clients use the Soapsuds tool to download the XML schema from the server (generated on the server) to generate source files or an assembly that contains only metadata, no code. This assembly can be used to compile the client. Note that, alternatively, the clients can use the metadata assembly that is generated on the server and distribute it to the clients.
In addition, Soapsuds can create a static proxy object that wraps up the calls to the remote server object.
This is the syntax for running the Soapsuds.exe tool:
soapsuds {-url:schemaUrl -types:type1,assemblyname[,serviceEndpoint] [;type2,assemblyname][...]] -is:schemafile -ia:assemblyfile} [options]
Table 4.5 lists the available options.
Option | Description |
---|---|
domain:domain or -d:domain | Specifies the domain name to use when connecting to a server that requires a domain name for authentication. |
generatecode or -gc | Generates code. This option is equivalent to using -od:. , where the additional period indicates that the code should be placed in the current directory. |
Httpproxyname:name or -hpn:name | Specifies the HTTP proxy name to use when connecting to a server through an HTTP proxy server. |
Httpproxyport:number or -hpp:number | Specifies the HTTP proxy port number to use when connecting to a server through an HTTP proxy server. |
-inputassemblyfile: assemblyfile or -ia:assemblyfile | Specifies the input assembly file. The tool imports all types from the assembly. When you specify an input assembly, do not include the .exe or .dll extension. |
-inputdirectory:directory or -id:directory | Specifies the directory location of input dynamic link library (DLL) files. |
-inputschemafile:schemafile or -is:schemafile | Specifies the input XML schema file. |
-nowrappedproxy or -nowp | Does not create a wrapped proxy. If you do not specify this option, the tool creates a wrapped proxy by default. |
-outputassemblyfile: assemblyfile or -oa:assemblyfile | Saves output to the specified assembly file. Soapsuds.exe always generates source code when it generates an assembly. |
outputdirectory:output directory or -od:outputdirectory | Saves output to the specified output directory. |
-outputschemafile:schemafile or -os:schemafile | Saves output to the specified XML Schema file. |
-password:password or -p:password | Specifies the password to use when connecting to a server that requires authentication. |
-proxynamespace:namespace or -pn | Specifies the namespace for the code in the generated proxy. |
-serviceendpoint:URL or -se:URL | Specifies the URL or the path to the URL for the service endpoint to place in the WSDL file. |
-strongnamefile:filename or -sn:filename | Signs the assembly being generated with the key pair found in filename. You can generate this file by using the Strong Name tool ( Sn.exe ). |
-types: type1,assemblyname [,serviceEndpoint] [;type2, assemblyname[,serviceEndpoint]] [...] | Specifies the input type list. |
-urltoschema:schemaURL or -url:schemaURL | Specifies the URL from which to retrieve the XML schema. |
-username:username or -u:username | Specifies the username to use when connecting to a server that requires authentication. |
-wrappedproxy or -wp | Creates a wrapped proxy. This is the default. |
-wsdl | Generates WSDL schema. This is the default. |
The following sections contain a few sample commands that show the use of the Soapsuds tool with the different options listed in Table 4.5.
The following command downloads a schema from a URL and saves it to an XML file:
soapsuds -url:http://localhost/Service/MyService.soap?wsdl -os:MyService.xml
The following command downloads a schema from a URL and generates code:
soapsuds -url:http://localhost/Service/MyService.soap?wsdl gc
The following command downloads a schema from a URL, generates code, compiles, and generates an assembly:
soapsuds -url:http://localhost/Service/MyService.soap?wsdl -oa:StockQuote.dll
The following command converts a type to a schema and saves it to a file:
soapsuds -types:MyClass.MyMethod,Service -os:StockQuote.xml
The following command converts a type to a schema and generates code:
soapsuds -types:MyClass.MyMethod,Service -gc
only for RuBoard |