Silverlight and WCF

31 05 2008

With the release of Silverlight 2 beta 1, now developers can use .Net to create Silverlight applications To be more precise, developers can use XAML and VB.NET or C# as the back-end code language. To know more about Silverlight and what tools you need to start developing Silverlight applications, visit my post here.

This post focuses on how to make your Silverlight applications interact with Windows Communication Foundation(WCF) services. Visual Studio 2008 introduced several new WCF features. We will create a small calculator service which is going to add two numbers and return the result to the user.

First, let us create a Silverlight Web Application project.

silverlight-project

Visual Studio creates the necessary files needed for your solution. Let us straight away start with adding our WCF service. Visual Studio creates two projects, one being the actual Silverlight control project and the other being the web application project where the Silverlight control is hosted. So, we would be able to add a WCF service to our web application project and then reference the service in our Silverlight control project. Right click the web application project and add a WCF service to the project.

add-new-item

Name the service as CalculatorService. Visual Studio adds the necessary files such as the SVC and code-behind files and also the service configuration to the web.config file.

wcf-service-added

I have modified the service to hold only function as shown below:

[ServiceContract]
public interface ICalculatorService
{
    [OperationContract]
    int AddTwoNumbers(int num1,int num2);
}

And here is the implementation:

#region ICalculatorService Members

public int AddTwoNumbers(int num1, int num2)
{
    return (num1 + num2);
}

#endregion

Nothing complex, just simple addition and return the result 😉

Now comes the most important thing, at least for this beta 1 release – Silverlight supports only basicHttpBinding and thus our WCF service can only use basicHttpBinding if we are to interact with a Silverlight client. Let us check our CalcultorService’s binding in the web.config file under the system.servicemodel section.

default-binding

Yes, you are right. WCF by default uses wsHttpBinding and thus we need to change the binding to basicHttpBinding. Below is the modified version:

modified-binding

How do we use this service in our Silverlight application? Below is a screenshot of our Silverlight application.

screenshot-control

The interface is pretty simple accepting two numbers from the user and when Add is clicked, our service’s AddTwoNumbers is invoked to get the result.

How do we reference our WCF service now? We do the same way as we do in normal WPF or WinForms applications 😀

Right click on the Reference and select Add Service Reference

silverlight-add-service-reference

We will be presented with a dialog box to add a service reference.

service-discover

We can use the Discover option to discover any WCF services in our solution. As our CalculatorService is hosted in the same solution, the Discover would be able to find our service.

calculator-service-discovered

Let us give a name to our service reference – CalculatorServiceProxy 🙂

Once we add our service, we can see that the Silverlight project now has the necessary files to interact with our WCF service.

silverlight-added-wcf-reference-files

Now we are ready to add our code to the button Click event handler. Below is the code snippet.

private void Button_Click(object sender, RoutedEventArgs e)
{
    int num1 = Convert.ToInt32(TxtNum1.Text);
    int num2 = Convert.ToInt32(TxtNum2.Text);

    CalculatorServiceClient calculator_proxy =
        new CalculatorServiceClient();

    calculator_proxy.AddTwoNumbersCompleted +=
        new EventHandler<AddTwoNumbersCompletedEventArgs>
            (calculator_proxy_AddTwoNumbersCompleted);

    calculator_proxy.AddTwoNumbersAsync(num1, num2);

}

void calculator_proxy_AddTwoNumbersCompleted(object sender,
    AddTwoNumbersCompletedEventArgs e)
{
    HtmlPage.Window.Alert(Convert.ToString(e.Result));
}

You guessed it right – WCF reference adds the asynchronous operations to our Silverlight project and it does makes more sense to use asynchronous operations in a Silverlight environment as we cant block the browser and make the user wait.

Let us build and execute our project 🙂

And here is the screenshot:

output

That’s it! Now we have a Silverlight application interacting with a WCF service 😉

Wasn’t it easy 8)

The sample can be downloaded here:

Advertisements

Actions

Information

12 responses

23 10 2008
malcolm

Hi,
Thanks for this example.

I tried it, and get the following exception when I attempt to perform the call to the service. My service uses the Service1.svc default name. I am running local on my dev system.
Any ideas? Thanks!

Exception is below:

An error occurred while trying to make a request to URI ‘http://localhost:2642/Service1.svc’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. Please see the inner exception for more details.

1 08 2009
KC

Malcome,

Did you find a solution to this problem?

I am deploying a SL application and trying to hook up a WCF service already existing on the same server (Win2K8 with IIS 7).

It works fine when the SL app and the WCF service are in the same VS 9 solution but not when the SL is trying to use the deployed service.

I get the same exception… I can access the WCF service sync from a browser and a test asp.net application.

Any ideas?

Regards
KC

11 02 2009
nezraal

Request for the permission of type ‘System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ failed.

why is this happening ?

11 02 2009
nezraal

and yes service is on binding=”basicHttpBinding”

25 02 2009
Jesse

Very nice posting Chaks. Thank you.

BTW. Your sample was done with SL 1 and when you run it the page requests/complains about the SL download. I just did it in SL 2. if you want me to send it to you.

malcolm: I initially wanted to have my WCF service self contained and running independent of IIS in a Windows service. I faced quite few obstacles and one of them the same as your error and have been looking for a solution since yesterday. I stumbled over this example where the WCF service is contained in the project and it will do for now. I suggest to follow Chaks posting above and use his downloadable sample as a reference. If you want to have an independent WCF service, as I do, I can send you my research links, or the solution when I get there.

nezraal, malcom I can send you the sample that I just did in SL 2 if you give me your e-mail address. mine is bajov AT hotmail.com

25 02 2009
Chaks

@Jesse, thanks a lot 🙂

Yes, the application was done with SL 1

18 03 2009
Karthik

its really very good and easy to understand article
I would like to say special thanks to the contributer

8 04 2009
Chaks

@Karthik Thanks 🙂

20 01 2010
srini

very good application .easy to understand article.
thx. so much

11 12 2010
pradeep

hi Chaks,

Very Nice Article, but while i am testing this in localhost i didn’t get any error. but while tesing it in server i am facing error like “the remote server returned an error:notfound”. I also changed endpoint address in serviceclient.config file but it is showing that error.

please help me on this issue………..

Regards,
K.Pradeep Kumar

6 06 2011
Saravanakumar

Hi,
thank u very much dude as i novice to silverligtht wcf service,i have visited many links to get simple wcf in silverlight,
i got a solution for my problem after seeing your site,thank u very much.

Guys,if u get any error like crossdomain policy,please add the cross domain policy xml file into ur wcf project.

Thanks,
Saravanan

22 08 2011
Ritesh

Bad example , of no use… how to do async binding???? this is only for kids

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: