Silverlight 4 being a technology for Line-Of-Business (LOB) application has provided lots of features to developers. One of them is implementing value converters. In a Proof Of Concept (POC) assignment recently, I came across a requirement for displaying images in Silverlight DataGrid. I used IValueConverter for this requirement. In this article, I have also used a WCF service which reads images from the Database and returns a Byte array. This service is consumed by the Silverlight application, where a converter is implemented.
Creating WCF service
In this task we will create a WCF service using VS2010 targeted for .NET 4.0 framework.
Step 1: Open VS2010 and create a blank solution, name it as ‘SILV4_Converters’. To this solution, add a WCF service and name it as ‘WCF4_ImageService’.
Step 2: Add the following interface and the DataContract class in ‘IService1.cs’:
C#
using System.Runtime.Serialization;
using System.ServiceModel;
Namespace WCF4_ImageService
{
[ServiceContract]
Public Interface IService
{
[OperationContract]
ImageEmployee[] GetAllEmp();
}
[DataContract]
Public Class ImageEmployee
{
[DataMember]
public int EmpNo { get; set; }
[DataMember]
public string EmpName { get; set; }
[DataMember]
public int DeptNo { get; set; }
[DataMember]
public int Salary { get; set; }
[DataMember]
public byte[] EmpImage { get; set; }
}
}
VB.NET (Converted Code)
Imports System.Runtime.Serialization
Imports System.ServiceModel
Private Property WCF4_ImageService() As [Namespace]
<ServiceContract>
Public Interface IService
<OperationContract>
ImageEmployee() GetAllEmp()
<DataContract>
Public Class ImageEmployee
<DataMember>
public Integer EmpNo {get;set;}
<DataMember>
public String EmpName {get;set;}
<DataMember>
public Integer DeptNo {get;set;}
<DataMember>
public Integer Salary {get;set;}
<DataMember>
public Byte() EmpImage {get;set;}
End Property
Step 3: Implement the above interface in the Service class as shown below:
C#
public class Service : IService
{
public ImageEmployee[] GetAllEmp()
{
SqlConnection Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
Conn.Open();
SqlCommand Cmd = new SqlCommand("Select * from ImageEmployee",Conn);
SqlDataReader Reader = Cmd.ExecuteReader() ;
DataTable dt = new DataTable();
dt.Load(Reader);
ImageEmployee[] arrEmp = new ImageEmployee[dt.Rows.Count];
int count = 0;
foreach (DataRow Dr in dt.Rows)
{
arrEmp[count] = new ImageEmployee()
{
EmpNo = Convert.ToInt32(Dr["EmpNo"]),
EmpName = Dr["EmpName"].ToString (),
DeptNo = Convert.ToInt32(Dr["DeptNo"]),
Salary = Convert.ToInt32(Dr["Salary"]),
EmpImage = (byte[])Dr["EmpImage"]
};
count++;
}
Conn.Close();
return arrEmp;
}
}
VB.NET (Converted Code)
Public Class Service
Implements IService
Public Function GetAllEmp() As ImageEmployee()
Dim Conn As New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
Conn.Open()
Dim Cmd As New SqlCommand("Select * from ImageEmployee",Conn)
Dim Reader As SqlDataReader = Cmd.ExecuteReader()
Dim dt As New DataTable()
dt.Load(Reader)
Dim arrEmp(dt.Rows.Count - 1) As ImageEmployee
Dim count As Integer = 0
For Each Dr As DataRow In dt.Rows
arrEmp(count) = New ImageEmployee() With {.EmpNo = Convert.ToInt32(Dr("EmpNo")), .EmpName = Dr("EmpName").ToString (), .DeptNo = Convert.ToInt32(Dr("DeptNo")), .Salary = Convert.ToInt32(Dr("Salary")), .EmpImage = CType(Dr("EmpImage"), Byte())}
count += 1
Next Dr
Conn.Close()
Return arrEmp
End Function
End Class
Step 4: Build the WCF service and publish it on IIS (recommended on IIS 7.0).
Creating Silverlight 4 Client application.
In this task, I will create an SL 4 application with the converter.
Step 1: In the same solution created above, add a new SL 4 project and name it as ‘SILV4_Converters’.
Step 2: In the SL 4 project, add a WCF service reference and name it as ‘MyRef’.
Step 3: Now add a new class and name it as ‘ImageConveter’. Write the following code in it:
C#
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
MemoryStream memStream = new MemoryStream((byte[])value,false);
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)
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
Dim memStream As New MemoryStream(CType(value, Byte()),False)
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
Throw New NotImplementedException()
End Function
End Class
The above class implements ‘IValueConverter’ interface and its methods. The ‘Convert’ method reads byte array and converts it into a memory stream. This memory stream is then bound with the ‘BitMapImage’ so that it can be further bound with the Image UI element.
Step 4: In the SL application, add one more class and name it as ‘CurrencyConverter’. This class will be responsible for converting currency using the local settings with convert culture, in this case it is the Indian Currency (note I am using the old currency symbol):
C#
public class CurrencyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int Salary = int.Parse(value.ToString());
return Salary.ToString("C", culture);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
VB.NET
Public Class CurrencyConverter
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
Dim Salary As Integer = Integer.Parse(value.ToString())
Return Salary.ToString("C", culture)
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
Throw New NotImplementedException()
End Function
End Class
Step 5: Open MainPage.xaml and write the following XAML:
<UserControlx:Class="SILV4_Converters.MainPage_Images"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:src="clr-namespace:SILV4_Converters"
mc:Ignorable="d"
d:DesignHeight="300"d:DesignWidth="700"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
Loaded="UserControl_Loaded">
<UserControl.Resources>
<src:ImageConverterx:Key="ConvertToImage"></src:ImageConverter>
<src:CurrencyConverterx:Key="ConvertCurrency"></src:CurrencyConverter>
</UserControl.Resources>
<Gridx:Name="LayoutRoot"Background="White">
<sdk:DataGridAutoGenerateColumns="False"
Height="258"HorizontalAlignment="Left"
Margin="28,23,0,0"Name="dgEmp"
VerticalAlignment="Top"Width="645">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumnHeader="EmpNo"Binding="{Binding EmpNo}"></sdk:DataGridTextColumn>
<sdk:DataGridTextColumnHeader="EmpName"Binding="{Binding EmpName}"></sdk:DataGridTextColumn>
<sdk:DataGridTextColumnHeader="DeptNo"Binding="{Binding DeptNo}"></sdk:DataGridTextColumn>
<sdk:DataGridTextColumnHeader="Salary"
Binding="{Binding Salary,Converter={StaticResource ConvertCurrency},ConverterCulture=hi-IN}"></sdk:DataGridTextColumn>
<sdk:DataGridTemplateColumnHeader="EmpImage">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ImageHeight="50"Width="50"Source="{Binding EmpImage,Converter={StaticResource ConvertToImage}}"></Image>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</UserControl>
In the above XAML code, the Gray colored code represents the registration of the Converter classes in XAML and we are using it during binding, with the DataGrid columns.
Step 6: Open MainPage.xaml.cs and write the following binding code:
C#
MyRef.ServiceClient Proxy;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Proxy = new MyRef.ServiceClient();
Proxy.GetAllEmpCompleted += new EventHandler<MyRef.GetAllEmpCompletedEventArgs>(Proxy_GetAllEmpCompleted);
Proxy.GetAllEmpAsync();
}
void Proxy_GetAllEmpCompleted(object sender, MyRef.GetAllEmpCompletedEventArgs e)
{
dgEmp.ItemsSource = e.Result;
}
VB.NET (Converted Code)
Private Proxy As MyRef.ServiceClient
Private Sub UserControl_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
Proxy = New MyRef.ServiceClient()
AddHandler Proxy.GetAllEmpCompleted, AddressOf Proxy_GetAllEmpCompleted
Proxy.GetAllEmpAsync()
End Sub
Private Sub Proxy_GetAllEmpCompleted(ByVal sender As Object, ByVal e As MyRef.GetAllEmpCompletedEventArgs)
dgEmp.ItemsSource = e.Result
End Sub
Step 7: Run the application and the following result will be displayed:
Conclusion: Using the IValueConverter, professional looking applications can be developed in Silverlight.
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