Consuming WCF 4.0 REST Service in Windows Phone 7

Posted by: Mahesh Sabnis , on 4/29/2010, in Category Windows Phone
Views: 82459
Abstract: In this article, we will consume a WCF REST service in a Windows Phone 7 application.
Windows Phone 7 (WP7) is the upcoming next generation Mobile Operating System by Microsoft. My regular readers may have gauged that I am very passionate about WCF and so I have decided to write an article that shows how to consume WCF REST service in Windows phone application. In this application, I have created a WCF 4.0 REST service. For demonstration, this service is published on an IIS web server on Windows Server 2008 R2. This article assumes that you are aware of creating WCF REST service. If that’s not the case, you can read my article Windows Communication Foundation 4.0 - New REST Features to get started with creating a WCF 4.0 Rest Service.




Step 1: Open VS2010 and create a new Windows Phone application as below:
AddNewProject
Note 1: When you installed VS2010 Express for Windows Phone (Developer Tools), and if VS2010 RC is already installed, then in the installed template list, ‘Silverlight for Windows Phone’, template will be displayed.
Note 2: In VS 2010 RTM, the ‘Add Service Reference…’ option is now available (yet to confirm this)
Step 2: In the project, add references to the following namespaces:
·         System.Core.
·         System.Xml.
·         System.Xml.Linq.
These namespace are for doing LINQ programming in the client project.
Step 3: To the project, add a new class as shown below:
C#
public class Employee
{
    public int EmpNo { get; set; }
    public string EmpName { get; set; }
    public int DeptNo { get; set; }
    public int Salary { get; set; }
}
VB.NET
Public Class Employee
      Private privateEmpNo As Integer
      Public Property EmpNo() As Integer
            Get
                  Return privateEmpNo
            End Get
            Set(ByVal value As Integer)
                  privateEmpNo = value
            End Set
      End Property
      Private privateEmpName As String
      Public Property EmpName() As String
            Get
                  Return privateEmpName
            End Get
            Set(ByVal value As String)
                  privateEmpName = value
            End Set
      End Property
      Private privateDeptNo As Integer
      Public Property DeptNo() As Integer
            Get
                  Return privateDeptNo
            End Get
            Set(ByVal value As Integer)
                  privateDeptNo = value
            End Set
      End Property
      Private privateSalary As Integer
      Public Property Salary() As Integer
            Get
                  Return privateSalary
            End Get
            Set(ByVal value As Integer)
                  privateSalary = value
            End Set
      End Property
End Class
 
This class is required for storing data retrieved from the WCF REST service.
Step 4: In the MainPage.Xaml, write the following DataTemplate. This represents visual for the data display.
<phoneNavigation:PhoneApplicationPage.Resources>
 <DataTemplate x:Key="EmpDs">
    <Grid Width="400">
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"></ColumnDefinition>
        <ColumnDefinition Width="100"></ColumnDefinition>
        <ColumnDefinition Width="100"></ColumnDefinition>
        <ColumnDefinition Width="100"></ColumnDefinition>
      </Grid.ColumnDefinitions>
      <TextBlock Text="{Binding EmpNo}" Height="25" Grid.Column="0"/>
      <TextBlock Text="{Binding EmpName}" Height="25" Grid.Column="1"/>
      <TextBlock Text="{Binding Salary}" Height="25" Grid.Column="2"/>
      <TextBlock Text="{Binding DeptNo}" Height="25" Grid.Column="3"/>
    </Grid>
 </DataTemplate>
</phoneNavigation:PhoneApplicationPage.Resources>
 
Step 5: In the MainPage.Xaml, add a Grid element under the default Grid provided called ‘TitleGrid’:
<Grid x:Name="ContentGrid" Grid.Row="1">
 <TextBlock Height="69" HorizontalAlignment="Left" Margin="17,20,0,0" Name="textBlock1"
             Text="Employee Details" VerticalAlignment="Top" Width="442" TextAlignment="Center"
             FontStretch="ExtraExpanded" FontSize="40" />
 <ListBox Height="519" HorizontalAlignment="Left" Margin="30,116,0,0"
           Name="lstEmpDetails" VerticalAlignment="Top" Width="429" ItemsSource="{Binding}"
            ItemTemplate="{StaticResource EmpDs}"
                      />
</Grid>
 
Step 6: Open MainPage.Xaml.cs/vb and write the following code:
C#
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
 
    try
    {
        WebClient wClient = new WebClient();
        wClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wClient_DownloadStringCompleted);
        wClient.DownloadStringAsync(new Uri("http://maheshserver.mossserver.com:8900/REST_SL4_DML/Service.svc/GetAllEmployee", UriKind.Absolute));
    }
    catch (Exception ex)
    {
        string s = ex.Message;
    }
}
 
void wClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    try
    {
 
        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,
                          Salary = Convert.ToInt32(Emp.Descendants("Salary").First().Value),
                          DeptNo = Convert.ToInt32(Emp.Descendants("DeptNo").First().Value)
                      };
 
        lstEmpDetails.DataContext = AllEmps.ToList();
        lstEmpDetails.ItemsSource = AllEmps.ToList();
    }
    catch (Exception ex)
    {
        string s = ex.Message;
    }
 
}
 
VB.NET
Private Sub PhoneApplicationPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
 
      Try
            Dim wClient As New WebClient()
            AddHandler wClient.DownloadStringCompleted, AddressOf wClient_DownloadStringCompleted
            wClient.DownloadStringAsync(New Uri("http://maheshserver.mossserver.com:8900/REST_SL4_DML/Service.svc/GetAllEmployee", UriKind.Absolute))
      Catch ex As Exception
            Dim s As String = ex.Message
      End Try
End Sub
 
Private Sub wClient_DownloadStringCompleted(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
      Try
 
            Dim xDoc As XDocument = XDocument.Parse(e.Result)
 
            Dim AllEmps = From Emp In xDoc.Descendants("Employee") _
                          Select New Employee()
                                     Convert.ToInt32(Emp.Descendants("Salary").First().Value), DeptNo = Convert.ToInt32(Emp.Descendants("DeptNo").First().Value)
                                     Emp.Descendants("EmpName").First().Value, Salary = Convert.ToInt32(Emp.Descendants("Salary").First().Value), DeptNo
                                     Convert.ToInt32(Emp.Descendants("EmpNo").First().Value), EmpName = Emp.Descendants("EmpName").First().Value, Salary
                                     EmpNo = Convert.ToInt32(Emp.Descendants("EmpNo").First().Value), EmpName
 
            lstEmpDetails.DataContext = AllEmps.ToList()
            lstEmpDetails.ItemsSource = AllEmps.ToList()
      Catch ex As Exception
            Dim s As String = ex.Message
      End Try
 
End Sub
 
In the loaded event, using the WebClient class, a request is made to the WCF REST service. Since WCF REST outputs in XML, the result is stored in the XDocument class. Using XLinq, the XML data from XDocument is read and stored in the Employee class collection. Once the complete XML data is read, it is assigned to the DataContext property of theLlist.   
Step 7: Run the application and the following result will be displayed:
PageTitle    
Conclusion: If your Windows Phone 7 is connected to internet, using HTTP protocol, the data from the service can be consumed by a WP7 application. There is no change in the type of code you write for a normal Silverlight Browser application and WP7 Silverlight application.    
The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Bobby Cannon on Tuesday, November 30, 2010 2:01 PM
What about security? I can't seem to figure out how to securely accesses the data over SSL with Windows Authentication. My desktop client works fine but I can't get the WP7 client to authenticate. Surely you wouldn't hand out employee data that's not secure, correct?
Comment posted by Zeba hassan on Tuesday, July 22, 2014 5:55 PM
Can you please update the code for Windows Phone 8??