Currency Converter-WCF Service For Silverlight Client Application

Source: Internet
Author: User

 

This is first article in three part series on writing an end to end solution usingWCF,Silverlight. This first article will discussHow to write WCFService for Silverlight clients. Well you may be asking a question now, is there something different aboutWCFService 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.

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 waits es 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.

Currency Converter ControlHow 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 whatDataContractWill be defined?
  • What transport mechanic 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.

 

Code

[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 shoshould look very familiar. It is nothing but regular interface declaration. So there is nothing unusual here. By definitionInterfaceIs 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 mechanisms for you to indicate what needs to be attached ded in service. by puttingOperationContractOn 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. 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 wowould mean that what ever data objects are being passed back and forth have to be atleast serialable. but that is not enough. as I mentioned, WCF uses Opt-in mechanic. that wowould 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 methodGetCurrencies.

 

Code

[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 useDataContractAndDataMember. By decorating an objectDataContractAttribute you indicate your intention of making that object visible to callers. And my puttingDataMemberAttribute on properties or fields you make them available for serialization. Any property or field that is not markedDataMemberAttribute, will not be serialized.

Transport mechanic 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 chooseBasicHttpBindingAs your binding mechanic. If you chooseWsHttpBindingThe comunication between silverlight application and WCF service will fail. In your aiton 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 chooseBasicHttpBindingIn 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 codeNotFound. 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 cocould 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.

    

Code

[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 inSystem. servicemodelSection. this way when you move your service around und 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.
       <baseAddresses>
    <add baseAddress="http://www.myhostserver.com/MyWCFServices/"/>
    </baseAddresses>

     

  • Very very important. Do not forget to placeCrossDomain. xmlOrClientAccessPolicy. xmlFiles at root of yuor end point. Otherwise Silverlight application will get security privileges tions 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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.