Tuesday, August 31, 2010

WCF Services and Silverlight 4: Basic example using WCF Services

Where is the data classes to get information from databases? I can't find them. We'll you can stop looking because they don't exist in silverlight. The answer to getting data into your silverlight application is web services. In this post I will show the basic steps to get data into your silverlight application using WCF services.

To begin open up Visual Studio 2008 or Visual Studio 2010. Select File ->New->Project. Select the silverlight application template, give it a name and click OK. After clicking OK, visual studio present a dialog box allowing you to choose which silverlight version you want to target, an option to enable wcf ria services, and the web project type. For the purposes of this post, accept the default and click OK.



Now that we have our silverlight application created let's add a Button control and a Listbox control to our silverlight application. We can do this by simply dragging a Button control and a Listbox control from the toolbox panel onto the design view.


Let's change the text on the button to relate to the purpose of this post . To do this, you can click on the button one time and then go to the properties panel and locate the Content property. Change the text from Button to Call Service. Next we need set up a button click event to call our service. So go ahead and double click on the button to create a click event in the code-behind page.

What will happen is, as soon as the button is click we'll call our service and populate the listbox with some data return from the service.

Creating the Service
To create the service right click on the web project and go to Add ->New Item->Silverlight-enabled Wcf Service.Select the Silverlight-enabled Wcf Service template and click OK.


Now inside the Services1.cs class we will add a method that will return a list of String types. In order for this method to be expose to our silverlight application we have to decorate the method with an OperationContract attribute. For more information about OperationContract I will point you to the msdn website http://msdn.microsoft.com/en-us/library/dd456779.aspx.

Below is the complete code for the Service1.svc.cs class. Once the code is in your Service1.svc.cs class, build the project by pressing F6 if you using VS 2008 or Shift+Control+B for VS 2010.

                                

To call the service,  right-click on the References folder in the silverlight project and click on Add Service Reference. A window pops up allowing you to discover any services that you have created in your project. Click on discover to find our service. Select the service we created and specify a namespace to find the service then click Ok. 



Inside the MainPage.xaml.cs page insert the following code:




Press F5 to run the project.

Enjoy.


No comments:

Post a Comment