Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

Creating a Silverlight WCF Binary Encoding Client in Code

Pete Brown - 14 July 2009

In Silverlight, it can sometimes bet better to skip using the ServiceReferences.ClientConfig file and instead create your WCF clients from code, specifying the endpoint address. This was pretty simple in Silverlight 2 where all we had was basicHttpBinding. Silverlight 3, however, adds in the ability to use binary message encoding via the binaryMessageEncoding element in the server-side WCF config file – something that is on by default in the Silverlight Enabled WCF Service template.

Assuming you have a generated client (from a service reference) named “ExampleServiceClient”, here’s what the code looks like. The key entry is the BinaryMessageEncodingBindingElement. This may be obvious to folks who do tons of custom WCF work :)

private ExampleServiceClient BuildExampleServiceClient()
{
    BindingElementCollection elements = new BindingElementCollection();

    // order of entries in collection is significant: dumb.
    elements.Add(new BinaryMessageEncodingBindingElement());
    elements.Add(new HttpTransportBindingElement());

    CustomBinding binding = new CustomBinding(elements);

    // insert your favorite address resolution algorithm here
    EndpointAddress address = new EndpointAddress(
        new Uri("http://localhost:13519/Services/ExampleService.svc", UriKind.Absolute));

    ExampleServiceClient client = new ExampleServiceClient(binding, address);

    return client;
}

Thanks to Mike Taulty for pointing me in the right direction. I hope that saves you some trouble.

     
posted by Pete Brown on Tuesday, July 14, 2009
filed under:      

3 comments for “Creating a Silverlight WCF Binary Encoding Client in Code”

  1. Miguel MAderosays:
    <p>You'll want to change that Uri when you deploy, this code will help you dynamically get it: </p><pre>public static string GetHost()
    {
    if (!HtmlPage.IsEnabled)
    return "http://localhost:8732/";

    Uri uri = HtmlPage.Document.DocumentUri;

    return String.Format("{0}://{1}:{2}/", uri.Scheme, uri.Host??"80", uri.Port);
    }</pre>

Comment on this Post

Remember me

3 trackbacks for “Creating a Silverlight WCF Binary Encoding Client in Code”

  1. NewsPeepssays:
    Thank you for submitting this cool story - Trackback from NewsPeeps
  2. DotNetShoutoutsays:
    Thank you for submitting this cool story - Trackback from DotNetShoutout
  3. #.think.insays:
    #.think.in infoDose #37 (12th July - 19th July)