Creating a Windows Phone 7 Application Consuming Data Using a WCF Service


Introduction:

The objective of this article is to create a WCF service that retrieves data from the database using LINQ to SQL classes and a Windows Phone 7 application that consumes that service to display the data.

The article contains three main parts:

  1. Creating the database
  2. Creating the WCF Service
  3. Creating the Windows Phone 7 application that consumes the WCF service
The above mentioned scenario has been illustrated with an example. In the example I have created a table that contains some details about an employee (Employee ID, Employee Name and Phone No). When the user of our Windows Phone 7 application enters an employee id, he will be able to retrieve the details of that employee from the database through the WCF service.

Creating the Database:

The following steps have been followed to create the database.
  1. Open the SQL Server Management Studio and connect to the server.
    Image1.gif
     
  2. Create a new database as shown below. (Right Click on the Database and select New Database)

    Image2.gif
     
  3. Give a name to the database (Here I have given the name as MyDatabase) and click OK.

    Image3.gif
     
  4. Now we can see our database (MyDatabase).

    Image4.gif
     
  5. Now create a new table as shown below. (Right Click on table and select New Table)

    Image5.gif
     
  6. We have created a table that contains four columns

    • EmpID (Primary Key) [nchar(10)]
    • EmpFirstName [nvarchar(50)]
    • EmpLastName [nvarchar(50)]
    • PhoneNo [numeric(10,0), Allow null]

      Image6.gif

    Save the table (ctrl+s) and give it a name (In our case, it is MyEmployee)
     
  7. Now some data are added to the table.

    Image7.gif

Now we have created our database.

Creating the WCF Service

We have followed the steps given below to create the WCF Service.
  1. Open the Visual Studio 2010 & create a new WCF Service Application. (In our case, the name of the WCF service is MyService)
    Image8.gif
     
  2. Right Click on the project name and then add a new item.

    Image9.gif
     
  3. Now add a LINQ to SQL class to the project.

    Image10.gif
     
  4. Now go to server explorer and add a new data connection. (Right click on Data Connection and select Add Connection)

    Image11.gif
     
  5. Give the server name, select the database and click test connection. Then click OK.

    Image12.gif
     
  6. Now from server explorer select your database and table and drag the table to the middle pane.

    Image13.gif
     
  7. Now open the IService1.cs and delete all the default codes. Write down the following code there. I have explained the code later.
     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Runtime.Serialization;

    using System.ServiceModel;

    using System.ServiceModel.Web;

    using System.Text;

    using System.Collections.Generic;

     

    namespace MyService

    {

        [ServiceContract]

        public interface IService1

        {

            [OperationContract]

            List<MyEmployee> FindEmployee(string uid);

           
        }
    }

    Image14.gif

    Explanation of the code :

    The interface Iservice1 is the service contract of our WCF service. We have declared only one function (FindEmployee) as our operation contract. This function takes a string as an argument (which is the employee ID entered by the user) and return a List of MyEmployee which is our data model class.

  8. Now open the Service1.svc.cs and delete all the default codes. Write down the following code there. I have explained the code later.
     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Runtime.Serialization;

    using System.ServiceModel;

    using System.ServiceModel.Web;

    using System.Text;

    namespace MyService

    {

        public class Service1 : IService1

        {

            public List<MyEmployee> FindEmployee(string uid)

            {

                DataClasses1DataContext context = new DataClasses1DataContext();

                var res = from r in context.MyEmployees where r.EmpID == uid select r;

                return res.ToList();

            }

        }
    }

    Image15.gif

    Explanation of the code :

    The class Service1 is our service that implements the service contract IService1. In this class we have defined the operation contract FindEmployee. In this method, we have created a data context object. Then we have written a simple LINQ to SQL query that fetches the details of a particular employee whose employee id was passed as an argument of the operation contract. The method returns a list of objects of MyEmployee class. (We could have returned only one object of MyEmployee class also as we are fetching data using the primary key)

  9. Right click on service1.svc and select the "view in browser" option.

    Image16.gif
     
  10. Our service is running now (In Cassini server).

    Image17.gif
     
  11. Copy the URL of the service.
Creating the Windows Phone 7 application that consumes the WCF service
  1. Open the Microsoft Visual Studio 2010 Express for Windows Phone and create a Windows Phone Application. (In our case the name of the Windows Phone 7 application is MyClientWin7)
    Image18.gif
     
  2. In MainPage.xaml drag and drop a TextBox and a Button as shown below.

    Image19.gif

    The XAML code for MainPage.xaml is given below

    <
    phoneNavigation:PhoneApplicationPage
        x:Class="MyClientWin7.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:phoneNavigation="clr- namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
        FontFamily="{StaticResource PhoneFontFamilyNormal}"
        FontSize="{StaticResource PhoneFontSizeNormal}"
        Foreground="{StaticResource PhoneForegroundBrush}">

        <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <!--TitleGrid is the name of the application and page title-->
            <Grid x:Name="TitleGrid" Grid.Row="0">
                <TextBlock Text="MY APPLICATION" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>
                <TextBlock Text="page title" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>
            </Grid>

            <!--ContentGrid is empty. Place new content here-->
            <Grid x:Name="ContentGrid" Grid.Row="1">
                <TextBox Height="32" HorizontalAlignment="Left" Margin="40,87,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="401" />
                <Button Height="70" HorizontalAlignment="Left" Margin="152,304,0,0" Name="button1" VerticalAlignment="Top" Width="160" Content="Find" Click="button1_Click" />
            </Grid>
        </Grid>

     </phoneNavigation:PhoneApplicationPage>
     

  3. Right click on the project name (MyClientWin7) and add a new item. Then select a Windows Phone Portrait Page and add it to the project.

    Image20.gif
     
  4. In Page1.xaml, drag and drop a list box.

    Image21.gif

    The XAML code for Page1.xaml is given below

    <navigation:PhoneApplicationPage
        x:Class="MyClientWin7.Page1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:navigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        SupportedOrientations="Portrait"
        mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="480">

        <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
            <Grid.RowDefinitions>
                <RowDefinition Height="170"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <!--This is the name of the application and page title-->
            <Grid Grid.Row="0" x:Name="TitleGrid">
                <TextBlock x:Name="ApplicationName" Text="MY APPLICATION" Style="{StaticResource PhoneTextPageTitle1Style}"/>
                <TextBlock x:Name="ListName" Text="page title" Style="{StaticResource PhoneTextPageTitle2Style}"/>
            </Grid>

            <!--This section is empty. Place new content here Grid.Row="1"-->
            <Grid Grid.Row="1" x:Name="ContentGrid">
                <ListBox Height="444" HorizontalAlignment="Left" Margin="20,81,0,0" Name="listBox1" VerticalAlignment="Top" Width="434" />
            </Grid>
        </Grid>
    </
    navigation:PhoneApplicationPage>
     

  5. Now right click on the References and add a Service Reference.

    Image22.gif
     
  6. In the Address paste the URL of the WCF service which is running and click Go. Then click OK.

    Image23.gif
     
  7. Now open the MainPAge.xaml.cs (Double click on the button "Find") and write down the follwing code.
     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net;

    using System.Windows;

    using System.Windows.Controls;

    using System.Windows.Documents;

    using System.Windows.Input;

    using System.Windows.Media;

    using System.Windows.Media.Animation;

    using System.Windows.Shapes;

    using Microsoft.Phone.Controls;

     

    namespace MyClientWin7

    {

        public partial class MainPage : PhoneApplicationPage

        {

            public MainPage()

            {

                InitializeComponent();

     

                SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

            }

     

            private void button1_Click(object sender, RoutedEventArgs e)

            {

                string s = textBox1.Text;

                this.Content = new Page1(s);

     

            }
        }
    }

    Image24.gif

    Explanation of the code:

    In the button click event (button1_Click), we have stored the textbox entry in a string and move to a new page (Page1) . In the Page1 constructor, we have passed the textbox entry.
    (Here we will find an error in new Page1(s) as the constructor defined in Page1.xaml.cs has no arguments. But we will change the constructor in the next step. Then the error will be removed.)
     

  8. Open Page1.xaml.cs and write down the code.
     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net;

    using System.Windows;

    using System.Windows.Controls;

    using System.Windows.Documents;

    using System.Windows.Input;

    using System.Windows.Media;

    using System.Windows.Media.Animation;

    using System.Windows.Shapes;

    using Microsoft.Phone.Controls;

    using MyClientWin7.ServiceReference1;

     

    namespace MyClientWin7

    {

        public partial class Page1 : PhoneApplicationPage

        {

            public Page1(string s)

            {

                InitializeComponent();

                Service1Client proxy = new Service1Client();

                proxy.FindEmployeeCompleted += new EventHandler<FindEmployeeCompletedEventArgs>(proxy_FindEmployeeCompleted);

                proxy.FindEmployeeAsync(s);

     

            }

         void proxy_FindEmployeeCompleted(object sender, FindEmployeeCompletedEventArgs e)

            {
                listBox1.ItemsSource = e.Result;
            }
        }
    }

    Image25.gif

    Explanation of the code:

    In the Page1 constructor, we have created a proxy object of the service. Now all WCF service calls from Silverlight are made through asynchronous communications. The FindEmployee contract is implemented in the generated proxy with an asynchronous method FindEmployeeAsync and an event proxy_FindEmployeeCompleted that is raised when the operation has completed.
    The proxy_ FindEmployeeCompleted event sets the ItemSource property of the list box with the return value of the operation contract.
     

  9. Replace the code for the ListBox in the Page1.xaml in the following way.
     

    <ListBox Height="444" HorizontalAlignment="Left" Margin="20,81,0,0" Name="listBox1" VerticalAlignment="Top" Width="434" >

                    <ListBox.ItemTemplate>

                        <DataTemplate>

                            <StackPanel Orientation="Horizontal">

                                <TextBlock Text="{Binding EmpID}"/>

                                <TextBlock Text="{Binding EmpFirstName}"/>

                                <TextBlock Text="{Binding EmpLastName}"/>

                                <TextBlock Text=" " />

                                <TextBlock Text="{Binding PhoneNo}"/>

                            </StackPanel>

                        </DataTemplate>

                    </ListBox.ItemTemplate>

                </ListBox>
    Explanation of the code:

    In this code we have overriden the ListBox control's ItemTemplate and supplied a custom DataTemplate. This DataTemplate uses one StackPanel to stack some textblocks together horizontally. These textblocks are used to bind to the data from the table in a readable manner.

  10. Rebuild the solution and start debugging. The following screen will appear in the emulator.

    Image26.gif
     
  11. Enter some Employee ID in the textbox and click the Find button. (Here I have entered U22975 in the text box )The following screen will appear then showing the details of the employee whose ID was entered in the textbox.

    Image27.gif


Up Next
    Ebook Download
    View all
    Learn
    View all