Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Gauge for SharePoint
Search :       Advanced Search »
Home » Silverlight » Photo Viewer in Silverlight 4 using SQL Server 2008

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.

Author Rank :
Page Views : 7913
Downloads : 405
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PhotoViewer.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

 

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Author
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Database script?? by kojikabutosv On December 4, 2010
Hi... how try the example with out database script? thanks!
Reply | Email | Modify 
Image path by tai On October 20, 2011
I can't get image url from my database. please help me.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.