Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
300 lines (259 sloc) 18.6 KB
title ms.assetid
Custom WSDL Publication

Custom WSDL Publication

This sample demonstrates how to:

  • Implement a xref:System.ServiceModel.Description.IWsdlExportExtension?displayProperty=nameWithType on a custom xref:System.ServiceModel.Description.IContractBehavior?displayProperty=nameWithType attribute to export attribute properties as WSDL annotations.

  • Implement xref:System.ServiceModel.Description.IWsdlImportExtension?displayProperty=nameWithType to import the custom WSDL annotations.

  • Implement xref:System.ServiceModel.Description.IServiceContractGenerationExtension?displayProperty=nameWithType and xref:System.ServiceModel.Description.IOperationContractGenerationExtension?displayProperty=nameWithType on a custom contract behavior and a custom operation behavior, respectively, to write imported annotations as comments in the CodeDom for the imported contract and operation.

  • Use the xref:System.ServiceModel.Description.MetadataExchangeClient?displayProperty=nameWithType to download the WSDL, a xref:System.ServiceModel.Description.WsdlImporter?displayProperty=nameWithType to import the WSDL using the custom WSDL importer, and the xref:System.ServiceModel.Description.ServiceContractGenerator?displayProperty=nameWithType to generate Windows Communication Foundation (WCF) client code with the WSDL annotations as /// and ''' comments in C# and Visual Basic.

[!NOTE] The setup procedure and build instructions for this sample are located at the end of this topic.


The service in this sample is marked with two custom attributes. The first, the WsdlDocumentationAttribute, accepts a string in the constructor and can be applied to provide a contract interface or operation with a string that describes its usage. The second, WsdlParamOrReturnDocumentationAttribute, can be applied to return values or parameters to describe those values in the operation. The following example shows a service contract, ICalculator, described using these attributes.

// Define a service contract.      
// Document it.  
[WsdlDocumentation("The ICalculator contract performs basic calculation services.")]  
public interface ICalculator  
    [WsdlDocumentation("The Add operation adds two numbers and returns the result.")]  
    [return:WsdlParamOrReturnDocumentation("The result of adding the two arguments together.")]  
    double Add(  
      [WsdlParamOrReturnDocumentation("The first value to add.")]double n1,   
      [WsdlParamOrReturnDocumentation("The second value to add.")]double n2  
    [WsdlDocumentation("The Subtract operation subtracts the second argument from the first.")]  
    [return:WsdlParamOrReturnDocumentation("The result of the second argument subtracted from the first.")]  
    double Subtract(  
      [WsdlParamOrReturnDocumentation("The value from which the second is subtracted.")]double n1,   
      [WsdlParamOrReturnDocumentation("The value that is subtracted from the first.")]double n2  
    [WsdlDocumentation("The Multiply operation multiplies two values.")]  
    [return:WsdlParamOrReturnDocumentation("The result of multiplying the first and second arguments.")]  
    double Multiply(  
      [WsdlParamOrReturnDocumentation("The first value to multiply.")]double n1,   
      [WsdlParamOrReturnDocumentation("The second value to multiply.")]double n2  
    [WsdlDocumentation("The Divide operation returns the value of the first argument divided by the second argument.")]  
    [return:WsdlParamOrReturnDocumentation("The result of dividing the first argument by the second.")]  
    double Divide(  
      [WsdlParamOrReturnDocumentation("The numerator.")]double n1,   
      [WsdlParamOrReturnDocumentation("The denominator.")]double n2  

The WsdlDocumentationAttribute implements xref:System.ServiceModel.Description.IContractBehavior and xref:System.ServiceModel.Description.IOperationBehavior, so the attribute instances are added to the corresponding xref:System.ServiceModel.Description.ContractDescription or xref:System.ServiceModel.Description.OperationDescription when the service is opened. The attribute also implements xref:System.ServiceModel.Description.IWsdlExportExtension. When xref:System.ServiceModel.Description.IWsdlExportExtension.ExportContract%28System.ServiceModel.Description.WsdlExporter%2CSystem.ServiceModel.Description.WsdlContractConversionContext%29 is called, the xref:System.ServiceModel.Description.WsdlExporter that is used to export the metadata and the xref:System.ServiceModel.Description.WsdlContractConversionContext that contains the service description objects are passed in as parameters enabling the modification of the exported metadata.

In this sample, depending upon whether the export context object has a xref:System.ServiceModel.Description.ContractDescription or an xref:System.ServiceModel.Description.OperationDescription, a comment is extracted from the attribute using the text property and is added to the WSDL annotation element as shown in the following code.

public void ExportContract(WsdlExporter exporter, WsdlContractConversionContext context)  
    if (contractDescription != null)  
        // Inside this block it is the contract-level comment attribute.  
        // This.Text returns the string for the contract attribute.  
        // Set the doc element; if this isn't done first, there is no XmlElement in the   
        // DocumentElement property.  
        context.WsdlPortType.Documentation = string.Empty;  
        // Contract comments.  
        XmlDocument owner = context.WsdlPortType.DocumentationElement.OwnerDocument;  
        XmlElement summaryElement = owner.CreateElement("summary");  
        summaryElement.InnerText = this.Text;  
        Operation operation = context.GetOperation(operationDescription);  
        if (operation != null)  
            // We are dealing strictly with the operation here.  
            // This.Text returns the string for the operation-level attributes.  
            // Set the doc element; if this isn't done first, there is no XmlElement in the   
            // DocumentElement property.  
            operation.Documentation = String.Empty;  
            // Operation C# triple comments.  
            XmlDocument owner = operation.DocumentationElement.OwnerDocument;  
            XmlElement newSummaryElement = owner.CreateElement("summary");  
            newSummaryElement.InnerText = this.Text;  

If an operation is being exported, the sample uses reflection to obtain any WsdlParamOrReturnDocumentationAttribute values for parameters and return values and adds them to the WSDL annotation elements for that operation as follows.

// Get returns information  
ParameterInfo returnValue = operationDescription.SyncMethod.ReturnParameter;  
object[] returnAttrs = returnValue.GetCustomAttributes(typeof(WsdlParamOrReturnDocumentationAttribute), false);  
if (returnAttrs.Length != 0)  
    // <returns>text.</returns>  
    XmlElement returnsElement = owner.CreateElement("returns");  
    returnsElement.InnerText = ((WsdlParamOrReturnDocumentationAttribute)returnAttrs[0]).ParamComment;  
// Get parameter information.  
ParameterInfo[] args = operationDescription.SyncMethod.GetParameters();  
for (int i = 0; i < args.Length; i++)  
    object[] docAttrs = args[i].GetCustomAttributes(typeof(WsdlParamOrReturnDocumentationAttribute), false);  
    if (docAttrs.Length == 1)  
        // <param name="Int1">Text.</param>  
        XmlElement newParamElement = owner.CreateElement("param");  
        XmlAttribute paramName = owner.CreateAttribute("name");  
        paramName.Value = args[i].Name;  
        newParamElement.InnerText = ((WsdlParamOrReturnDocumentationAttribute)docAttrs[0]).ParamComment;  

The sample then publishes metadata in the standard way, using the following configuration file.

    <!-- ICalculator is exposed at the base address provided by host: http://localhost/servicemodelsamples/service.svc  -->  
    <endpoint address=""  
              contract="Microsoft.ServiceModel.Samples.ICalculator" />  
    <!-- the mex endpoint is exposed at http://localhost/servicemodelsamples/service.svc/mex -->  
    <endpoint address="mex"  
              contract="IMetadataExchange" />  
<!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-->  
    <behavior name="CalculatorServiceBehavior">  
      <serviceMetadata httpGetEnabled="True"/>  
      <serviceDebug includeExceptionDetailInFaults="False" />  

Svcutil client

This sample does not use Svcutil.exe. The contract is provided in the generatedClient.cs file so that after the sample demonstrates custom WSDL import and code generation, the service can be invoked. To use the following custom WSDL importer for this example, you can run Svcutil.exe and specify the /svcutilConfig option, giving the path to the client configuration file used in this sample, which references the WsdlDocumentation.dll library. To load the WsdlDocumentationImporter, however, Svuctil.exe must be able to locate and load the WsdlDocumentation.dll library, which means either that it is registered in the global assembly cache, in the path, or is in the same directory as Svcutil.exe. For a basic sample such as this, the easiest thing to do is to copy Svcutil.exe and the client configuration file into the same directory as WsdlDocumentation.dll and run it from there.

The Custom WSDL Importer

The custom xref:System.ServiceModel.Description.IWsdlImportExtension object WsdlDocumentationImporter also implements xref:System.ServiceModel.Description.IContractBehavior and xref:System.ServiceModel.Description.IOperationBehavior to be added to the imported ServiceEndpoints and xref:System.ServiceModel.Description.IServiceContractGenerationExtension and xref:System.ServiceModel.Description.IOperationContractGenerationExtension to be invoked to modify the code generation when the contract or operation code is being created.

First, in the xref:System.ServiceModel.Description.IWsdlImportExtension.ImportContract%28System.ServiceModel.Description.WsdlImporter%2CSystem.ServiceModel.Description.WsdlContractConversionContext%29 method, the sample determines whether the WSDL annotation is at the contract or operation level, and adds itself as a behavior at the appropriate scope, passing the imported annotation text to its constructor.

public void ImportContract(WsdlImporter importer, WsdlContractConversionContext context)  
    // Contract Documentation  
    if (context.WsdlPortType.Documentation != null)  
        // System examines the contract behaviors to see whether any implement IWsdlImportExtension.  
        context.Contract.Behaviors.Add(new WsdlDocumentationImporter(context.WsdlPortType.Documentation));  
    // Operation Documentation  
    foreach (Operation operation in context.WsdlPortType.Operations)  
        if (operation.Documentation != null)  
            OperationDescription operationDescription = context.Contract.Operations.Find(operation.Name);  
            if (operationDescription != null)  
                // System examines the operation behaviors to see whether any implement IWsdlImportExtension.  
                operationDescription.Behaviors.Add(new WsdlDocumentationImporter(operation.Documentation));  

Then, when the code is generated, the system invokes the xref:System.ServiceModel.Description.IServiceContractGenerationExtension.GenerateContract%28System.ServiceModel.Description.ServiceContractGenerationContext%29 and xref:System.ServiceModel.Description.IOperationContractGenerationExtension.GenerateOperation%28System.ServiceModel.Description.OperationContractGenerationContext%29 methods, passing the appropriate context information. The sample formats the custom WSDL annotations and inserts them as comments into the CodeDom.

public void GenerateContract(ServiceContractGenerationContext context)  
    Debug.WriteLine("In generate contract.");  
public void GenerateOperation(OperationContractGenerationContext context)  
    Debug.WriteLine("In generate operation.");  

The Client Application

The client application loads the custom WSDL importer by specifying it in the application configuration file.

  <endpoint address="http://localhost/servicemodelsamples/service.svc"   
  contract="ICalculator" />  
      <extension type="Microsoft.ServiceModel.Samples.WsdlDocumentationImporter, WsdlDocumentation"/>  

Once the custom importer has been specified, the WCF metadata system loads the custom importer into any xref:System.ServiceModel.Description.WsdlImporter created for that purpose. This sample uses the xref:System.ServiceModel.Description.MetadataExchangeClient to download the metadata, the xref:System.ServiceModel.Description.WsdlImporter properly configured to import the metadata using the custom importer the sample creates, and the xref:System.ServiceModel.Description.ServiceContractGenerator to compile the modified contract information into both Visual Basic and C# client code that can be used in Visual Studio to support Intellisense or compiled into XML documentation.

/// From WSDL Documentation:  
/// <summary>The ICalculator contract performs basic calculation   
/// services.</summary>   
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "")]  
[System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.ServiceModel.Samples", ConfigurationName="ICalculator")]  
public interface ICalculator  
    /// From WSDL Documentation:  
    /// <summary>The Add operation adds two numbers and returns the   
    /// result.</summary><returns>The result of adding the two arguments   
    /// together.</returns><param name="n1">The first value to add.</param><param   
    /// name="n2">The second value to add.</param>   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Add", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")]  
    double Add(double n1, double n2);  
    /// From WSDL Documentation:  
    /// <summary>The Subtract operation subtracts the second argument from the   
    /// first.</summary><returns>The result of the second argument subtracted from the   
    /// first.</returns><param name="n1">The value from which the second is   
    /// subtracted.</param><param name="n2">The value that is subtracted from the   
    /// first.</param>   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Subtract", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")]  
    double Subtract(double n1, double n2);  
    /// From WSDL Documentation:  
    /// <summary>The Multiply operation multiplies two values.</summary><returns>The   
    /// result of multiplying the first and second arguments.</returns><param   
    /// name="n1">The first value to multiply.</param><param name="n2">The second value   
    /// to multiply.</param>   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Multiply", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")]  
    double Multiply(double n1, double n2);  
    /// From WSDL Documentation:  
    /// <summary>The Divide operation returns the value of the first argument divided   
    /// by the second argument.</summary><returns>The result of dividing the first   
    /// argument by the second.</returns><param name="n1">The numerator.</param><param   
    /// name="n2">The denominator.</param>   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Divide", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")]  
    double Divide(double n1, double n2);  

To set up, build, and run the sample

  1. Ensure that you have performed the One-Time Setup Procedure for the Windows Communication Foundation Samples.

  2. To build the C# or Visual Basic .NET edition of the solution, follow the instructions in Building the Windows Communication Foundation Samples.

  3. To run the sample in a single- or cross-machine configuration, follow the instructions in Running the Windows Communication Foundation Samples.

[!IMPORTANT] The samples may already be installed on your machine. Check for the following (default) directory before continuing.


If this directory does not exist, go to Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4 to download all Windows Communication Foundation (WCF) and [!INCLUDEwf1] samples. This sample is located in the following directory.


You can’t perform that action at this time.