I suppose with the .NET 4.0 release round the corner, most of you must have started exploring WCF 4.0. As of this writing, Microsoft has released Visual Studio 2010 RC and you can download from the following link.

With VS 2010, lots of new features have been introduced for developers to make their life easier. But one of the very exciting feature provided is inbuilt support to Silverlight. For all those who use VS2008 and Silverlight 3.0 may know that you need to install Silverlight 3.0 SDK and toolkit externally. VS2008 does not provide any drag-drop support for Silverlight controls on the designer canvas, you can drag-drop XAML of Elements in the XAML designer or need to use Expression Blend to design.

With VS2010, developers are provided with easy to use Silverlight 3.0 features like element drag-drop on the designer canvas, easy to use property window etc. For charting, you need to download Silverlight 3.0 Charting toolkit from the following link: http://www.codeplex.com/Silverlight

When you install it, you will get the necessary charting controls and other controls in VS2010 toolbox for Silverlight 3.0 applications.

Now during last week, I was conducting a training for a client on Silverlight 3.0. In this training, I was discussing features of Silverlight 3.0 for application development (Note: Silverlight 4 is going to be released soon). One of the attendees asked me a question if it was possible to use WCF 4.0 in Silverlight 3.0 and can we have some sort of message encoding so that the message size can be handled. Silverlight 3.0 has support for binary encoded message communication to WCF service. These messages are comparatively small in size and help in improving performance of communication.

In this article, I have used VS2010 RC, WCF 4.0 and Silverlight 3.0. The service is hosted on IIS 7.5 and makes a query to a Sql Server 2008 database to fetch the data. This data is then displayed in a Silverlight 3.0 client application.

Task 1: Database Table creation.

Step 1: Create database ‘Company’.

Step 2: Add following tables with columns:

The above table is used to store Employee information.

The above table is used to store, company wise quarter wise sales information.

The above table is used to store ItemName wise sales quantity data.

The above table is used to store state wise sales quantity.

Task 2: Creating WCF 4.0 Service.

Step 1: Open VS2010 and create a blank solution > name it as ‘WCF_Silverlight_BinaryEncodedCall’.

Step 2: To this solution, add a new WCF Service Application and name it as ‘WCF_BinaryEncodedStatasticService’ as shown below. Make sure that .NET 4.0 is selected in the dropdown:

Step 3: Rename ‘Iservice1.cs’ to ‘IStatasticService.cs’. Write the following code in it:

C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace WCF_BinaryEncodedStatasticService

{

[ServiceContract]

publicinterfaceIStatasticService

{

[OperationContract]

List<clsSales> GetSalesDetails();

[OperationContract]

List<clsSalesData> GetSalesData();

[OperationContract]

List<clsStatewiseSales> GetStatewiseSales();

}

[DataContract]

publicclassclsSales

{

[DataMember]

publicint CompanyId { get; set; }

[DataMember]

publicstring CompanyName { get; set; }

[DataMember]

publicint Sales;

}

[DataContract]

publicclassclsSalesData

{

[DataMember]

publicstring ItemName { get; set; }

[DataMember]

publicint SalesQty { get; set; }

}

[DataContract]

publicclassclsStatewiseSales

{

[DataMember]

publicstring StateName { get; set; }

[DataMember]

publicdecimal SalesQuantity { get; set; }

}

}

VB.NET (Converted code)

Imports System

Imports System.Collections.Generic

Imports System.Linq

Imports System.Runtime.Serialization

Imports System.ServiceModel

Imports System.ServiceModel.Web

Imports System.Text

Namespace WCF_BinaryEncodedStatasticService

<ServiceContract> _

PublicInterface IStatasticService

<OperationContract> _

Function GetSalesDetails() As List(Of clsSales)

<OperationContract> _

Function GetSalesData() As List(Of clsSalesData)

<OperationContract> _

Function GetStatewiseSales() As List(Of clsStatewiseSales)

EndInterface

<DataContract> _

PublicClass clsSales

Private privateCompanyId AsInteger

<DataMember> _

PublicProperty CompanyId() AsInteger

Get

Return privateCompanyId

EndGet

Set(ByVal value AsInteger)

privateCompanyId = value

EndSet

EndProperty

Private privateCompanyName AsString

<DataMember> _

PublicProperty CompanyName() AsString

Get

Return privateCompanyName

EndGet

Set(ByVal value AsString)

privateCompanyName = value

EndSet

EndProperty

<DataMember> _

Public Sales AsInteger

EndClass

<DataContract> _

PublicClass clsSalesData

Private privateItemName AsString

<DataMember> _

PublicProperty ItemName() AsString

Get

Return privateItemName

EndGet

Set(ByVal value AsString)

privateItemName = value

EndSet

EndProperty

Private privateSalesQty AsInteger

<DataMember> _

PublicProperty SalesQty() AsInteger

Get

Return privateSalesQty

EndGet

Set(ByVal value AsInteger)

privateSalesQty = value

EndSet

EndProperty

EndClass

<DataContract> _

PublicClass clsStatewiseSales

Private privateStateName AsString

<DataMember> _

PublicProperty StateName() AsString

Get

Return privateStateName

EndGet

Set(ByVal value AsString)

privateStateName = value

EndSet

EndProperty

Private privateSalesQuantity AsDecimal

<DataMember> _

PublicProperty SalesQuantity() AsDecimal

Get

Return privateSalesQuantity

EndGet

Set(ByVal value AsDecimal)

privateSalesQuantity = value

EndSet

EndProperty

EndClass

EndNamespace

The above code shows DataContracts and ServiceContract used to create the WCF service

Step 4: Rename, ‘Service1.cs’ to ‘StatasticService.cs’. This is the WCF service class and implements ‘IStatasticService’ interface as shown below:

Note: I have used the connection string at a number of places here as I built these method individually, but ideally you could use a ConnectionManager class to read the string from a config file. Search out on google and there are plenty of solutions out there.

The above code shows the implementation of the WCF service. The code makes call to the Sql Server 2008 database and fetches data from it.

Step 5: Open Web.Config file and write following configuration:

<?xml version="1.0"?>

<configuration>

<system.web>

<compilation debug="true" targetFramework="4.0" />

</system.web>

<system.serviceModel>

<services>

<service name="WCF_BinaryEncodedStatasticService.StatasticService"

behaviorConfiguration="ServBehave">

<endpoint

address=""

binding="customBinding"

bindingConfiguration="customBinaryEncodedBinding"

contract="WCF_BinaryEncodedStatasticService.IStatasticService"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="ServBehave">

<serviceMetadata httpGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

<bindings>

<customBinding>

<bindingname="customBinaryEncodedBinding">

<binaryMessageEncoding></binaryMessageEncoding>

<httpTransport></httpTransport>

</binding>

</customBinding>

</bindings>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

</system.serviceModel>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true"/>

</system.webServer>

</configuration>

The above configurations are very important. It shows the following:

·It specifies the runtime used to execute WCF service. The target framework attribute demands .NET 4.0 to installed on the web server.

·In the <bindings>, custom binding specifies that the WCF runtime is going to use binary encoding for message transport. So though the service is hosted on IIS which uses Http transport, the binary messages will be carried over it. This makes the communication more optimized, so if there are multiple clients communicating with the WCF service at a time, for all such clients, optimized messaging will be provided by WCF.

Step 6: Make the following changes in ‘StatasticService.svc’ file by right clicking and selecting ‘View Markup’ on it.

<%@ServiceHost="" Language="C#" Debug="true"

Service="WCF_BinaryEncodedStatasticService.StatasticService"

CodeBehind="StatasticService.svc.cs" %>

Task 3: Deploying WCF service on IIS by using the ‘Publish’ mechanism of VS2010 RC and Setting Database Connectivity.

Step 1: Right click on the WCF service project and select ‘Publish’ > you will get the following window. Select the IIS path and click on ‘Publish’.

Note: If the server on which you want to publish this WCF service contains ASP.NET 2.0 runtime and ASP.NET 4.0 runtime, then you need to be more careful, because you need to make some changes in Application Pool properties so that service will use .NET 4.0 and will communicate to the Database server.

(Here I am using Windows 7 Enterprise, IIS 7.5 and Sql Server 2008. These are the steps I have followed to make my solution workable, if you have any better settings, share your solution in the comments section. They are welcome!)

Step 3: Open IIS 7.0 and select Application Pools. You will get the list of all application pools currently available. Select ASP.NET v40 and select advance Settings. From the Advance Settings window, select Process Model and change Identity form ‘ApplicationPoolIdentity’ to ‘Local System’ as below:

Step 4: Browse the svc file by right clicking on it, you should see the page with wsdl link in the browser.

Task 4: Creating Silverlight 3.0 client application.

Step 1: In the solution, right click and add a new Silverlight application, name it a ‘Silv3_StatasticsClient’. Once you click OK, VS2010 will ask for the settings for the Silverlight project as shown below:

The ‘Options’ shows Silverlight versions installed on the machine.

Step 2: Since I am going to use the charting feature of Silverlight, I have done a drag-drop for all charts which I have downloaded from this link. After the drag-drop, my Xaml looks as shown below:

The above code makes an Async call to all methods from WCF. The data received from every call is put in ‘KeyValue<K.V>’ generic class. This class acts as a data source to every Chart control on the page.

Step 4: Run the application, the following result will be displayed:

Conclusion: VS2010 has in built support to Silverlight 3.0. WCF 4.0 services can be consumed in Silverlight 3.0 client applications. The binary encoded WCF service can be consumed in Silverlight 3.0 client for messaging optimization.

Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet

Feedback - Leave us some adulation, criticism and everything in between!

WCF 4.0 is not an easy thing to understand. I am learning to work with Microsoft Visual Studio at the moment and it looks like a dark forest for me. Moreover if combine it with silverlight. Such articles as yours really help to understand many things which would be hard to come up with alone. Keep writing those articles in the nearest future too. Thanks!

Comment posted by
Ilham
on Thursday, January 6, 2011 1:17 AM

May I get the source code? Thank's.

Comment posted by
Ilham
on Monday, January 10, 2011 12:01 AM

Hey Mahesh when I'am compile in visual studio I get this error. What wrong? Thank's.

Ilham - When you create the Service Reference, go into the Advanced Settings and be sure to use the System.Array collection instead of the default collection type, which is causing your error.

Comment posted by
mssqldude
on Wednesday, March 16, 2011 12:20 AM

This is an AWESOME example of how to bind data with Silverlight charts, using WCF. It took me a few hours to fix the code up for my Silverlight 4.0 example, but it worked out in the end. Many thanks for this!