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

  • Article: Q&A on the Book "Humans vs Computers"
    Author Gojko Adzic has released a book, Humans vs Computers in which he tells stories about the impact of inflexible automation, edge cases and software bugs on the lives of real people. He explains the common mistakes built into the systems and provides advice on how to prevent these mistakes from being built into our systems in the first place. By Shane Ha […]
  • Q&A with Michael Coté on Devops Adoption and his Talk at DevOpsDays NZ
    Raf Gemmail talks to Pivotal’s Michael Coté about obstacles to DevOps adoption and his forthcoming talk at DevOpsDays NZ 2017 By Rafiq Gemmail
  • TensorFlow Serving 1.0 Release Detailed at Google I/O
    Google's Noah Fiedel details new programming model for TensorFlow Serving in a stable 1.0 release. Subject matter addresses common challenges with portability, servablility , and reproducibility improvements. By Dylan Raithel
  • First NetBeans Code Drop Lands at Apache
    Oracle has released the first of three NetBeans code drops to the Apache Incubator. By Matt Raible
  • Article: The Top 10 Adages in Continuous Deployment
    On the basis of discussions at the Continuous Deployment Summit, researchers derived 10 adages about continuous-deployment practices. These adages represent a working set of approaches and beliefs that guide current practice and establish a tangible target for empirical validation. By Chris Parnin
  • Podcast: Joshua Kerievsky and Heidi Helfand on High Performance via Psychological Safety
    In this podcast Shane Hastie, Lead Editor for Culture & Methods, spoke to Joshua Kerievsky, CEO of Industrial Logic, and Heidi Helfand, Director of Engineering Excellence at Procore Technologies and author of the book Dynamic Reteaming, about their talk High Performance via Psychological Safety. By Joshua Kerievsky
  • Spotify and Google Release Forseti GCP Security Tools
    Google has opened up Forseti Security, a set open source tools for GCP security, to all GCP users. The project is the result of a collaborative effort from both Spotify and Google, combining what was originally separate work together into a single toolkit. It aims to automate security processes for developers in order for them to develop more freely. By Andr […]
  • Article: Q&A on the Book SAFe Distilled
    The book SAFe Distilled breaks down the complexity of the framework into easily understood explanations and actionable guidance. It’s a resource for acquiring a deep understanding of the Scaled Agile Framework, and how to implement it successfully. By Ben Linders
  • String Interpolation in Entity Framework Raises Concerns
    One of the new features in Entity Framework Core 2 is the ability to automatically convert interpolated strings into parameterized SQL. Though designed to avoid problems with poorly written SQL, it is feared that it may actually lead to more SQL injection attacks. By Jonathan Allen
  • Podcast: Twitter's Yao Yue on Latency, Performance Monitoring, & Caching at Scale
    Yao Yue spent the majority of her career working on caching systems at Twitter. She created a performance team that deals with edge performance outliers often exposed by the enormous scale of Twitter. In this podcast, she discusses standing up the performance team, thoughts on instrumenting applications, and interesting performance issues (and strategies for […]

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: