Tuesday, March 22, 2011

Silverlight - Web Service in Silverlight

In this article i will show you how to create a web service in Silverlight 4.

Step 1
Download Silverlight 4 tools from the following link

Download Silverlight 4 toolkit from the following link
http://silverlight.codeplex.com/

Note : Select only April 2010 Toolkit Silverlight 4


Step 2
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 3
Attach a northwind database into MS-SQL server.

Step 4
Create a Silverlight Application and give the solution name as WebServiceinSilverlight.




Click on image for better view

Note: Select Web Project Type as ASP.NET Web site.

Step 5
Select a ASP.net Web application(WebServiceinSilverlight.Web) and Add a Linq to Sql class,right click on solution then Add new Item,select LINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this



Click on image for better view

Step 6
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this















Click on image for better view




















Click on image for better view

Visual stdio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.

Step 7
Create a employee object that will use LINQ to SQL to map to this table.go to the Server explorer,select northwind database,go to the tables and select Employees table,it is look like this


























Click on image for better view

Drag and drop Employee table from Server explorer onto the design surface of the O/R Designer,it is look like this


















Click on image for better view

Step 8
Select a ASP.net Web application(WebServiceinSilverlight.Web) and Add  a new asmx file for web service and name it as WSEmployee.asmx,it is look like this




















Click on image for better view
Step 9
In the below code snippet, write GetEmployeeData() method of a WSEmployee class to return Employee data from northwind database,it is look like this





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WSEmployee
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class WSEmployee : System.Web.Services.WebService {

    public WSEmployee () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    /// <summary>
    /// Get Employee data from Northwind Database
    /// </summary>
    /// <returns>List</returns>
    [WebMethod]
    public List<Employee> GetEmployeeData()
    {
        try
        {
            // Create a Object of NorthwindDataContext
            NorthwindDCDataContext DC = new NorthwindDCDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.Trim());

            // Create a Select Query
            var Query = from Q in DC.Employees
                        select new Employee
                        {
                            FirstName=Q.FirstName,
                            LastName=Q.LastName,
                            City=Q.City
                        };

         
            return Query.ToList<Employee>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }
    
}

Step 10
Next step is add reference of web service in the Silverlight Application(WebServiceinSilverlight).Right click the Silverlight project and add a Service reference,it is look like this


























Click on image for better view

Step 11
Add a web service in the silverlight application.Add Service Reference dialog box will open and click on Discover button and give the namesapace name as SREmployee.























Click on image for better view

Now web service is ready,Lets design the Silverlight Page.

Step 12
Add a DataGrid and button on page,it is look like this
<Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid AutoGenerateColumns="False" Height="249" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dgEmployee" VerticalAlignment="Top" Width="376" ItemsSource="{Binding}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="LastName" Binding="{Binding LastName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="City" Binding="{Binding City}" Width="Auto" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <Button Content="Data" Height="23" HorizontalAlignment="Left" Margin="313,270,0,0" Name="btnData" VerticalAlignment="Top" Width="75" Click="btnData_Click" />
    </Grid>






















In this DataGrid we bind the employee data on button click event.

Step 13
In Code Behind,On btnData click event call the service,it is look like this

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;

namespace WebServiceinSilverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Call a Web Service
                SREmployee.WSEmployeeSoapClient WSProxy = new SREmployee.WSEmployeeSoapClient();

                // Wire up the Async DataCompleted  handler
                WSProxy.GetEmployeeDataCompleted += new EventHandler<SREmployee.GetEmployeeDataCompletedEventArgs>(WSProxy_GetEmployeeDataCompleted);

                // Call a WebService Method
                WSProxy.GetEmployeeDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        void WSProxy_GetEmployeeDataCompleted(object sender, SREmployee.GetEmployeeDataCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    // Bind Employee Data in DataGrid
                    dgEmployee.DataContext = e.Result;
                    // The arguments provide us a e.Result object that represents the return type, in this case a List object.
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

       
    }
}


Run the Project.

Output




















Full XAML Code

<UserControl x:Class="WebServiceinSilverlight.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"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid AutoGenerateColumns="False" Height="249" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dgEmployee" VerticalAlignment="Top" Width="376" ItemsSource="{Binding}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="LastName" Binding="{Binding LastName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="City" Binding="{Binding City}" Width="Auto" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <Button Content="Data" Height="23" HorizontalAlignment="Left" Margin="313,270,0,0" Name="btnData" VerticalAlignment="Top" Width="75" Click="btnData_Click" />
    </Grid>
</UserControl>



Download
Download Source Code

Wednesday, March 16, 2011

Silverlight - Data Binding in Accordion Control in Silverlight

In my last article i discussed how to use Silverlight Accordion Control without data binding.In this post i will show you how to use data binding in Silverlight accordion control.i will show you same example.(Image Gallery)

Step 1
You need to download Silverlight 4 toolkit from the following link and install in you'r system
http://silverlight.codeplex.com/

Note : Select only April 2010 Toolkit Silverlight 4

Step 2
Create a Silverlight application and give the solution name as AccordianControl_Dynamic.

Step 3
Create a New Folder in the solution and give folder name as Images. Add five images like this






















Step 4
Add XML file in the solution from the solution explorer and give the file name as ImageData.xml.


Step 5
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called

ImageName and ImagePath.



<?xml version="1.0" encoding="utf-8" ?>
<Images>

  <Image>
    <ImageName>Kakashi Hatake</ImageName>
    <ImagePath>../Images/Kakashi011.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Jiraiya Sama</ImageName>
    <ImagePath>../Images/1_Jiraiya003.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Naruto</ImageName>
    <ImagePath>../Images/Naruto.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Gara</ImageName>
    <ImagePath>../Images/gara.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Yamato</ImageName>
    <ImagePath>../Images/yamato.jpg</ImagePath>
  </Image>

</Images>

Step 6
Create a ImageEntity class in the solution,it is an entity class,it is look like this

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace AccordianControl_Dynamic
{
    public class ImageEntity
    {

        #region property

        public String ImageName
        {
            get;
            set;
        }

        public String ImagePath
        {
            get;
            set;
        }

        #endregion

    }
}

Step 7
Add a System.Xml.Linq Assemble reference to the project.Right click on the project name in Solution Explorer, select Add Reference and System.Xml.Linq on the .NET Tab and select OK button.






















Click on image for better View.

Step 8
Create a ImageView static class in a solution for retriving data from XML document.it is look like this


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;

namespace AccordianControl_Dynamic
{
    public static class ImagesView
    {
        public static List<ImageEntity> GetAllImagesData()
        {
            try
            {
                // Load Xml Document
                XDocument XDoc = XDocument.Load("ImageData.xml");

                // Query for retriving all Images data from XML
                var Query = from Q in XDoc.Descendants("Image")
                            select new ImageEntity
                            {
                                ImageName = Q.Element("ImageName").Value,
                                ImagePath = Q.Element("ImagePath").Value
                            };

                // return images data
                return Query.ToList<ImageEntity>();
              
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}


Step 9
Drag and drop a Accordion control from toolbox on page.it is look like this

<Grid x:Name="LayoutRoot">

        <toolkit:Accordion x:Name="ImageAccordian" Width="640" ExpandDirection="Right" VerticalAlignment="Stretch">
    
        </toolkit:Accordion>
        
        
        
</Grid>

Set ExpandDirection as Right.Default ExpandDirection is Down.

Step 10
Create a Data Template for Accordion Control.it is look like this


<UserControl.Resources>
        
        <!--For Change the header Name-->
        <Style x:Key="AccordionItemStyle" TargetType="toolkit:AccordionItem">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding ImageName}" FontFamily="Arial"  FontSize="16"  FontWeight="Bold" Foreground="Red"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        
        <!--For Change the Content-->
        <DataTemplate x:Key="AccordionContentDataTemplate">
            <Grid>
                <Image Source="{Binding ImagePath}" Width="400" Height="400"></Image>
            </Grid>
        </DataTemplate>
    </UserControl.Resources>
    

Step 11
Apply Data Template on Accordion Control,it is look like this

<Grid x:Name="LayoutRoot">

        <toolkit:Accordion x:Name="ImageAccordian" Width="640" ExpandDirection="Right" VerticalAlignment="Stretch" ItemsSource="{Binding}" ItemContainerStyle="{StaticResource AccordionItemStyle}" ContentTemplate="{StaticResource AccordionContentDataTemplate}" >
    
        </toolkit:Accordion>
        
    </Grid>

ItemSource Property- Gets or sets a collection used to generate the content of the itemsControl.

ItemContainerStyle Property - Gets or sets the style that is used when rendering the item containers.

ContentTemplate Property - Gets or sets the data template that is used to display the content of the ContentControl.

Step 12
Now Bind the data in Accordion Control in code behind,it is look like this


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;

namespace AccordianControl_Dynamic
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            // Required to initialize variables
            InitializeComponent();

            BindImages(); // Bind Images in Constructor
        }

        #region Method
        /// <summary>
        /// Bind Images and Image name in Accordian Control
        /// </summary>
        private void BindImages()
        {
            try
            {
                // Store Data in List Box.
                List<ImageEntity> ListImagesObj = ImagesView.GetAllImagesData();

                // Check the List Object Count
                if (ListImagesObj.Count > 0)
                {
                    // Bind data in accordian control
                    ImageAccordian.DataContext = ListImagesObj;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion
    }
}


Run the Project.


Output
1.





















Click on Image for Better View

2.




















Click on Image for Better View

3.




Click on Image for Better View

4.


Click on Image for Better View

5.




Full XAML Code


<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
    x:Class="AccordianControl_Dynamic.MainPage"
    Width="640" Height="480">
    
    <UserControl.Resources>
        
        <!--For Change the header Name-->
        <Style x:Key="AccordionItemStyle" TargetType="toolkit:AccordionItem">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding ImageName}" FontFamily="Arial"  FontSize="16"  FontWeight="Bold" Foreground="Red"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        
        <!--For Change the Content-->
        <DataTemplate x:Key="AccordionContentDataTemplate">
            <Grid>
                <Image Source="{Binding ImagePath}" Width="400" Height="400"></Image>
            </Grid>
        </DataTemplate>
    </UserControl.Resources>
    
    
    
    <Grid x:Name="LayoutRoot">

        <toolkit:Accordion x:Name="ImageAccordian" Width="640" ExpandDirection="Right" VerticalAlignment="Stretch" ItemsSource="{Binding}" ItemContainerStyle="{StaticResource AccordionItemStyle}" ContentTemplate="{StaticResource AccordionContentDataTemplate}" >
    
        </toolkit:Accordion>
        
    </Grid>
</UserControl>


Download
Download Source Code