Technology Corner

Home » DotNet » Get WCF Service Metadata on client application

Get WCF Service Metadata on client application

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Archives

RSS InfoQ Feeds

  • How Google Develops New Managers
    Alex Langshur, host of Google Partners Podcasts, has organized the podcast Google HR secrets: identifying & developing great managers, interviewing Sarah Calderon, People Development at Google, on how Google selects, trains, and develops their managers. By Abel Avram
  • Presentation: Cognitive Services, Next Step in Creating Our Robot Overlords
    Harold Pulcher discusses Cognitive Services, how to get started using them, and how to incorporate speech, image, and facial recognition into an application. By Harold Pulcher
  • Presentation: Control Flow Integrity Using Hardware Counters
    Jamie Butler and Cody Pierce discuss a new system for early detection and prevention of unknown exploits. Their system uses Performance Monitoring Unit hardware to enforce coarse-grained Control Flow Integrity (CFI). They intend to prove that their approach is effective and suitable for practical use, while staying resistant to bypass. By Jamie Butler
  • JetBrains Launches GoLand Go IDE
    JetBrains has moved its Go IDE from its early access programme to market. Now branded as GoLand, the IDE extends the IntelliJ platform making its core functionality specific to Go. This follows suit with their other language-specific tools such as PyCharm for Python and RubyMine for Ruby. By Andrew Morgan
  • Panel on the Future of AI
    An SF QCon panel on the future of AI explored some issues facing machine learning today. The areas explored: critical issues facing AI right now, how has technology changed the way people are hired, how non-leading edge companies make the best use of current technologies, what the role of humans in relation to AI is, and exciting new breakthroughs on the imm […]
  • Microsoft Updates Cosmos DB with Cassandra Support and Provides Better Availability Guarantees
    Last month at Microsoft Connect 2017, Azure Cosmos DB received several new updates, including support for using the Cassandra NoSQL database API and increased guarantees for availability. With the Cassandra NoSQL database API, customers can run operations inside Cosmos DB on a data model. The availability guarantee moves from 99.99 percent to 99.999 percent. […]
  • Article: Approximate Computing on WSO2: Explaining Approximation Algorithms in an Applied Setting
    In this article, we describe an example real world application of API monitoring which gets benefit by using approximate stream processing. We developed the application on top of WSO2 Stream Processor as Siddhi extension. Siddhi is the complex event processing library which acts as the event processing engine of WSO2 Stream Processor. By Chamod Samarajeewa
  • Rust in Visual Studio and VS Code
    Daniel Griffen has released a preview version of a Rust language service for Visual Studio. This plugin requires Visual Studio 2017 Preview, an experimental release stream for testing new VS features. By Jonathan Allen
  • Article: Key Takeaway Points and Lessons Learned from QCon San Francisco 2017
    The eleventh annual QCon San Francisco was the biggest yet, bringing together over 1,800 team leads, architects, project managers, and engineering directors. By Abel Avram
  • Article: Q&A With Eberhard Wolff On the Book “A Practical Guide to Continuous Delivery”
    Eberhard Wolff speaks with InfoQ about his work "Continuous Delivery: A Practical Guide", where we detail some of the major concepts behind successful CD adoption and the ripple-effect it can have on developer productivity and quality of service. By Dylan Raithel

Sometimes the client needs to programmatically verify whether a particular endpoint supports a particular contracts. Suppose Application administrator deployed application but it was pointing to development environment or some other address. If this feature implemented in application then he can get to know there is difference in service contracts or endpoints. He can then point to correct endpoints to run properly. This feature can reduce unnecessary diagnosis of errors on production system.

In order to support this feature client application should able to fetch metadata of service. This is not valid in case of netTcpBinding.

Metadata Processing

The metadata may be available either in special metadata exchange endpoints (if the service supports them), or over the HTTP-GET protocol. When you use HTTP-GET, the address of the metadata exchange is the HTTP-GET address suffixed by ?wsdl.

WCF Service

I hosted wcf service with HttpGetEnabled=”true” configuration. This is configuration on service side.

<?xml version="1.0"?>
<configuration>
 
  <system.web>
   </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8045/MarketService"
            httpGetBinding="webHttpBinding" httpGetBindingConfiguration="" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="MyService">
        <endpoint address="net.tcp://localhost:8000/MyService" binding="netTcpBinding"
          name="tcpendpoint" contract="IMarketDataProvider" />
        <endpoint address="http://localhost:8045/marketservice" binding="basicHttpBinding"
          bindingConfiguration="httpbinding" name="httpservicepint" contract="MarketApi.IMarketDataProvider" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="httpbinding" />
      </basicHttpBinding>
      <netTcpBinding>
        <binding name="tcpbinding" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

This service is running on two bindings : tcpbinding and httpbinding with endpoints address net.tcp://localhost:8000/MyService" and http://localhost:8045/marketservice.

<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8045/MarketService"
httpGetBinding="webHttpBinding" httpGetBindingConfiguration="" />

This configuration ensure that service metadata should be exposed and can be get via httpGetUrl. So wsdl will be available on http://localhost:8045/MarketService?wsdl address.

Service Host Code

 class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8045/MarketService");
            using (var productHost = new ServiceHost(typeof(MarketDataProvider)))
            {
                ServiceEndpoint productEndpoint = productHost.AddServiceEndpoint(
			typeof(IMarketDataProvider), new NetTcpBinding(), 
			"net.tcp://localhost:8000/MarketService");
                ServiceEndpoint producthttpEndpoint = productHost.AddServiceEndpoint(
			typeof(IMarketDataProvider), new BasicHttpBinding(), 
			"http://localhost:8045/MarketService");

                productHost.Open();
                Console.WriteLine("The Market service is running and is listening on:");
                Console.WriteLine("{0} ({1})",
                  productEndpoint.Address.ToString(),
                  productEndpoint.Binding.Name);
                Console.WriteLine("{0} ({1})",
                  producthttpEndpoint.Address.ToString(),
                  producthttpEndpoint.Binding.Name);
                Console.WriteLine("\nPress any key to stop the service.");
                Console.ReadKey();
            }
        }


    }

 

Access Metadata on Client Side

MetadataExchangeClient class in System.ServiceModel.Description namespace uses for downloading service metadata on client.

Constructor on MetadataExchangeClient accepts endpoint address instance wrapping the metadata exchange address and enum which specify mode to use when downloading the metadata. It can be MetaDataExchange or HttpGet.

Here is code which extract metadata information:

	
	  static void GetMetadata()
        {
            Uri mexAddress = new Uri("http://localhost:8045/marketservice");
            var mexClient = new MetadataExchangeClient(mexAddress, 
		MetadataExchangeClientMode.HttpGet);
            MetadataSet metadata = mexClient.GetMetadata();
            MetadataImporter importer = new WsdlImporter(metadata);
            ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();

            foreach (var end in endpoints)
                Console.WriteLine("Endpoints on server {0}", end.Address);
            
            ContractDescription description =
            ContractDescription.GetContract(typeof(IMarketDataProvider));
            bool contractSupported = endpoints.Any(endpoint =>
            endpoint.Contract.Namespace == description.Namespace &&
            endpoint.Contract.Name == description.Name);

            if (!contractSupported)
                throw new Exception("Not supported service contracts");

        }

Endpoints can also be accessed with MetadataResolver class.

 ServiceEndpointCollection endpoints =  	
	   MetadataResolver.Resolve(typeof(IMarketDataProvider),
            mexAddress, MetadataExchangeClientMode.HttpGet);

This way you can access service metadata on client side to verify about about endpoints, service contracts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blogs I Follow

%d bloggers like this: