Click here to Skip to main content
Licence CPOL
First Posted 14 Jul 2009
Views 19,409
Bookmarked 17 times

Abstracting WCF Service Calls in Silverlight 3

By Jeremy Likness | 14 Jul 2009 | Technical Blog
A method for abstracting WCF service calls in Silverlight to facilitate reuse and easy re-targeting of services.

1

2
2 votes, 66.7%
3
1 vote, 33.3%
4

5
3.40/5 - 3 votes
μ 3.40, σa 1.01 [?]

While working with WCF in Silverlight is a blessing, it is also a challenge because of the way Silverlight manages service references. There are often extra steps required to ensure a service is Silverlight compatible, then additional considerations relative to making the service consumable on the Silverlight side and ensuring security concerns are met, etc. The purpose of this post is to provide a relatively simple and lightweight framework for abstracting the services in your applications to provide a more solid foundation for using them.

The service fundamentally begins on the web server side. Silverlight provides additional templates including a "Silverlight-enabled WCF service." Use this to add a new service reference. This is the first place that the fun can begin.

Despite the friendly sounding name, I've actually had the designer add a service and then declare custom bindings in the web.config with a mode of binary. This isn't something Silverlight knows how to consume. After receiving the ambiguous "NotFound" error and then digging deeper and finding my service was causing a "415 unsupported media type" error in the Silverlight client, I realized my service had generated incorrectly.

The first step was to dig into the web.config and find the service behaviors for my service. The "basicHttpBinding" is the one Silverlight is friendly with, something custom or binary will not. This snippet of web.config demonstrates some of the fundamentals for having the service correct on the server side:

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />    
    <behaviors>
       <serviceBehaviors>
          <behavior name="Silverlight.Service.CustomServiceBehavior">
             <serviceMetadata httpGetEnabled="true" />
             <serviceDebug includeExceptionDetailInFaults="false" />
          </behavior>
       </serviceBehaviors>
    </behaviors>
    <services>  
    <service behaviorConfiguration="Silverlight.Service.CustomServiceBehavior"
       name="Silverlight.Service.CustomService">  
       <endpoint address="" binding="basicHttpBinding" 
		contract="Silverlight.Service.ICustomService"/>
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    </service>
  </services>
</system.serviceModel>

The basics: aspNetCompatibilityEnabled, basicHttpBinding, and the "mex" binding for meta data exchange. Now we're good and can publish this somewhere to reference from the Silverlight client.

On the client, things get more interesting. You could hard code the endpoint if you knew the location it was being published to, but I needed something much more flexible. What I did know was that the client would always be in a folder relative to the web host with the services, so by extracting my local URI, I can recreate the service URI on the fly. What was bothering me was doing this over and over for each service, so I finally created a generic BaseService class.

The class is based on the client and channel for the service. From this, it knows how to construct a URL. Because my service named "CustomService" is actually at "Silverlight/Service/CustomService.svc", a little bit of parsing the host and changing the endpoint is all that is needed.

Here is the class:

public abstract class BaseService<TClient,TChannel> : 
	ClientBase<TChannel> where TClient: ClientBase<TChannel>, 
	new() where TChannel: class
{
    private const string BASE_SERVICE = "Silverlight/Service/{0}.svc";

    private static readonly string _baseUri;

    static BaseService()
    {
        _baseUri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
        int lastSlash = _baseUri.LastIndexOf("/");
        _baseUri = _baseUri.Substring(0, lastSlash+1);            
    }

    private readonly TClient _channel; 

    protected BaseService()
    {        
        if (_baseUri.Contains("http"))
        {
            Binding binding = new BasicHttpBinding();
            EndpointAddress endPoint =
                new EndpointAddress(string.Format("{0}{1}", _baseUri,
                     string.Format(BASE_SERVICE, typeof (TChannel).Name.Substring(1))));
            _channel = (TClient)Activator.CreateInstance(typeof (TClient), 
			new object[] {binding, endPoint});                
        }    
        else
        {
            _channel = Activator.CreateInstance<tclient />();
        }
    }

    protected TClient _GetClientChannel()
    {
        return _channel; 
    }
}

Basically, the service encapsulates creating the client channel for communicating with the service. The static constructor takes path to the Silverlight application and then using string manipulation to find the virtual directory it is hosted in (note if you are running the client in a subfolder, you'll have to trim more slashes to get back to the application root). We use the substring because if we're using interfaces, we get ICustomService but the endpoint is at CustomService.

Note the use of the Activator to instantiate new objects that are typed to the channel/client we need. The first passes an object[] array, which causes the activator to find the constructor that best matches the parameters, in this case we are basically doing this:

_channel = new CustomServiceClient(binding, endpoint); 

When the service is constructed, it checks to see the base URI contains "http." The reason we do this is because when you run debug, the URI is actually on the file system (file:). We assume your default set up for the endpoint is sufficient for debugging and simply instantiate the client without any parameters. If, however, you are running in a web context, the endpoint is overridden with the reconstructed path. Note that we take the name of the channel and then format it into the path so that a channel called CustomService gets mapped to Silverlight/Service/CustomService.svc.

I then created a special event argument to handle the completion of a service call. It will pass back the entity that the service references, as well as the error object, so the client can process as needed:

public class ServiceCompleteArgs<T> : EventArgs where T: class 
{
    public T Entity { get; set; }

    public Exception Error { get; set; }

    public ServiceCompleteArgs(T entity, Exception e)
    {
        Entity = entity;
        Error = e;
    }
}

Now we can inherit from the base class for our actual service calls. Let's assume CustomService returns an integer. My custom service helper will look like this:

public class CustomServiceClientHelper : 
	BaseService<CustomServiceClient, CustomService>
{
    public event EventHandler<ServiceCompleteArgs<int>> CustomServiceCompleted;

    public CustomServiceClientHelper() 
    {
        _GetClientChannel().GetIntegerCompleted += 
		_CustomServiceClientHelperGetIntegerCompleted;
    }        

    public void GetInteger()
    {
        _GetClientChannel().GetIntegerAsync();
    }

    void _CustomServiceClientHelperGetIntegerCompleted
		(object sender, GetIntegerCompletedEventArgs e)
    {
        if (CustomServiceCompleted != null)
        {
            int result = e.Error == null ? e.Result : -1; 
            CustomServiceCompleted(this, new ServiceCompleteArgs<int />(result,e.Error));
        }
    }
}

Now it's very easy for me to reuse the service elsewhere without understanding how the endpoint or data is bound - in my code, putting the result in a TextBlock is as simple as this:

public void Init()
{
    CustomServiceClientHelper client = new CustomServiceClientHelper();
    client.CustomServiceCompleted += _ClientCustomServiceCompleted;
    client.GetInteger();
}

void _ClientCustomServiceCompleted(object sender, ServiceCompleteArgs<int> e)
{
    if (e.Error == null)
    {
        DisplayTextBlock.Text = e.Entity.ToString();
    }
    else 
    {
        HandleError(e.Error);
    }
}  

Now you've got a simple framework for plugging in services and consuming them on the client side that will update its references based on the location it is installed. Of course, there is much more you can do and I suggest the following articles for further reading:

Jeremy Likness

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jeremy Likness

Architect
Wintellect
United States United States

Member

Follow on Twitter Follow on Twitter
Jeremy Likness is a Microsoft Silverlight MVP who works as Project Manager and Senior Consultant for Wintellect with 15 years of experience developing enterprise applications. He has worked with software in multiple verticals ranging from insurance, health and wellness, supply chain management, and mobility. His primary focus for the past decade has been building highly scalable web-based solutions using the Microsoft technology stack with a focus on Silverlight since version 2.0.
 
Prior to Wintellect, Jeremy was Director of Information Technology and served as development manager and architect for AirWatch, LLC, where he helped the company grow and solidify its position as one of the leading wireless technology solution providers in the United States by managing the development of their product portfolio that includes public HotSpot solutions and a management console for enterprise grade wireless networks, mobile devices, and their consumers. A fluent Spanish speaker, Jeremy served as Director of Information Technology for Hispanicare, where he architected a multi-lingual content management system for the company's Hispanic-focused online diet program. Jeremy accepted his role there after serving as Development Manager for Manhattan Associates, a software company that provides supply chain management solutions.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120209.1 | Last Updated 14 Jul 2009
Article Copyright 2009 by Jeremy Likness
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid