Creating a Silverlight 2.0 Application that Consumes a WCF Service
This is my second article in a series focusing on Silverlight 2.0 (beta 2) development using Visual Studio 2008. This article is for beginners who are quite new to Silverlight development and need a practical introduction to developing Silverlight applications which consume WCF services using Visual Studio 2008.
If you are new to Silverlight 2.0 development, please refer my first article in this series titled “Beginning Silverlight 2.0 Development Using Visual Studio 2008.”
In this article, we will create a new WCF Service and consume it using the Silverlight 2.0 application. Technically, we will have a Silverlight 2.0 Datagrid control consuming rows from a regular WCF Service.
My development machine is equipped with following environment:
Windows Server 2003 with SP2
IIS
SQL Server 2008
Visual Studio 2008 (comes with .NET 3.5) with SP1
Microsoft Silverlight Tools Beta 2 for Visual Studio 2008 (includes Silverlight, Silverlight SDK and Tools for VS 2008)
To make this article simple, I created a new database named “Sample” with the following table (“emp”) on my machine (Fig 01):
The entire source code for this article is available in the form of a free downloadable zip file. The solution was developed using Microsoft Visual Studio 2008 Team Edition (with SP1) with Microsoft SQL Server 2008 Developer Edition on Microsoft Windows Server 2003 Standard Edition (with SP3) with Silverlight 2.0 Beta 2. I didn’t really test it in any other environment. I request that you post in the discussion area if you have any problems in execution.
Developing WCF Service using Visual Studio 2008: Creating the project
Let us start our development with WCF Service.
Create a blank solution (DemoSln) as follows:
Go to File || New || Project.
At the top of the “New Project” dialog, make sure that you have selected “.NET Framework 3.5” as your target .NET version.
In the “Project Type” (left pane of “New Project” dialog), open “Visual Studio Solutions” in “Other Project Types.”
In the “Templates” (right pane of “New Project” dialog), select “Blank Solution.”
Provide “DemoSln” as the "Name," your own location, and click “OK.”
Add a new WCF Service Application as follows:
Go to File || Add || New Project (to the existing solution).
In “Add New Project,” make sure “.NET Framework 3.5” is selected at the top.
Open “Visual Basic” || “Web” in the “Project Types” list.
Select “WCF Service Application” as the template.
Provide “DemoEmpService” as the name (Fig 02) and click on “OK.”
The following are the steps to configure the WCF Service to be consumed by the Silverlight 2.0 application. Please understand that the entire following configuration is only for a development environment and the configuration for a production environment might be different.
Change “Service1” to “EmpService” everywhere as follows:
Using Solution Explorer, right click on “IService1.vb” and rename it to “IEmpService.vb.”
The above should replace the existing interface “IService1” to “IEmpService” everywhere in the code. If it does not do it automatically, you have to do it manually yourself.
Using Solution Explorer, right click on “Service1.svc” and rename it to “EmpService.svc.”
Go to the code-behind of the same file and change the class name “Service1” to “EmpService.”
Right click on “EmpService.svc” again and select “Open with.”
Now you have to modify the service file itself. In the “Open with” list, select “Source Code (Text) Editor” and click “OK.”
Modify the existing line so that it matches the following:
Once you have created and configured your WCF Service as explained in previous sections, you need to develop some code to retrieve rows from the database.
Open “IEmpService.vb” and modify the code so that it looks like the following:
<ServiceContract()> _
Public Interface IEmpService
<OperationContract()> _
Function GetEmployee(ByVal empno As Integer) As Employee
<OperationContract()> _
Function GetEmployeeList() As List(Of Employee)
End Interface
' Use a data contract as illustrated in the sample below to add composite types to service operations.
<DataContract()> _
Public Class Employee
Private _Empno As Integer
Private _Ename As String
Private _Sal As Double
Private _Deptno As Integer
<DataMember()> _
Public Property Empno() As Integer
Get
Return _Empno
End Get
Set(ByVal value As Integer)
_Empno = value
End Set
End Property
<DataMember()> _
Public Property Ename() As String
Get
Return _Ename
End Get
Set(ByVal value As String)
_Ename = value
End Set
End Property
<DataMember()> _
Public Property Sal() As Double
Get
Return _Sal
End Get
Set(ByVal value As Double)
_Sal = value
End Set
End Property
<DataMember()> _
Public Property Deptno() As Integer
Get
Return _Deptno
End Get
Set(ByVal value As Integer)
_Deptno = value
End Set
End Property
End Class
Open “EmpService.svc” and modify the code as follows:
Imports System.Data.SqlClient
Public Class EmpService
Implements IEmpService
Public Sub New()
End Sub
Public Function GetEmployee(ByVal empno As Integer) As Employee Implements IEmpService.GetEmployee
Dim objEmp As Employee = Nothing
Using cmd As New SqlCommand("select empno, ename, sal, deptno from dbo.emp where empno = " & empno, New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("cnSample").ConnectionString))
cmd.Connection.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
objEmp = New Employee With {.Empno = dr.GetValue(dr.GetOrdinal("Empno")), _
.Ename = dr.GetValue(dr.GetOrdinal("Ename")), _
.Sal = dr.GetValue(dr.GetOrdinal("Sal")), _
.Deptno = dr.GetValue(dr.GetOrdinal("Deptno")) _
}
End If
cmd.Connection.Close()
End Using
Return objEmp
End Function
Public Function GetEmployeeList() As System.Collections.Generic.List(Of Employee) Implements IEmpService.GetEmployeeList
Dim clnEmp As New List(Of Employee)
Using cmd As New SqlCommand("select empno, ename, sal, deptno from dbo.emp ", New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("cnSample").ConnectionString))
cmd.Connection.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
clnEmp.Add(New Employee With {.Empno = dr.GetValue(dr.GetOrdinal("Empno")), _
.Ename = dr.GetValue(dr.GetOrdinal("Ename")), _
.Sal = dr.GetValue(dr.GetOrdinal("Sal")), _
.Deptno = dr.GetValue(dr.GetOrdinal("Deptno")) _
} _
)
End While
End If
cmd.Connection.Close()
End Using
Return clnEmp
End Function
End Class
Build your solution and open “EmpService.svc” in a browser. It should respond with the following (Fig 06).
Developing WCF Service using Visual Studio 2008: Testing WCF Service
The easiest and fastest way to test a WCF Service is by using the “WCF Test Client” which comes with Visual Studio 2008. The other way is to develop our own WCF consumer (say WinForm consumer, Unit Test consumer) and write code to access the WCF Service. We will deal with the first method here (for simplicity). The second method (WinForm consumer) is available in the source download.
WCF Service test using “WCF Test Client”:
Open Start || Programs || Visual Studio 2008 || Visual Studio Tools || Visual Studio 2008 Command Prompt.
At the prompt, type “wcftestclient” and press enter.
You should see “WCF Test Client” opened for you.
Go to File || Add service, provide “http://localhost/DemoEmpService/EmpService.svc” as the endpoint address and click “OK.”
It should connect to your WCF service and show you the list of web methods.
Double click on those methods and start testing as follows (Fig 07):
Now we need to develop a Silverlight 2 application which consumes our regular WCF Service.
The following are the necessary steps to get started:
Open Visual Studio 2008.
Go to File || Add || New Project (to the existing solution).
Select “Silverlight” as the "Project Type," “Silverlight Application” as the "Template," “DemoSL” as the "Name" and finally click “OK.”
You will be provided with an “Add Silverlight Application” dialog.
Select “Add a new Web to the solution” (first radio button).
Select “Web Application Project” as the "Project Type," “DemoSLWeb” as the "Name" and finally click on “OK” (as shown in Fig 09).
If you observe the “Solution explorer” now, you will find two projects. One is the Silverlight application itself and the other is simply a web application which is used to render and test the Silverlight application developed.
Now that we've created a new Silverlight application, we need to add a reference to the WCF Service we developed earlier.
Using “Solution Explorer," right click on the “DemoSL” project and “Add Service Reference” to “DemoEmpService” as shown below (Fig 10). Rebuild the solution.
Modify the “ServiceReferences.ClientConfig” in “DemoSL” as follows (Fig 11). Rebuild the solution.
Developing a Silverlight 2 application to consume WCF: Writing code
Drag and drop a button, label and a Datagrid from the toolbox onto the Silverlight design surface. Modify your code so that it looks like the following:
Once the datagrid control is added to the Silverlight application, you should have a “System.Windows.Controls.Data” assembly added to your reference list. You should also observe the namespace “my” added to the “UserControl” tag.
Go to the code-behind of the “Page.xaml” and modify the code to look like the following:
Partial Public Class Page
Inherits UserControl
Public Sub New()
InitializeComponent()
End Sub
Private Sub EmployeeListFetched(ByVal sender As Object, ByVal e As EmpService.GetEmployeeListCompletedEventArgs)
Me.dgEmployees.ItemsSource = e.Result
Me.lblMsg.Text = "Fetched!"
End Sub
Private Sub btnShow_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnShow.Click
Once you execute your Silverlight application, you should see the output as follows:
Fig 12
In my upcoming articles, we will see more and more examples of Silverlight 2.0 development. I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com