jump to navigation

Using WCF Services in Silverlight 4.0 applications November 21, 2011

Posted by fofo in Silverlight, Silverlight 4, Silverlight-enabled WCF Service, WCF Service.
Tags: ,
trackback

In this post I would like to present in detail how we can consume WCF services from a Silverlight 4 application.I strongly suggest that you have a look in this post of mine where I talk about using web services – .asmx services and how we consume them in our Silverlight applications.I do advise against using .asmx web services in Silverlight application.WCF is strongly recommended by Microsoft and is the distributed technology that MS supports and will continue to support and enhance.In many cases you will see a difference in performance.WCF is significantly faster.Have a look in this very useful article in MSDN where it compares performance of WCF distributed systems with other existing distributed technologies.

All the tools you need to get you started with Silverlight ( and to follow this example) can be found here. Make sure you download and install everything. You will need Visual Studio 2010 or Visual Web Developer Express edition with Microsoft Silverlight 4 Tools for Visual Studio 2010.

I have Visual Studio 2010 Ultimate edition installed in my machine and that is I am going to use.

1) Launch Visual Studio and create a new project a Silverlight application.Give it an appropriate name.I have named it SilverlightWCFService. Make sure you click the option where you host the Silverlight application in a new web site.The Silverlight version should be 4.I will use C# as the development language.

2) I am not going to look into WCF in detail. I can only say a few things. Microsoft with .Net 3.0 Framework, introduced WCF. WCF is Microsoft’s choice to design/build Service Oriented Architecture applications. In this example the silverlght client will use a WCF data service to work with the data.Add a new item to your Web hosting project.Select the project and right click on it. Choose Add new item and from the available templates choose Silverlight-enabled WCF Service.I have named it ProductsByCategory.svc.Have a look at the picture below.

This will build us a service that is correctly configured for Silverlight.Do not choose the WCF Service template.As I have said earlier, Microsoft suggests that WCF is the best way of writing services when a Silvelight application is involved.So Microsoft has provided us with a template that is specifically configured for Silverlight.Typically built-in WCF Services do not work out of the box for Silverlight.You cannot have any kind of bindings with Silverlight.You cannot have any type of ws*.Binding should be set to BasicHttpBinding.

3) Obviously we need to add a data source, a database. I will use the Northwind database.If you need the installation scripts for the sample Northwind database, click here. I assume that you have access to a version of SQL Server.If you do not, you can download and install the free SQL Server Express edition from here.

4)  I assume that you probably have some experience on working with Entity Framework.With EF we can create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of Object-relational impedance mismatch. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.

We will need to add an ADO.Net Entity Data model to our project.

In order to see how I am going to accomplish that, have a look in this post (this is my other blog).You can follow steps 5-9.Ι am going to adopt the database first approach.The only difference is that you should pick Northwind database instead of AdventureWorksLT.In the model we only need the Categories,Suppliers,Products tables.So pick only those tables and close the Entity Data Model wizard.My final model in the Entity Designer looks something like this

5) Now we are ready to write a method in our service class that gets the Products By Category.Have a look at the ProductsByCategory.svc.cs file.The Silverlight code will call the WCF service to request the data from the database.This is the code I wrote for the WCF Service.You have to mark the method you wrote with “[OperationContract] ” .

public class ProductsByCategory
{
[OperationContract]
public List<Product> GetProductsByCategory(string categoryname)
{
var ctx = new NorthwindEntities();

var query = from product in ctx.Products
where product.Category.CategoryName == categoryname
select product;
return query.ToList();

}

// Add more operations here and mark them with [OperationContract]
}

6) Now that we have our WCF service ready we can add a Service Reference from the Silverlight application.Select the Silverlight project and right click on it. Choose Add Service Reference.Click Discover to find available services. You will find the available service and then select it.You will see all the methods available in it.I choose to have a new namespace “MyServices”.Finally click OK.Have a look at the picture below. It will also show you the steps Ι followed.

This whole process generates the necessary proxy and data contract classes that are necessary to talk to the web service.Our Silverlight application knows all about the WCF service up to this point.I would urge you to have a look in the Reference.cs file in the Silvelight project. You can find this file if you choose “Show All files” from the Solution Explorer. Have a look at the picture below to see where it is located.

7) Now we have to design our user interface and also write the necessary code for the data binding. We have to open the MainPage.xaml file and type the following.

<Grid Background="Cyan">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<ListBox x:Name="ProductList"
Margin="12 12 12 12 "
DisplayMemberPath="ProductName" />
<Border BorderBrush="#D92B2B"
Background="Gray"
BorderThickness="3"
Padding="10"
Margin="10 10"
Grid.Column="1">

<StackPanel DataContext="{Binding SelectedItem, ElementName=ProductList}" Background="#FF47CE52">
<TextBlock>Product Name</TextBlock>
<TextBox Text="{Binding ProductName, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}" />
<TextBlock>Unit Price</TextBlock>
<TextBox Text="{Binding UnitPrice, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}" />
<TextBlock>Discontinued</TextBlock>
<TextBox Text="{Binding Discontinued, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}" />

</StackPanel>
</Border>
</Grid>

I have a ListBox control and displays the names of the Products.In a seperate StackPanel element I have 3 textblock and 3 textbox elements.Inside the textbox elements I am going to bind data fetched from the WCF service.More specifically I am interested in the ProductName,UnitPrice,Discontinued properties/fields. I am not going to go into details as far as data binding is concerned. We have the FrameworkElement (StackPanel) that we want to link it to the datasource.The DataContext property sets the data context for that element.If you want to learn more  about the issue click here .

8) Now we need to write the code in the MainPage.xaml.cs file.We have to populate the ProductList element with data.We are going to write some code in the MainPage_Loaded event handling routine.

public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();

Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{

var clnt = new ProductsByCategoryClient();

clnt.GetProductsByCategoryCompleted += (t, r) =>
{

if (!r.Cancelled && r.Error == null)
{

ProductList.ItemsSource = r.Result;

}

else
{
MessageBox.Show("There is no data");
}
};

clnt.GetProductsByCategoryAsync("Refreshments");

}

}

We must instantiate an instance of the client before we can use the service ( var clnt = new ProductsByCategoryClient(); ).

We have two members for the GetProductsByCategory operation. We have the asynchronous method and the completed event.I am handling the completed event first. I am going to use a lambda expression. First I check that the operation has not been cancelled.Then I bind the results to the ProductList element.

Finally I hard code the category, I execute the call  in which the products I am interested to bring into the silverlight client  belong ( clnt.GetProductsByCategoryAsync(“Refreshments”);  ).

Build and Run your application and see all the products appearing in the silverlight client fetched from the WCF service.

That is all folks. Stay tuned because I am going to post more examples on Silverlight 4.

Email me if you need the source code.

Hope it helps!!!

Comments»

1. Dot Net Rules : Using WCF Services in Silverlight 4.0 applications - November 21, 2011

[…] and is the distributed technology that MS supports and will continue to support and enhance. (read more) Share Posted: Δευτέρα, 21 Νοεμβρίου 2011 12:26 πμ από το […]


Leave a comment