Photo Viewer in Silverlight 4 using SQL Server 2008


This article will describes you how to use photo viewer in Silverlight using SQL Server 2008 database. I had search many time but could get more samples using SQL Server. So I decided let's use Silverlight with SQL Server 2008. So here is my first article in Silverlight with SQL Server 2008.

First of all make a new project using Silverlight 4.

Image1.jpg

Image1.

Here is my database table screenshot.

Image2.jpg

Image2.

Let's add a new WCF service in Web project.

 Image3.jpg

Image3. 

Web.Config.

<connectionStrings>

    <add name="ConnectionString" connectionString="Data Source=RAJ\MSSQLSERVER2008;UID=sa;pwd=wintellect;Initial Catalog=Test;" providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

ImagesService.svc.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Data.SqlClient;

using System.Configuration;

 

namespace PhotoViewer.Web

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ImagesService" in code, svc and config file together.

    public class ImagesService : IImagesService

    {

 

        public void DoWork()

        {

        }

 

        public List<Pictures> GetImageList()

        {

            //string conn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Test.MDF;Integrated Security=True;User Instance=True";

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            List<Pictures> returnedImageCollection = new List<Pictures>();

            using (SqlConnection con = new SqlConnection(conn))

            {

                using (SqlCommand cmd = new SqlCommand())

                {

                    //cmd.CommandText = "GetAllImages";

                    cmd.CommandText = "Select * From Images";

                    cmd.Connection = con;

                    //cmd.CommandType = System.Data.CommandType.StoredProcedure;                    

                    con.Open();

                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())

                    {

                        Pictures pictures = new Pictures();

                        pictures.Name = Convert.ToString(reader["Name"].ToString());

                        pictures.Title = Convert.ToString(reader["Title"]);

                        pictures.Url = Convert.ToString(reader["Url"]);

                        pictures.Description = Convert.ToString(reader["Description"]);

                        returnedImageCollection.Add(pictures);

                    }

                }

                return returnedImageCollection;

            }

        }

    }

}

 

 

IImagesService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

 

namespace PhotoViewer.Web

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IImagesService" in both code and config file together.

    [ServiceContract]

    public interface IImagesService

    {

        [OperationContract]

        void DoWork();

 

        [OperationContract]

        List<Pictures> GetImageList();

    }

}

 

 

Add service refrence:

 Image4.jpg

 

Image4.

 

Discover service reference and click OK.

Image5.jpg 

Image5.

 

When you add service reference in application, it automatically generates clientconfig file which looks like this.

 

ServiceReferences.ClientConfig

 

<configuration>

    <system.serviceModel>

        <bindings>

            <basicHttpBinding>

                <binding name="BasicHttpBinding_IImagesService" maxBufferSize="2147483647"

                    maxReceivedMessageSize="2147483647">

                    <security mode="None" />

                </binding>

            </basicHttpBinding>

        </bindings>

        <client>

            <endpoint address="http://localhost:32722/ImagesService.svc"

                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IImagesService"

                contract="ServiceReference1.IImagesService" name="BasicHttpBinding_IImagesService" />

        </client>

    </system.serviceModel>

</configuration>

 

 

 

 

Now let's start work on main Page.xaml

<UserControl x:Class="PhotoViewer.MainPage"

    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:controlstoolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"

    mc:Ignorable="d" Height="554" Loaded="UserControl_Loaded" Width="642">

    <UserControl.Resources >

        <ControlTemplate x:Key="pevButtonControlTemplate" TargetType="Button">

            <Grid Background="Black">

                <Image HorizontalAlignment="Left" Source="prev.jpg" Width="31" Height="23" Stretch="Fill" VerticalAlignment="Center"></Image>               

            </Grid>

        </ControlTemplate>

        <ControlTemplate x:Key="nextButtonControlTemplate" TargetType="Button">

            <Grid Background="Black">               

                <Image HorizontalAlignment="Left" Height="23" Source="next.jpg" Stretch="Fill" VerticalAlignment="Center" Width="31"/>

            </Grid>

        </ControlTemplate>

        <Storyboard x:Name="MouseEnterStoryboard"  >

            <DoubleAnimation To="100" Duration="0:0:0.3" Storyboard.TargetProperty="Height" Storyboard.TargetName="ImageDetailGrid"/>

        </Storyboard>

        <Storyboard x:Name="MouseLeaveStoryboard"  Completed="MouseLeaveStoryboard_Completed">

            <DoubleAnimation To="0" Duration="0:0:0.1" Storyboard.TargetProperty="Height" Storyboard.TargetName="ImageDetailGrid"/>

        </Storyboard>

    </UserControl.Resources>

    <Border BorderBrush="#3F3F3F" CornerRadius="4" BorderThickness="1" Width="600"

                    Background="#3F3F3F" Margin="22,23,20,31" Padding="6,6,6,6" Height="500">

        <Grid x:Name="LayoutRoot" Margin="0,0,0,1">

            <Grid.Background>

                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                    <GradientStop Color="#FF3E61C7" Offset="1"/>

                    <GradientStop Color="White"/>

                </LinearGradientBrush>

            </Grid.Background>

            <Grid.ColumnDefinitions>

                <ColumnDefinition />

                <ColumnDefinition Width="600"/>

                <ColumnDefinition />

            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions >

                <RowDefinition />

                <RowDefinition Height="500"/>

                <RowDefinition />

            </Grid.RowDefinitions>

            <Grid Grid.Row="1" Grid.Column="1" Background="White" Margin="0,0,14,15" >

                <Grid.RowDefinitions >

                    <RowDefinition />

                    <RowDefinition Height="80"/>

                </Grid.RowDefinitions>               

                <Image Source="{Binding ElementName=ImagesListBox, Path=SelectedItem.Url}"  Margin="5,5,6,5" Stretch="Fill" />

                <controlstoolkit:BusyIndicator x:Name="BusyWindow" Content="" BusyContent="Please Wait While Loading Data..."/>

                <Grid VerticalAlignment="Bottom" Height="0" Margin="4,0,6,5" x:Name="ImageDetailGrid" >

                    <Grid.RowDefinitions >

                        <RowDefinition Height="20"/>

                        <RowDefinition Height="30"/>

                        <RowDefinition Height="1*"/>

                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions >

                        <ColumnDefinition />

                    </Grid.ColumnDefinitions>

                    <Border Opacity=".5" Background="Black" Grid.RowSpan ="3" Grid.ColumnSpan ="2"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Border>

                    <Border Background="Transparent" BorderBrush="Black" BorderThickness="1" Grid.RowSpan ="3" Grid.ColumnSpan ="2"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Border>

                    <TextBlock Text="{Binding ElementName=ImagesListBox, Path=SelectedItem.Name}" Grid.Column="1" Grid.Row="0" FontWeight="Bold" VerticalAlignment="Center" Foreground="White" Margin="5,0,0,0"></TextBlock>

                    <TextBlock Text="{Binding ElementName=ImagesListBox, Path=SelectedItem.Description}" Grid.Column="1" TextWrapping="Wrap" Grid.Row="1" VerticalAlignment="Center" Foreground="White" Margin="5,0,0,0" Height="30"></TextBlock>

                </Grid>

                <Grid Grid.Row="1" Height="80" Background="Black">

                    <ListBox x:Name="ImagesListBox" Height="80" Background="Transparent" Margin="2,1,1,1" VerticalAlignment="Center" BorderBrush="{x:Null}"  Style="{StaticResource DefaultListBoxStyle}" ItemContainerStyle="{StaticResource DefaultListBoxItemStyle}" SelectionChanged="ImagesListBox_SelectionChanged" Width="510">

                        <ListBox.ItemsPanel >

                            <ItemsPanelTemplate >

                                <StackPanel Orientation="Horizontal" >

                                </StackPanel>

                            </ItemsPanelTemplate>

                        </ListBox.ItemsPanel>

                        <ListBox.ItemTemplate >

                            <DataTemplate >                               

                                <StackPanel>                                                      

                                    <Image Source="{Binding Path=Url}" Stretch="Fill"  Margin="1,1,1,1" Width="65" Height="65"></Image>

                                </StackPanel>

                            </DataTemplate>

                        </ListBox.ItemTemplate>                       

                    </ListBox>

                    <Button HorizontalAlignment="Left" Background="Black" VerticalAlignment="Top" Height="75"

                            x:Name="LeftArrowButton" Click="LeftArrowButton_Click" Template="{StaticResource pevButtonControlTemplate}">                      

                    </Button>

                    <Button VerticalAlignment="Top" Height="75" HorizontalAlignment="Right"

                            x:Name="RightArrowButton" Click="RightArrowButton_Click" Template="{StaticResource nextButtonControlTemplate}">                       

                    </Button>

                    <!--<Popup x:Name="PopupWindow" Height="200" Width="200" VerticalAlignment="Top">

                        <Border CornerRadius="10" Background="Silver" BorderThickness="2" BorderBrush="Black" Height="200" Width="200">

                            <StackPanel Margin="10">

                                <Image Source="{Binding ElementName=ImagesListBox, Path=SelectedItem.Url}" Stretch="Fill"  Margin="1,1,1,1" Width="190" Height="190"></Image>                               

                            </StackPanel>

                        </Border>

                    </Popup>-->

                </Grid>

            </Grid>

        </Grid>

    </Border>

</UserControl>

 

Page.xaml.cs

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 PhotoViewer.ServiceReference1;

using System.Threading;

 

namespace PhotoViewer

{

    public partial class MainPage : UserControl

    {

        int PageNumber = 0;

        int PageIndex = 7;

 

 

        public MainPage()

        {

            InitializeComponent();           

        }

 

        private void ImagesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)

        {

            MouseLeaveStoryboard.Begin();           

        }

 

        private void UserControl_Loaded(object sender, RoutedEventArgs e)

        {

            int busyDisplay = 3;

            int delayDisplay = 500;

            BusyWindow.DisplayAfter = TimeSpan.FromMilliseconds(delayDisplay);

            BusyWindow.IsBusy = true;

            ThreadPool.QueueUserWorkItem((state) =>

            {

                Thread.Sleep(busyDisplay * 1000);

                Dispatcher.BeginInvoke(() => BusyWindow.IsBusy = false);

            });

            ImagesServiceClient svc = new ImagesServiceClient();

            svc.GetImageListCompleted +=new EventHandler<GetImageListCompletedEventArgs>(svc_GetImageListCompleted);

            svc.GetImageListAsync();

        }

 

        void svc_GetImageListCompleted(object sender, GetImageListCompletedEventArgs e)

        {

            ImagesListBox.ItemsSource = e.Result.Skip((PageNumber) * PageIndex).Take(7);

            //ImagesListBox.ItemsSource = e.Result.Skip(PageNumber).Take(7);

            ImagesListBox.SelectedIndex = 0;           

        }

 

        private void MouseLeaveStoryboard_Completed(object sender, EventArgs e)

        {

            MouseEnterStoryboard.Begin();

        }

 

        private void LeftArrowButton_Click(object sender, RoutedEventArgs e)

        {

            if (PageNumber > 0)

            {

                PageNumber = PageNumber - 1;

                ImagesServiceClient svc = new ImagesServiceClient();

                svc.GetImageListCompleted += new EventHandler<GetImageListCompletedEventArgs>(svc_GetImageListCompleted);

                svc.GetImageListAsync();

            }

        }

 

        private void RightArrowButton_Click(object sender, RoutedEventArgs e)

        {

          

                PageNumber = PageNumber + 1;

                ImagesServiceClient svc = new ImagesServiceClient();

                svc.GetImageListCompleted += new EventHandler<GetImageListCompletedEventArgs>(svc_GetImageListCompleted);

                svc.GetImageListAsync();

          

        }

    }

}

 

 

So finally we are done with code and time to run the project and see the result.

 Image6.jpg

Image6.

 

First it shows busy indicator until all images load. We put BusyIndicator code. Final result looks like this.

Image7.jpg 

Image7.

When you click on any thumbnail image.

Image8.jpg

Image8.

So finally we are done here with Photo Viewer control in Silverlight 4 using SQL Server database.

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all