Creating Silverlight Client Application with WCF

Creating Silverlight client application.
 

Task 1: In the same solution add Silverlight client application, name it as
 
‘SILV3_WCF_REST_Client'. (Note: Create separate website for the Silverlight application else the WCF and ASP.NET website will be created in the same project.).
 
Task 2: In the Silverlight project add the ‘Employee' class. This is used to consume the REST –POX response from the WCF service.

public class Employee

{

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

}

 
Task 3: Open MainPage.xaml and write the following Xaml:

Image-1.jpg

  
(Note: <data:DataGrid> tag for DataGrid may be different in your case, so instead of copying the above xaml better Drag-Drop the controls.).
 
Task 4: Open MainPage.Xaml.cs and write the following code on ‘Get Data' button click:
 

    private void btnGetData_Click(object sender, RoutedEventArgs e)

    {

        WebClient wc = new WebClient(); try

        {

            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);

            wc.DownloadStringAsync(new Uri("http://localhost:8001/WCF_REST_HP_VD/Service.svc/Employee"));

        }

        catch (Exception ex)

        {

            MessageBox.Show(ex.Message);

        }

    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

    {

        XDocument xDoc = XDocument.Parse(e.Result);

        var AllEmps = from Emp in xDoc.Descendants("Employee")

                      select new Employee()

                      {

                          EmpNo = Convert.ToInt32(Emp.Descendants("EmpNo").First().Value),

                          EmpName = Emp.Descendants("EmpName").First().Value,

                          DeptName = Emp.Descendants("DeptName").First().Value,

                          Salary = Convert.ToInt32(Emp.Descendants("Salary").First().Value)

                      };

        dgEmp.ItemsSource = AllEmps.ToList();

    }

 
Using the ‘WebClient' class is used to make an Async call to the WCF service and download the contents using ‘DownloadStringAsync()' method using the Url. The above also use Linq to Xml (XLINQ) to read the data from the xml response from the WCF service and store it in the Employee object.
 
Task 5: Run the application and click on the ‘Ger Data' button the following result will be displayed:

Image-2.jpg

Ebook Download
View all
Learn
View all