Displaying Images in Silverlight 4 DataGrid using Converter

Posted by: Mahesh Sabnis , on 9/30/2010, in Category Silverlight 2, 3, 4 and 5
Views: 30270
Abstract: Silverlight 4 being a technology for Line-Of-Business (LOB) application has provided lots of features to developers. One of the nice features is implementing value converters.
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:
image_1
Conclusion: Using the IValueConverter, professional looking applications can be developed in Silverlight.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

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 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 eBook 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 the 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!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years 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). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by T Gus on Friday, October 8, 2010 2:53 PM
Great Article - The Code - download link does not work though!
Comment posted by Bach on Tuesday, September 13, 2011 8:36 PM
Dear Sir,
Could you provide your completed solution?

Thanks!
Comment posted by Bach on Tuesday, September 13, 2011 8:36 PM
Dear Sir,
Could you provide your completed solution?

Thanks!
Comment posted by Francesco on Sunday, March 18, 2012 10:36 AM
:):):) the your post has saved me :):):)

very much thankful... Thanks
Comment posted by Altivo on Thursday, March 29, 2012 1:50 PM
How sort data if i use IValueConverter ?
When i click on column header - nothing happened if i use IValueConverter. :-(
Comment posted by Sarah on Monday, March 10, 2014 5:21 AM
Thanks for the post, I want to delete the selected item from the Grid, how can I do that, with your method?
I was able to delete/Update the selected item from the dataGrid but once I used the MyRef, I cant' do that anymore?
Any ideas Please
Comment posted by Sarah on Monday, March 10, 2014 6:26 AM
Thanks for the post, I want to delete the selected item from the Grid, how can I do that, with your method?
I was able to delete/Update the selected item from the dataGrid but once I used the MyRef, I cant' do that anymore?
Any ideas Please
Comment posted by Sarah on Monday, March 10, 2014 6:27 AM
Thanks for the post, I want to delete the selected item from the Grid, how can I do that, with your method?
I was able to delete/Update the selected item from the dataGrid but once I used the MyRef, I cant' do that anymore?
Any ideas Please
Comment posted by Ramesh on Friday, October 10, 2014 4:56 AM
kindly send your complete application or DB script pls . I do understand the plow of data.It is a nice artical ever i read .

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook