Thứ Hai, 7 tháng 10, 2013

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.
1. Creating the Database:
The following steps have been followed to create the database

Image6.gif

    Now some data are added to the table.
    Image7.gif

    Now we have created our database.


    2. Creating the WCF Service

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

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

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

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

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

    Image13.gif
     
    Now open the IService1.cs and delete all the default codes. Write down the following code there. I have explained the code later.
     
    Now open the Service1.svc.cs and delete all the default codes. Write down the following code there. I have explained the code later.
     
    Right click on service1.svc and select the "view in browser" option.

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

    Image17.gif
     
    Copy the URL of the service.
    3. 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

    In MainPage.xaml drag and drop a TextBox and a Button as shown below.

    1. Image19.gif

    2. The XAML code for MainPage.xaml is given below

    3. <phoneNavigation:PhoneApplicationPage 
    4.     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}">
    5.     <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">        <Grid.RowDefinitions>            <RowDefinition Height="Auto"/>            <RowDefinition Height="*"/>        </Grid.RowDefinitions>
    6.         <!--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="{StaticResourcePhoneTextPageTitle2Style}"/>        </Grid>
    7. 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.

    8. Image20.gif
    9.  
    10. In Page1.xaml, drag and drop a list box.

    11. Image21.gif

    12. The XAML code for Page1.xaml is given below

    13. <navigation:PhoneApplicationPage 
    14.     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">
    15. </navigation:PhoneApplicationPage>
    16. Now right click on the References and add a Service Reference.

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

    20. Image23.gif
    21.  
    22. Now open the MainPAge.xaml.cs (Double click on the button "Find") and write down the follwing code.
    23.  
    24. Open Page1.xaml.cs and write down the code.
    25.  
    26.             listBox1.ItemsSource = e.Result;
    27.         }    }
    28. Replace the code for the ListBox in the Page1.xaml in the following way.
    29.  
    30. Rebuild the solution and start debugging. The following screen will appear in the emulator.

    31. Image26.gif
    32.  
    33. 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.

    34. Image27.gif



    35. using System;




    1. using System.Collections.Generic;
    2. using System.Linq;
    3. using System.Runtime.Serialization;
    4. using System.ServiceModel;
    5. using System.ServiceModel.Web;
    6. using System.Text;
    7. using System.Collections.Generic;

    8. namespace MyService
    9. {
    10.     [ServiceContract]
    11.     public interface IService1
    12.     {
    13.         [OperationContract]
    14.         List<MyEmployee> FindEmployee(string uid);
    15.      
    16.     }
    17. }

    18. Image14.gif

    19. Explanation of the code :

    20. 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.
    21. using System;
    22. using System.Collections.Generic;
    23. using System.Linq;
    24. using System.Runtime.Serialization;
    25. using System.ServiceModel;
    26. using System.ServiceModel.Web;
    27. using System.Text;
    28. namespace MyService
    29. {
    30.     public class Service1 : IService1
    31.     {
    32.         public List<MyEmployee> FindEmployee(string uid)
    33.         {
    34.             DataClasses1DataContext context = new DataClasses1DataContext();
    35.             var res = from r in context.MyEmployees where r.EmpID == uid select r;
    36.             return res.ToList();
    37.         }
    38.     }
    39. }

    40. Image15.gif

    41. Explanation of the code :
    42. 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)
    43.         <!--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>
    44.  </phoneNavigation:PhoneApplicationPage>
    45.     <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">        <Grid.RowDefinitions>            <RowDefinition Height="170"/>            <RowDefinition Height="*"/>        </Grid.RowDefinitions>
    46.         <!--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="{StaticResourcePhoneTextPageTitle2Style}"/>        </Grid>
    47.         <!--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>
    48. using System;
    49. using System.Collections.Generic;
    50. using System.Linq;
    51. using System.Net;
    52. using System.Windows;
    53. using System.Windows.Controls;
    54. using System.Windows.Documents;
    55. using System.Windows.Input;
    56. using System.Windows.Media;
    57. using System.Windows.Media.Animation;
    58. using System.Windows.Shapes;
    59. using Microsoft.Phone.Controls;

    60. namespace MyClientWin7
    61. {
    62.     public partial class MainPage : PhoneApplicationPage
    63.     {
    64.         public MainPage()
    65.         {
    66.             InitializeComponent();

    67.             SupportedOrientations = SupportedPageOrientation.Portrait |SupportedPageOrientation.Landscape;
    68.         }

    69.         private void button1_Click(object sender, RoutedEventArgs e)
    70.         {
    71.             string s = textBox1.Text;
    72.             this.Content = new Page1(s);

    73.         }
    74.     }
    75. }

    76. Image24.gif

    77. Explanation of the code:

    78. 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.
    79. (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.)
    80. using System;
    81. using System.Collections.Generic;
    82. using System.Linq;
    83. using System.Net;
    84. using System.Windows;
    85. using System.Windows.Controls;
    86. using System.Windows.Documents;
    87. using System.Windows.Input;
    88. using System.Windows.Media;
    89. using System.Windows.Media.Animation;
    90. using System.Windows.Shapes;
    91. using Microsoft.Phone.Controls;
    92. using MyClientWin7.ServiceReference1;

    93. namespace MyClientWin7
    94. {
    95.     public partial class Page1 : PhoneApplicationPage
    96.     {
    97.         public Page1(string s)
    98.         {
    99.             InitializeComponent();
    100.             Service1Client proxy = new Service1Client();
    101.             proxy.FindEmployeeCompleted += newEventHandler<FindEmployeeCompletedEventArgs>(proxy_FindEmployeeCompleted);
    102.             proxy.FindEmployeeAsync(s);

    103.         }
    104.      void proxy_FindEmployeeCompleted(object sender, FindEmployeeCompletedEventArgse)
    105.         {
    106. }

    107. Image25.gif

    108. Explanation of the code:

    109. 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.
    110. The proxy_ FindEmployeeCompleted event sets the ItemSource property of the list box with the return value of the operation contract.
    111. <ListBox Height="444" HorizontalAlignment="Left" Margin="20,81,0,0" Name="listBox1"VerticalAlignment="Top" Width="434" >
    112.                 <ListBox.ItemTemplate>
    113.                     <DataTemplate>
    114.                         <StackPanel Orientation="Horizontal">
    115.                             <TextBlock Text="{Binding EmpID}"/>
    116.                             <TextBlock Text="{Binding EmpFirstName}"/>
    117.                             <TextBlock Text="{Binding EmpLastName}"/>
    118.                             <TextBlock Text=" " />
    119.                             <TextBlock Text="{Binding PhoneNo}"/>
    120.                         </StackPanel>
    121.                     </DataTemplate>
    122.                 </ListBox.ItemTemplate>
    123.             </ListBox>
    124. Explanation of the code:

    125. 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. 
    (Sưu tầm)