Write WCF Service For Silverlight Application

Download Currency Coonverter Projects

This is first article in three part series on writing an end to end solution using WCF, Silverlight. This first article will discuss How to write WCF service for Silverlight clients. Well you may be asking a question now, is there something different about WCF service for Silverlight application? Well short answer to the question is, Yes. I will discuss that little later. For the discussion I have developed a Silverlight application for Foreign Exchange currency conversion. The data flow of the application is as below.

Data flow
Data flow

From Silverlight application, user selects two currencies for which conversion rate is to be obtained. Silverlight application connects to a WCF service. The WCF service, using HTMLParser.Net to connect to a data source site. It receives the response and then parses it to get conversion rate. And then sends that conversion rate back to Silverlight client application. And then client application displays the conversion rate. You can see this all in action in demo at following location.

How to write WCF service?

There is lot of documentation available on MSDN about what is WCF and what is purpose of it. I will not go into all those details. I will jump right into what do you need to do to develop a service based on Windows Communication Foundation (WCF) technology. There are couple of questions that you will need to answer before you can dig into actual implementaiton of the service.

  • What will the service do? What functionality will the service expose? In WCF terms, this will translate to what contracts that you need to define or what methods will the service expose?
  • What information will be transmitted between clients and service? Tis translates into what data types will be created or exposed? In more stricter terms, this means what DataContract will be defined?
  • What transport mechanism will be used to communicate between client and service? This translates into what type of binding will be used to communicate?
  • How and where will you host the service? This translates into what is going to be endpoint for the communication?

I will discuss these points one at a time.

What is ServiceContract and Operation Contract?

This is the first question that you will need to answer when developing a service using WCF. Loosely defined this what this means is that what are the methods that a client can call in your web service. The following code snipper shows what the contracts look like in the service that I developed for this discussion.


[ServiceContract(Namespace="http://byteblocks.com", Name="CurrencyService")]
public interface ICurrencyService
{
	[OperationContract]
	List<Currency> GetCurrencies(out CallResult status);

	[OperationContract]
	double Convert(string from, string to, out CallResult status);
}

This should look very familiar. It is nothing but regular interface declaration. So there is nothing unusual here. By definition an Interface is no more than a contract for its implementers. The only thing different here is attributes that are decorating interface definition and method declrations. WCF uses Opt-in mechanism for you to indicate what needs to be included in service. By putting OperationContract on method, that you indicate that this method is to be exposed to clients as service's contract.

What data objects are being exposed - DataContract

When client and service communicate with each other, there is some data that gets tramissted as well with. If there is some input that method is expecting then client needs to send that. And if there is some response that service is going to send back to caller, then that data objects need to be sent back. This data communication happens by marhsalling or serializing the data in format that both client and service understand. That would mean that what ever data objects are being passed back and forth have to be atleast serialzable. But that is not enough. As I mentioned, WCF uses Opt-in mechanism. That would mean that what ever objects are being serialized, you will have to indicate what part of the object can be serialized. Lets take a look at one of the objects that is sent back as part of the response for method GetCurrencies.


[DataContract]
public class Currency
{
	public Currency()
	{
	}
	public Currency(string country, string name, string symbol)
	{
		Country = country;
		Symbol = symbol;
		Name = name;
	}
	[DataMember]
	public string Symbol
	{
		get; set;
	}
	[DataMember]
	public string Name
	{
		get; set;
	}
	[DataMember]
	public string Country
	{
		get; set;
	}
}

Notice the use of DataContract and DataMember. By decorating an object with DataContract attribute you indicate your intention of making that object visible to callers. And my putting DataMember attribute on properties or fields you make them available for serialization. Any property or field that is not marked with DataMember attribute, will not be serialized.

Transport Mechanism and Binding

Silverlight can communicate with any service or application that is capable of communicating via Tcp channel or Http with in some restrictions. I will not talk about communication via raw sockets in this article. In this article I will discuss communication over Http. Silverlight can handle all communications that implement SOAP1.1 specification and also stick to BasicHttpBinding. What this means is that in your service when you define end point, make sure that you choose basicHttpBinding as your binding mechanism. If you choose wsHttpBinding the comunication between silverlight application and WCF service will fail. In configuraiton file of WCF service, your end point defintion may look like as below.


<endpoint address="" binding="basicHttpBinding" 
	contract="ByteBlocks.ForExService.ICurrencyService">

For this demo project, I have decided to host my service in IIS. That way I can leverage security implemented by ASP.Net framework.

Important Lessons Learned

During execution of few WCF/Silverlight projects there are some very important lessons I learned. I will point out those from WCF prespective in this article.

  • Make sure that you choose basicHttpBinding in your endpoint defintion.
  • If you throw any excceptions from your WCF service, silverlight application will not get it. All execptions thrown from WCF service end up as HTTP 404 errors in client application. You will see WebException thrown with error code of NotFound. Don't start thinking that your target service URL may not be active. So when you are designing your WCF service for Silverlight, you will need a different approach to convey application errors to client. I will mention few of them here.
    • All methods return response as standard envelope kind of object that has one component as STATUS. Client can look at this status object to decide if there was any error and what was error.
    • Second approach could be that your methods can have an OUT parameter that can be used to convey status of each call to the client. And client can look at this parameter to decide if call failed and why it failed.
    You can see that in my implementation I took later approach of having an OUT parameter. Following snippet shows how my OUT paramter object looks like.
    
    [DataContract]
    public class CallResult
    {
    	public CallResult()
    	{
    		StatusCode = 0;
    		StatusMessage = "OK";
    	}
    	[DataMember]
    	public int StatusCode
    	{get; set;}
    	[DataMember]
    	public string StatusMessage
    	{get; set;}
    	[DataMember]
    	public string ExceptionDetails
    	{get; set;}
    }
    
    
  • When you deploy WCF service on production web server, do define your base address in system.servicemodel section. This way when you move your service around on different servers, the only place where you will need to make change will be in the node that defines base address. Your relative URL definitions will not have to change. For example it may look like as below.
    
    <host>
    <baseAddresses>
    <add baseAddress="http://www.myhostserver.com/MyWCFServices/"/>
    </baseAddresses>
    </host>
    
    
  • Very very important. Do not forget to place CrossDomain.xml or ClientAccessPolicy.xml files at root of yuor end point. Otherwise Silverlight application will get security exceptions because of missing cross domain access policy file.

In next article Consume WCF Services in silverlight control or application, i will discuss development of Silverlight application that consumes this WCF service.

blog comments powered by Disqus