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:
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:
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
Give me a +1 if you think it was a good article. Thanks!