The Windows Phone 7 (WP7) Developer Toolkit RTW provides an excellent mechanism to built Rich UX applications on mobile devices (phone). One of the interesting aspect of WP7 programming is that it provides the Silverlight platform for application development. I am a great fan of Silverlight and WPF development and I am going to adopt a similar programming mechanism with WP7, for consuming WCF service and perform the data communication.
In this article, I have designed a WCF service which makes a call to a Database and reads data from the table. This table contains Images stored in binary form and through the WCF service, we make the byte array data available to the WP7 application.
I am using SQL Server 2008 and the Table schema is as below: The name of the table is ‘ImageEmployee’:
Creating a WCF Service
Step 1: Open VS2010 and create a blank solution, name it as ‘WP7_FIrstApp’. In the solution add a WCF service application, name it as ‘WCF_DataServiceApp’.
Step 2: Open IService1.cs and define the following Interface and DataContract:
C#
[ServiceContract]
public interface IService
{
[OperationContract]
ImageEmployee GetEmpByEmpNo(int EmpNo);
}
[DataContract]
public class ImageEmployee
{
[DataMember]
public int EmpNo { get; set; }
[DataMember]
public string EmpName { get; set; }
[DataMember]
public decimal Salary { get; set; }
[DataMember]
public int DeptNo { get; set; }
[DataMember]
public byte[] EmpImage { get; set; }
}
VB.NET (Converted Code)
<ServiceContract>
Public Interface IService
<OperationContract>
Function GetEmpByEmpNo(ByVal EmpNo As Integer) As ImageEmployee
End Interface
<DataContract>
Public Class ImageEmployee
<DataMember>
Public Property EmpNo() As Integer
<DataMember>
Public Property EmpName() As String
<DataMember>
Public Property Salary() As Decimal
<DataMember>
Public Property DeptNo() As Integer
<DataMember>
Public Property EmpImage() As Byte()
End Class
Step 3: Open Service1.Svc and implement the above service contract, ‘IService’ interface as shown below:
C#
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace WCF_DataServiceApp
{
public class Service : IService
{
public ImageEmployee GetEmpByEmpNo(int EmpNo)
{
var Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
Conn.Open();
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Select * from ImageEmployee where EmpNo=@EmpNo";
Cmd.Parameters.AddWithValue("@EmpNo", EmpNo);
var Reader = Cmd.ExecuteReader();
ImageEmployee objImgEmp = new ImageEmployee();
while (Reader.Read())
{
objImgEmp.EmpNo = Convert.ToInt32(Reader["EmpNo"]);
objImgEmp.EmpName = Reader["EmpName"].ToString();
objImgEmp.Salary = Convert.ToInt32(Reader["Salary"]);
objImgEmp.DeptNo = Convert.ToInt32(Reader["DeptNo"]);
objImgEmp.EmpImage = (byte[])Reader["EmpImage"];
}
Reader.Close();
Conn.Close();
return objImgEmp;
}
}
}
VB.NET (Converted Code)
Imports System
Imports System.Collections.Generic
Imports System.Data.SqlClient
Namespace WCF_DataServiceApp
Public Class Service
Implements IService
Public Function GetEmpByEmpNo(ByVal EmpNo As Integer) As ImageEmployee
Dim Conn = New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
Conn.Open()
Dim Cmd = New SqlCommand()
Cmd.Connection = Conn
Cmd.CommandText = "Select * from ImageEmployee where EmpNo=@EmpNo"
Cmd.Parameters.AddWithValue("@EmpNo", EmpNo)
Dim Reader = Cmd.ExecuteReader()
Dim objImgEmp As New ImageEmployee()
Do While Reader.Read()
objImgEmp.EmpNo = Convert.ToInt32(Reader("EmpNo"))
objImgEmp.EmpName = Reader("EmpName").ToString()
objImgEmp.Salary = Convert.ToInt32(Reader("Salary"))
objImgEmp.DeptNo = Convert.ToInt32(Reader("DeptNo"))
objImgEmp.EmpImage =CType(Reader("EmpImage"), Byte())
Loop
Reader.Close()
Conn.Close()
Return objImgEmp
End Function
End Class
End Namespace
The above method makes a call to the database table ‘ImageEmployee’ and by comparing EmpNo, the record for the employee is returned.
Step 4: Build the service and publish it on IIS.
Creating Windows Phone (WP7) application
In this task, we will create a WP7 client application. I am using VS2010 and WP7 RTW development environment.
Step 1: In the solution created above, add a new WP7 application as shown below in the screenshot:
The template for ‘Silverlight for Windows Phone’ will appear after downloading WP7 Developer Toolkit RTW and installing it on your machines
Step 2: Since WP7 provides Silverlight development platform, you can design the UI using XAML. By default, the MainPage.Xaml provides Grid with name ‘LayoutRoot’ which contains StackPanel of name ‘TitlePanel’. The XAML elements in the StackPanel is as shown below:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Received Form WCF" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Employee Information" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="48" FontWeight="ExtraBold" />
</StackPanel>
Step 3: The Grid ‘LayoutRoot’ also contains one more Grid as child element of name ‘ContentPanle’. Put the following XAML elements in this grid.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="71*" />
<RowDefinition Height="67*" />
<RowDefinition Height="64*" />
<RowDefinition Height="70*" />
<RowDefinition Height="170*" />
<RowDefinition Height="197*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="221*" />
<ColumnDefinition Width="235*" />
</Grid.ColumnDefinitions>
<TextBlock Height="30" HorizontalAlignment="Left" Margin="29,23,0,0" Name="textBlock1" Text="EmpNo" VerticalAlignment="Top" Width="151" />
<TextBox Grid.Column="1" Grid.RowSpan="2" Height="72" HorizontalAlignment="Left" Margin="5,6,0,0" Name="txteno"
Text="{Binding EmpNo}" VerticalAlignment="Top" Width="229" />
<TextBox Grid.RowSpan="3" Height="72" HorizontalAlignment="Left" Margin="6,68,0,0" Name="txtename"
Text="{Binding EmpName}" VerticalAlignment="Top" Width="229" Grid.Column="1" />
<TextBox Grid.RowSpan="3" Height="72" HorizontalAlignment="Left" Margin="3,65,0,0" Name="txtsal"
Text="{Binding Salary}" VerticalAlignment="Top" Width="229" Grid.Column="1" Grid.Row="1" />
<TextBox Grid.RowSpan="2" Height="72" HorizontalAlignment="Left" Margin="6,0,0,0" Name="txtdno"
Text="{Binding DeptNo}" VerticalAlignment="Top" Width="229" Grid.Column="1" Grid.Row="3" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="29,20,0,0" Name="textBlock2" Text="EmpName" VerticalAlignment="Top" Width="151" Grid.Row="1" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="29,18,0,0" Name="textBlock3" Text="Salary" VerticalAlignment="Top" Width="151" Grid.Row="2" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="29,21,0,0" Name="textBlock4" Text="DeptNo" VerticalAlignment="Top" Width="151" Grid.Row="3" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="29,37,0,0" Name="textBlock5" Text="Image" VerticalAlignment="Top" Width="151" Grid.Row="4" />
<Image Grid.Column="1" Grid.Row="4" Height="136" HorizontalAlignment="Left"
Margin="16,16,0,0" Name="imgEmp" Stretch="Fill"
VerticalAlignment="Top" Width="200"
Source="{Binding EmpImage}"/>
<Button Content="Emp Details" Grid.Column="1" Grid.Row="5" Height="72" HorizontalAlignment="Left" Margin="16,29,0,0" Name="btnGetEmpDetails" VerticalAlignment="Top" Width="160" FontSize="20" Click="btnGetEmpDetails_Click" />
</Grid>
</Grid>
All textboxes are bound to properties defined in the DataContract class of the WCF service.
The UI design of the application we are building is as shown below:
Step 4: Now we will add the WCF service reference in the WP7 application. After installing WP7, you will get the utility ‘SlSvcUtil.exe’ in the following path:
C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Tools
This tool helps to generate the WCF proxy class and configuration file as shown below:
Copy the generated files from the above folder and paste it in the WP7 project.
Step 5: Since the WCF service returns ‘EmpImage’ as ‘Byte[]’ array, it needs to be converted to an image. To do this, I have added a converter class in the WP7 project as shown below.
C#
using System;
using System.Windows.Data;
using System.IO;
using System.Windows.Media.Imaging;
namespace WP7_ClientApp
{
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
MemoryStream memStream = new MemoryStream((byte[])value);
memStream.Seek(0, SeekOrigin.Begin);
BitmapImage empImage = new BitmapImage();
empImage.SetSource(memStream);
return empImage;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
VB.NET (Converted Code)
Imports System
Imports System.Windows.Data
Imports System.IO
Imports System.Windows.Media.Imaging
Namespace WP7_ClientApp
Public Class ImageConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
Dim memStream As New MemoryStream(CType(value, Byte()))
memStream.Seek(0, SeekOrigin.Begin)
Dim empImage As New BitmapImage()
empImage.SetSource(memStream)
Return empImage
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class
End Namespace
Step 6: This converter class needs to be used in the MainPage.xaml. To do this open ‘MainPage.xaml’ and declare an object on the converter class in the resources of the Grid ‘ContentPanel’ as shown below:
<Grid.Resources>
<src:ImageConverter x:Key="imgConverter"></src:ImageConverter>
</Grid.Resources>
Step 7: Now bind the above object in the image element in MainPage.xaml as shown below:
<Image Grid.Column="1" Grid.Row="4" Height="136" HorizontalAlignment="Left"
Margin="16,16,0,0" Name="imgEmp" Stretch="Fill"
VerticalAlignment="Top" Width="200"
Source="{Binding EmpImage,Converter={StaticResource imgConverter}}"/>
Step 8: Open MainPage.xaml.cs and write the following code:
At the class level declare the WCF proxy reference as shown below:
C#
ServiceClient Proxy;
VB.NET (Converted Code)
Dim Proxy As ServiceClient
Declare the WCF proxy object on the loaded event as below:
C#
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Proxy = new ServiceClient();
}
VB.NET (Converted Code)
Public Sub New()
InitializeComponent()
AddHandler Loaded, AddressOf MainPage_Loaded
End Sub
Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
Proxy = New ServiceClient()
End Sub
On the ‘Emp Details’ button click event, write the following code:
C#
private void btnGetEmpDetails_Click(object sender, RoutedEventArgs e)
{
Proxy.GetEmpByEmpNoCompleted += new EventHandler<GetEmpByEmpNoCompletedEventArgs>(Proxy_GetEmpByEmpNoCompleted);
Proxy.GetEmpByEmpNoAsync(Convert.ToInt32(txteno.Text));
}
void Proxy_GetEmpByEmpNoCompleted(object sender, GetEmpByEmpNoCompletedEventArgs e)
{
if (e.Result != null)
{
ImageEmployee objImgEmp = e.Result;
ContentPanel.DataContext = objImgEmp;
}
}
VB.NET (Converted Code)
Private Sub btnGetEmpDetails_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
AddHandler Proxy.GetEmpByEmpNoCompleted, AddressOf Proxy_GetEmpByEmpNoCompleted
Proxy.GetEmpByEmpNoAsync(Convert.ToInt32(txteno.Text))
End Sub
Private Sub Proxy_GetEmpByEmpNoCompleted(ByVal sender As Object, ByVal e As GetEmpByEmpNoCompletedEventArgs)
If e.Result IsNot Nothing Then
Dim objImgEmp As ImageEmployee = e.Result
ContentPanel.DataContext = objImgEmp
End If
End Sub
The above code makes an async call to the WCF service and get the Employee object. This object using ‘DataContext’ is bound with the ‘ContentPanel’ grid.
Step 9: Run the application, you will get the WP7 Emulator with UI as shown below:
When you click on the ‘EmpNo’ textbox, the keypad will be displayed as shown below:
Click on ‘&123’ button you will get the numeric keypad as shown above in column 2.
Type 101 in the textbox and click on any other part of the Emulator; the keypad will disappear. Now click on ‘Emp Details’ button and the following results will be displayed.
This article has been editorially reviewed by Suprotim Agarwal.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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