Posts Tagged ‘Windows Communication Foundation’

Metadata Exchange options for WCF

September 5, 2010

There are two options for publishing metadata from a WCF service.
By default, the services metadata is not published.
In order to make the services information about itself public, you must do either of the following.

  1. Provide the metadata over HTTP-GET automatically.
  2. Use a dedicated endpoint.

Thankfully, the ServiceHost already knows all about the services metadata.

Metadata exchange (whether using HTTP-GET or a dedicated endpoint) can be enabled Programmatically or administratively.
I find the second option by far the most popular, due to being able to modify, turn on/off after compilation, deployment.
The examples I’m going to show are how to enable the metadata exchange administratively (via the config files).

Bear in mind, that HTTP-GET is a WCF feature (may not be supported by all platforms).
Where as using a dedicated metadata exchange endpoint is an industry standard (WS-MetadataExchange).

Often the best way of explaining something is by example, so that’s what I’ll do here.
Most of the examples are shown using the HTTP transport.
Although, I also show the TCP and IPC transports using the mexTcpBinding and mexNamedPipeBinding respectively.

The solution layout looks like this

We’re pretty much just going to focus on the config files in the services project, that’s ServiceConsoleHost.

HTTP-GET examples

AppUsingHTTP-GET1.config

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <system.serviceModel>
      <services>
        <!--service must reference the custom behavior-->
        <service name="Tasks.Services.TaskManagerService"
            behaviorConfiguration="Tasks.Services.TaskServiceBehavior">
          <host>
            <baseAddresses>
              <!--now we browse to the baseAddress to get out metadata-->
              <!--By default, the address the clients need to use for HTTP-GET is the registered HTTP base address of the service.
              If the host is not configured with an HTTP base address, loading the service will throw an exception.
              You can also specify a different address (or just a URI appended to the HTTP base address)
              at which to publish the metadata by setting the httpGetUrl property of the serviceMetadata tag-->
              <add baseAddress = "http://localhost:8080/Tasks" />
            </baseAddresses>
          </host>
          <endpoint address ="TaskManager"
              binding="basicHttpBinding"
              contract="Tasks.Services.ITaskManagerService" />
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="Tasks.Services.TaskServiceBehavior">
            <!--publishing metadata over HTTP-GET.
            explicit service behavior must be added.
            no metadata endpoint needed-->
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="True" />
          </behavior>
        </serviceBehaviors>
      </behaviors>
    </system.serviceModel>
</configuration>

AppUsingHTTP-GET2.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <!--service must reference the custom behavior-->
      <service name="Tasks.Services.TaskManagerService"
          behaviorConfiguration="Tasks.Services.TaskServiceBehavior">
        <host>
          <baseAddresses>
            <!--now we browse to the baseAddress to get out metadata-->
            <add baseAddress = "http://localhost:8080/Tasks" />
          </baseAddresses>
        </host>
        <endpoint address ="TaskManager"
            binding="basicHttpBinding"
            contract="Tasks.Services.ITaskManagerService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Tasks.Services.TaskServiceBehavior">
          <!--publishing metadata over HTTP-GET.
          explicit service behavior must be added.
          no metadata endpoint needed-->
          <!--for the httpGetUrl, an absolute or relative address can be used
          MSDN states:
          If the value of HttpGetUrl is absolute,
            the address at which the metadata is published is the value of HttpGetUrl value plus a ?wsdl querystring.
          If the value of HttpGetUrl is relative,
            the address at which the metadata is published is the base address and the service address plus a ?wsdl querystring.-->
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8081"/> <!--generate proxy like this C:\>SvcUtil http://localhost:8081 /out:proxy.cs-->
          <!--<serviceMetadata httpGetEnabled="true" httpGetUrl="my"/>--> <!--generate proxy like this C:\>SvcUtil http://localhost:8080/Tasks/my /out:proxy.cs-->
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Dedicated Endpoint examples

AppUsingDedicatedEndpoint1.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <!--If the service does not reference the behavior, the host will expect your service to implement IMetadataExchange.
          While this normally adds no value, it is the only way to provide for custom implementation of the IMetadataExchange.-->
      <service name="Tasks.Services.TaskManagerService"
          behaviorConfiguration="Tasks.Services.TaskServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8080/Tasks" />
          </baseAddresses>
        </host>
        <endpoint address ="TaskManager"
            binding="basicHttpBinding"
            contract="Tasks.Services.ITaskManagerService" />
        <!--Don't need an address in the mex endpoint as the service uses the baseAddress anyway-->
        <endpoint
            binding="mexHttpBinding"
            contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Tasks.Services.TaskServiceBehavior">
          <!--It's not necessary to have the ServiceMetadataBehavior's HttpGetEnabled property set to true, as we now use the mex endpoint.-->
          <!--By simply adding the serviceMetadata behavior below and creating an endpoint with a mex binding and using the IMetadataExchange interface,
          WCF has the service host automatically provide the implementation of IMetadataExchange, providing the service references the behavior,
          in order to see serviceMetadata.-->
          <serviceMetadata/>
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

AppUsingDedicatedEndpoint2.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="Tasks.Services.TaskManagerService"
          behaviorConfiguration="Tasks.Services.TaskServiceBehavior">
        <host>
          <baseAddresses>
            <!--Don't need a baseAddress in order to get metadata, but if you want to browse the service (not the service's end point),
            you need a baseAddress.-->
          </baseAddresses>
        </host>
        <endpoint address ="http://localhost:8081/TaskManager"
            binding="basicHttpBinding"
            contract="Tasks.Services.ITaskManagerService" />
        <!--To get metadata using SvcUtil.exe:
        svcutil http://localhost:8081/mex /out:myProxy.cs
        or
        svcutil http://localhost:8081/ /out:myProxy.cs-->
        <endpoint
            address="http://localhost:8081/mex"
            binding="mexHttpBinding"
            contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Tasks.Services.TaskServiceBehavior">
          <serviceMetadata/>
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

AppUsingDedicatedEndpoint3.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="Tasks.Services.TaskManagerService"
          behaviorConfiguration="Tasks.Services.TaskServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8080/"/>
            <add baseAddress="net.pipe://localhost/"/>
            <!--The http baseAddress can reside here or be removed and added to the mex endpoint as an absolute address-->
            <add baseAddress="http://localhost:8081/"/>
          </baseAddresses>
        </host>
        <endpoint address ="TaskManager"
            binding="basicHttpBinding"
            contract="Tasks.Services.ITaskManagerService" />
        <!--To get metadata using SvcUtil.exe:
        svcutil net.tcp://localhost:8080/mex /out:myProxy.cs
        or
        svcutil net.tcp://localhost:8080/ /out:myProxy.cs-->
        <endpoint
            address="mex"
            binding="mexTcpBinding"
            contract="IMetadataExchange" />
        <!--To get metadata using SvcUtil.exe:
        svcutil net.pipe://localhost/mex /out:myProxy.cs
        or
        svcutil net.pipe://localhost/ /out:myProxy.cs-->
       <endpoint
           address="mex"
           binding="mexNamedPipeBinding"
           contract="IMetadataExchange" />
       <!--Don't need an address in the mex endpoint as the service uses the baseAddress anyway-->
       <!--To get metadata using SvcUtil.exe:
       svcutil http://localhost:8081/ /out:myProxy.cs-->
       <endpoint
           binding="mexHttpBinding"
           contract="IMetadataExchange" />
     </service>
   </services>
   <behaviors>
     <serviceBehaviors>
       <behavior name="Tasks.Services.TaskServiceBehavior">
         <serviceMetadata/>
         <serviceDebug includeExceptionDetailInFaults="True" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>

In order to use any of the above shown config files,
just rename and remove any text in the App.config file name between the App and the .config.
So for example AppUsingHTTP-GET1.config would become App.config

Click on link below to download full source code.

MetadataExchangeExamples.zip

This solution was created in Visual Studio 2008.

Advertisements

Message Inspection in WCF

June 14, 2010

Message Inspectors can be a very usefull tool in diagnosing problems between WCF services and clients.
The messages that are transferred between clients/services can be intercepted and operations performed on them.
We’ve used this at work in conjunction with a tool called SaopUI to capture the SOAP messages and fire them at our service.
This can be usefull for load testing, concurrency testing scenarios amongst others.

What I’ll be demonstrating

Sending a message from our client to the service and receiving a reply.
Capturing the SOAP packets in their raw form on the service, before they are processed by the service operations.

The parts we’ll be going over from my example solution

A service (CoffeeMakingservice)
A client (CoffeeAddict)
The message inspecting components

Service implementation

using System.Threading;

namespace CoffeeAddiction
{
    public class CoffeeShop : ICoffeeShop
    {
        public Coffee MakeCoffee(CoffeeType coffeeType)
        {
            return RunBarrister(coffeeType);
        }

        private Coffee RunBarrister(CoffeeType coffeeType)
        {
            Thread.Sleep(5000);
            return new Coffee() { TypeOfCoffee = coffeeType };
        }
    }
}

Client

using System;
using CoffeeAddict.ServieProxy;

namespace CoffeeAddict
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hi there. What type of Coffee would you like today?");

            ConsoleKey cK;

            do
            {
                DisplayOptionsToAddict();
                ProcessOrder();
                Console.WriteLine("Hit the Escape key to exit the shop. Hit any other key to order more joe.");
                Console.WriteLine();
                cK = Console.ReadKey(true).Key;
            }
            while (cK != ConsoleKey.Escape);
        }

        private static void ProcessOrder()
        {
            Coffee yourCoffee;
            char selectedKey;
            int option;
            bool selectionRequested = false;
            do
            {
                if (selectionRequested)
                    Console.WriteLine("You have entered an invalid option. Please try again.");

                selectedKey = Console.ReadKey(true).KeyChar;
                int.TryParse(selectedKey.ToString(), out option);
                if (!selectionRequested) selectionRequested = true;

            }
            while (option < 1 || option > Enum.GetValues(typeof(CoffeeType)).Length);

            Console.WriteLine("Thank you. We will now process your order.");

            using (CoffeeShopClient coffeeShopClient = new CoffeeShopClient())
                yourCoffee = coffeeShopClient.MakeCoffee((CoffeeType)option);

            Console.WriteLine();
            Console.WriteLine("Your {0} is served!", yourCoffee.TypeOfCoffee);
        }

        private static void DisplayOptionsToAddict()
        {
            Console.WriteLine("Please select the associated number");
            Console.WriteLine();

            foreach (string coffeeType in Enum.GetNames(typeof(CoffeeType)))
            {
                Console.WriteLine("{0} : {1}",
                    Convert.ToInt32(Enum.Parse(typeof(CoffeeType), coffeeType)),
                    coffeeType
                    );
            }
            Console.WriteLine();
        }
    }
}

I’ve hosted these projects in console apps for simplicities sake.
Run the service.

Now generate our ServiceProxy.
You would have to do this before you write the client.

Now we’re ready to start the client.
The client will give a welcome and display a list of options to choose from.
Once the user has made his/her choice, a proxy of the service is created and the users choice is sent to the service for coffee production to begin.
Once the coffee is made, it’s returned to the client.
The client can then decide whether he/she wants another coffee.

——

Now for the message inspection part

As we are going to be inspecting the messages on the service side, we implement the IDispatchMessageInspector.
If we were inspecting the messages on the client side, we would implement the IClientMessageInspector.
As you can see, the methods on these interfaces take a Message parameter.
The Message contains the serialized parameters, operation name, and other information about the message being inspected.
The body of the message is implemented as a streamed object, so we’ve given it some special attention.
Also the body of the message can be processed only once during the lifetime of the Message object.
Any further attempts to retrieve the body, will result in an InvalidOperationException.
The solution to this is to create a copy, by using the CreateBufferedCopy method of the message.
This allows us to create a copy of the original message by using the CreateMessage method on the new MessageBuffer we now have.
As you can see, we write the message out to a time stamped file.

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.Xml;

namespace MessageListener.Instrumentation
{
    public class MessageInspector : IDispatchMessageInspector
    {
        const string LogDir = @"C:\Logs\CoffeeMakingService\";

        private Message TraceMessage(MessageBuffer buffer)
        {
            //Must use a buffer rather than the origonal message, because the Message's body can be processed only once.
            Message msg = buffer.CreateMessage();

            //Setup StringWriter to use as input for our StreamWriter
            //This is needed in order to capture the body of the message, because the body is streamed.
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
            msg.WriteMessage(xmlTextWriter);
            xmlTextWriter.Flush();
            xmlTextWriter.Close();

            //Setup filename to write to
            if (!Directory.Exists(LogDir))
                Directory.CreateDirectory(LogDir);

            DateTime now = DateTime.Now;
            string datePart = now.Year.ToString() + '-' + now.Month.ToString() + '-' + now.Day.ToString() + '-' + now.Hour + '-' + now.Minute + '-' + now.Second;
            string fileName = LogDir + "\\" + datePart + '-' + "SoapEnv.xml";

            //Write to file
            using (StreamWriter sw = new StreamWriter(fileName))
                sw.Write(stringWriter.ToString());

            //Return copy of origonal message with unalterd State
            return buffer.CreateMessage();
        }

        //BeforeSendReply is called after the response has been constructed by the service operation
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            //Uncomment the below line if you need to capture the reply message
            //reply = TraceMessage(reply.CreateBufferedCopy(int.MaxValue));
        }

        //The AfterReceiveRequest method is fired after the message has been received but prior to invoking the service operation
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            request = TraceMessage(request.CreateBufferedCopy(int.MaxValue));
            return null;
        }
    }
}

Now we have to add the message inspector to the services channel stack.
First we create the behavior.
Now the only methods we are likely to want to use are the ApplyClientBehavior and/or ApplyDispatchBehavior.
ApplyDispatchBehavior provides the customization we will need to add our new inspector to the collection of message inspectors on the dispatch runtime of our endpoint dispatcher on the service side.

IEndpointBehavior implementation

using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace MessageListener.Instrumentation
{
    public class LoggingEndpointBehavior : IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {}

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {}

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            MessageInspector inspector = new MessageInspector();
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
        }

        public void Validate(ServiceEndpoint endpoint)
        {}
    }
}

Now we need to add our behavior to a behavior extension.
The BehaviorType property and the CreateBehavior method must be overridden.
By doing this we provide an instance of our behavior when the framework sees that we have added directions to our extension in the configuration.

Sub classing BehaviorExtensionElement

using System;
using System.ServiceModel.Configuration;

namespace MessageListener.Instrumentation
{
    public class LoggingBehaviorExtensionElement : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get
            {
                return typeof(LoggingEndpointBehavior);
            }
        }

        protected override object CreateBehavior()
        {
            return new LoggingEndpointBehavior();
        }
    }
}

After the behavior is added to an extension, it can be added to the channel stack.
We tell the framework where to look for our extension, by adding directions to our configuration file.
We now add a reference to our extension (messageInspector) to the endpoint behavior.

Important parts of the services config file.
I’ve left some parts out of this example, to allow us to focus on the listening functionality.

  <system.serviceModel>


























Now when we run the service and the client, we can enjoy the fruits of our labor.

Click on link below to download full source code.

You can grap the MessageListenerDemo code here.

You’ll need Visual Studio 2010 unless you want to create new projects using the source files.

public class WSDualHttpBinding : Binding,...
{
   public Uri ClientBaseAddress
   {get;set;}
   //More members
}

Duplex communication and callbacks in WCF

May 23, 2010

I was reading in the book Enterprise Integration Patterns that my dev manager bought for the team,
on the Message Endpoint pattern on the way home from work a few days ago.

“A Message Endpoint can be used to send messages or receive them, but one instance does not do both”
From my experience, this wasn’t necessarily true.
So I decided to confirm my suspicion.
The following is a mix of what I read and tested out.

Callback Operations

Not all bindings support callback operations. Only bidirectional-capable bindings (TCP, IPC) support callback operations.
For example, because of its connectionless nature, HTTP cannot be used for callbacks,
and therefore you cannot use callbacks over the BasicHttpBinding or the WSHttpBinding.
The MSMQ bindings also don’t support duplex communication.

To support callbacks over HTTP, WCF offers the WSDualHttpBinding, which actually sets up two WS channels:
one for the calls from the client to the service and one for the calls from the service to the client.

Two way communication can be set up for MSMQ bindings by using two one way contracts.

The CompositeDuplexBindingElement is commonly used with transports, such as HTTP, that do not allow duplex communications natively.
TCP, IPC by contrast, does allow duplex communications natively and so does not require the use of this binding element
for the service to send messages back to a client.

Callbacks, Ports, and Channels

When you use either the NetTcpBinding, NetPeerTcpBinding or the NetNamedPipebinding, the callbacks enter the client on the outgoing channel the binding maintains to the service.
There is no need to open a new port or a pipe for the callbacks.
When you use the WSDualHttpBinding, WCF maintains a separate, dedicated HTTP channel for the callbacks,
because HTTP itself is a unidirectional protocol.
WCF auto-generates a ClientBaseAddress if one is not explicitly set by the user.
WCF selects port 80 by default for that callback channel,
and it passes the service a callback address that uses HTTP, the client machine name, and port 80.
While using port 80 makes sense for Internet-based services, it is of little value to intranet-based services.
In addition, if the client machine happens to also have IIS 5 or 6 running, port 80 will already be reserved,
and the client will not be able to host the callback endpoint.
(IIS7, by default, will allow sharing the port.)

Assigning a callback address

Fortunately, the WSDualHttpBinding offers the ClientBaseAddress property,
which you can use to configure a different callback address on the client.

public class WSDualHttpBinding : Binding,...
{
   public Uri ClientBaseAddress
   {get;set;}
   //More members
}

and configuring the clients base address in the clients config file.

<system.serviceModel>
   <client>
      <endpoint
         address  = "http://localhost:8008/MyService"
         binding  = "wsDualHttpBinding"
         bindingConfiguration = "ClientCallback"
         contract = "IMyContract"
      />
   </client>
   <bindings>
      <wsDualHttpBinding>
         <binding name = "ClientCallback"
            clientBaseAddress = "http://localhost:8009/"
         />
      </wsDualHttpBinding>
   </bindings>
</system.serviceModel>

MSDN CompositeDuplexBindingElement states
The client must expose an address at which the service can contact it to establish a connection from the service to the client.
This client address is provided by the ClientBaseAddress property.

WSDualHttpBinding.ClientBaseAddress uses the CompositeDuplexBindingElement’s ClientBaseAddress property.

x

x

As Juval Lowey states
The problem with using a config file to set the callback base address is that it precludes running multiple instances of the client on the same machine, which is something you are likely to do in any decent testing scenario. However, since the callback port need not be known to the service in advance, in actuality any available port will do. It is therefore better to set the client base address programmatically to any available port.
This can be automated by using one of the SetClientBaseAddress extension methods on the WsDualProxyHelper class.

public static class WsDualProxyHelper
{
   public static void SetClientBaseAddress<T>(this DuplexClientBase<T> proxy,
      int port) where T : class
   {
      WSDualHttpBinding binding = proxy.Endpoint.Binding as WSDualHttpBinding;
      Debug.Assert(binding != null);
      binding.ClientBaseAddress = new Uri("http://localhost:"+ port + "/");
   }
   public static void SetClientBaseAddress<T>(this DuplexClientBase<T> proxy)
      where T : class
   {
      lock(typeof(WsDualProxyHelper))
      {
         int portNumber = FindPort( );
         SetClientBaseAddress(proxy,portNumber);
         proxy.Open( );
      }
   }
   internal static int FindPort( )
   {
      IPEndPoint endPoint = new IPEndPoint(IPAddress.Any,0);
      using(Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
      {
         socket.Bind(endPoint);
         IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;
         return local.Port;
      }
   }
}

There’s also a good description of how to implement callbacks in WCF in the MSDN Duplex Services item.

I’ve also implemented something similar in a project I worked on last year.
It used a singleton service, and has about 30 clients hitting it at any one point in time.

Logical vs Physical Addresses in WCF

April 18, 2010


In this example, I share a listenUri between two endpoints.

Synopsis:

We have one service implementation that has two service contracts.
Each service contract will have it’s own endpoint.
Each endpoint will share a listenUri.

We’ve also setup an endpoint for our metadata exchange.
I’ve done all of this imperatively.

Service code

using System.ServiceModel;
using System.ServiceModel.Description;

namespace Service
{
	[ServiceContract]
	public interface IGetHeaders
	{
		[OperationContract]
		string GetHeaders();
	}

	[ServiceContract]
	public interface ICalculate
	{
		[OperationContract]
		double Sum(double[] values);
	}

	public class HeaderService : IGetHeaders, ICalculate
	{
		public string GetHeaders()
		{
			return OperationContext.Current.RequestContext.RequestMessage.Headers.Action;
		}

		public double Sum(double[] values)
		{
			double result = 0.0;
			foreach (double value in values)
				result += value;
			return result;
		}
	}

	public class Program
	{
		public static void Main()
		{
			Uri baseAddress = new Uri("net.tcp://localhost:8241/Service");
			Uri listenUri = new Uri("net.tcp://localhost:8241/MyListenUri");

			ServiceHost serviceHost	= new ServiceHost(typeof(HeaderService), new Uri[] {baseAddress});
			NetTcpBinding netTcpBinding = new NetTcpBinding();

			serviceHost.AddServiceEndpoint(typeof(IGetHeaders),
				netTcpBinding, "/GetHeaders", listenUri);
			serviceHost.AddServiceEndpoint(typeof(ICalculate),
				netTcpBinding, "/Calculate", listenUri);

			ExposeMetadata(serviceHost);

				serviceHost.Open();
				Console.WriteLine("Host	running...");
			Console.WriteLine("Service {0} hosted and {1} to receive requests", serviceHost.Description.Name, serviceHost.State);
			Console.WriteLine("press Enter to terminate");
				Console.ReadLine();
				serviceHost.Close();
		}

		private static	void ExposeMetadata(ServiceHost serviceHost)
		{
			//Check	to see if the service host already has a ServiceMetadataBehavior
			ServiceMetadataBehavior	serviceMetadataBehavior	= serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
			//If not, add one
			if(serviceMetadataBehavior == null)
				serviceMetadataBehavior	= new ServiceMetadataBehavior();
			serviceMetadataBehavior.HttpGetEnabled = true;
			Uri mexUri = new Uri("http://localhost:8242/Service/Mex");
			serviceMetadataBehavior.HttpGetUrl = mexUri;
			serviceMetadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
			serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);
			//Add MEX endpoint
			serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,	MetadataExchangeBindings.CreateMexHttpBinding(), mexUri);
		}
	}
}

Client code

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Client
{
	 class Program
	 {
		  static void Main(string[] args)
		  {
			NetTcpBinding netTcpBinding = new NetTcpBinding();
			Uri myListenUri = new Uri("net.tcp://localhost:8241/MyListenUri");

			ServiceProxy.GetHeadersClient getHeadersProxy =
				new ServiceProxy.GetHeadersClient(netTcpBinding, new EndpointAddress("net.tcp://localhost:8241/Service/GetHeaders"));
			getHeadersProxy.Endpoint.Behaviors.Add(new ClientViaBehavior(myListenUri));

			ServiceProxy.CalculateClient calculateProxy =
				new ServiceProxy.CalculateClient(netTcpBinding, new EndpointAddress("net.tcp://localhost:8241/Service/Calculate"));
			calculateProxy.Endpoint.Behaviors.Add(new ClientViaBehavior(myListenUri));

			Console.WriteLine("Press Enter to exercise GetHeaders");
			Console.ReadLine();
			Console.WriteLine("And the header is: {0}{1}", getHeadersProxy.GetHeaders(), Environment.NewLine);
			Console.WriteLine("Press Enter to exercise Sum");
			Console.ReadLine();
			Console.WriteLine("And the sum is: {0}{1}", calculateProxy.Sum(new double[] { 1.4, 3.5, 7.8 }), Environment.NewLine);
			Console.WriteLine("press Enter to terminate");
			Console.ReadLine();
		  }
	 }
}

Click on link below to download full source code.

public class Program
{
public    static void    Main()
{
Uri baseAddress =    new Uri(“net.tcp://localhost:8241/Service”);
Uri listenUri = new Uri(“net.tcp://localhost:8241/MyListenUri”);

ServiceHost    serviceHost    = new    ServiceHost(typeof(HeaderService), new    Uri[]    {baseAddress});
NetTcpBinding netTcpBinding =    new NetTcpBinding();

serviceHost.AddServiceEndpoint(typeof(IGetHeaders),
netTcpBinding,    “/GetHeaders”,    listenUri);
serviceHost.AddServiceEndpoint(typeof(ICalculate),
netTcpBinding,    “/Calculate”, listenUri);

ExposeMetadata(serviceHost);

serviceHost.Open();
Console.WriteLine(“Host    running…”);
Console.WriteLine(“Service    {0} hosted and    {1} to receive    requests”, serviceHost.Description.Name, serviceHost.State);
Console.WriteLine(“press Enter to terminate”);
Console.ReadLine();
serviceHost.Close();
}

private static    void ExposeMetadata(ServiceHost serviceHost)
{
//    Check    to    see if the service host    already has    a ServiceMetadataBehavior
ServiceMetadataBehavior    serviceMetadataBehavior    = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
//    If    not, add    one
if    (serviceMetadataBehavior == null)
serviceMetadataBehavior    = new    ServiceMetadataBehavior();
serviceMetadataBehavior.HttpGetEnabled    = true;
Uri mexUri = new Uri(“http://localhost:8242/Service/Mex&#8221;);
serviceMetadataBehavior.HttpGetUrl = mexUri;
serviceMetadataBehavior.MetadataExporter.PolicyVersion =    PolicyVersion.Policy15;
serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);
//    Add MEX endpoint
serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,    MetadataExchangeBindings.CreateMexHttpBinding(), mexUri);
}
}

SingleServiceListenUriTwoEndpoints.zip – 20.98 KB

Once you’ve built the solution, navigate to
Service\bin\Debug\Service.exe and run it.
You should see output like the following.

Now run the Client project in the debugger.
You should see output like the following, once you’ve hit Enter twice.

This is also a good read on the differences between
Logical vs. Physical Addresses.

Built-in MSMQ Bindings

April 5, 2010

NetMsmqBinding, MsmqIntegrationBinding.

NetMsmqBinding only works if you have WCF on both sides of the Queue-to-Queue transfer.

MsmqIntegrationBinding is targeted toward existing MSMQ applications that use COM, native C++ APIs or the types defined in the System.Messaging namespace (as stated by MSDN).

.

Messages from one of the bindings are not compatible with the other binding type.

MsmqIntegrationBinding uses a pre-WCF serialization format, by way of the SerializationFormat property, which is of type enum MsmqMessageSerializationFormat.

The members being: Xml, Binary, ActiveX, ByteArray, Stream.

.

NetMsmqBinding has the following 2 binding elements:

MsmqIntegrationBinding has only one binding element:

BinaryMessageEncodingBindingElement.MessageVersion which is only available on the NetMsmqBinding specifies the WCF supported versioning information.

How do we set the security mode on the standard msmq bindings?

NetMsmqBinding.Security gets the NetMsmqSecurity associated with this binding.
MsmqIntegrationBinding.Security gets the MsmqIntegrationSecurity associated with this binding.

NetMsmqSecurity has the following properties:
Message, Mode, Transport.
MsmqIntegrationSecurity has the following properties:
Mode, Transport.

The Mode properties return the security modes…
MsmqIntegrationSecurityMode in the case of MsmqIntegrationSecurity.Mode.
NetMsmqSecurityMode in the case of NetMsmqSecurity.Mode.

Imperatively set security mode:

Declaratively set security mode:

<configuration>
   <system.ServiceModel>
      <bindings>
         <netMsmqBinding>
            <binding name="MyNetMsmqBinding">
               <security mode="Message"/>
            </binding>
         </netMsmqBinding>
         <msmqIntegrationBinding>
            <binding name="MyMsmqIntegrationBinding">
               <security mode="Transport"/>
            </binding>
         </msmqIntegrationBinding>
      </bindings>
   </system.ServiceModel>
</configuration>

According to this MSDN post, it appears as if the default security mode is Message for NetMsmqBinding and Transport for MsmqIntegrationBinding.

The default security mode for both NetMsmqBinding and MsmqIntegrationBinding is Transport.




-



-

70-503 Exam Training

February 7, 2010

I’ve done a few projects based around the .Net WCF Framework and have decided it’s time to consolidate some of this knowledge (experience?) and aim for the TS: Microsoft .NET Framework 3.5 – Windows Communication Foundation Certification.
I’m by no means an expert on the technology yet, but who knows, maybe I will be one day.

I’m going through a few books and projects I’ve worked on and I’ll be recording the information I personally see as being important to remember (with a focus on the exam).