Creating Silverlight Application to Consume the WCF Service

Creating a Silverlight application to consume a WCF service.
 
Task 1: In the same solution created in the Exercise 1, add a new Silverlight application and name it 'SILV4_JSON_Client'. (Note: You must create a separate web site for the Silverlight application.)
 
Task 2: Open the 'MailPage.xaml' and write the following XAML:

WCF-Service-1.jpg

(Note: <sdk:DataGrid> may be different in your code. So instead of copying and pasting, drag-and-drop the DataGrid from your toolbox.)
 
Task 3: Since we will be making a call to the WCF JSON service, we need to consume the JSON response in the stream. This stream needs to be deserialized into the object. To do this, add the following references in the Silverlight project:
 
SystemRuntime.Serialization and System.ServiceModel.Web

WCF-Service-2.jpg

Task 4: In the Silverlight project add the following class:

public class Employee

{

    public int EmpNo { get; set; } public string EmpName { get; set; } public string DeptName { get; set; } public int Salary { get; set; }

}

This class will be used to consume the JSON deserialized response.
 
Task 5: Add the following references in the using block:
 

using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Task 6: Open MainPage.Xaml.cs and write the following code in the "Get Data" click as below:
 

private void brnGetData_Click(object sender, RoutedEventArgs e)

{

WebClient wc = new WebClient(); wc.OpenReadCompleted += new

OpenReadCompletedEventHandler(wc_OpenReadCompleted); wc.OpenReadAsync(new

Uri("http://localhost:8900/JSON_HP/Service.svc/Employee"));

}

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

{

try

{

if (e.Result != null)

{

Stream jsonStream = e.Result;

DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Employee>));

List<Employee> objEmployeeData = (List<Employee>)ser.ReadObject(jsonStream);

dataGrid1.ItemsSource = objEmployeeData;

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

}

The code above makes an async class for WCF service. To make the request it makes use of the "WebClient" class, this is in the "System.Net" namespace. This downloads the response stream using the service URL. This stream is then deserialized into the object using the "DataContractJsonSerializer" class.

Task 7:
Run the application, and click on the "GetData" button, the following result will be displayed:

WCF-Service-3.jpg