Thursday, July 7, 2011

Silverlight - Image Gallery in Silverlight

In this article i will show you how to create a Dynamic Image Gallery in Silverlight application.


Step 1 

Create a Silverlight application and give the solution name as SolSilverlightImageGallery.


Step 2
Save images in Folder,Create a New Folder in the Solution and give folder name as Images,it is look like this


Click on image for better view


Step 3
Add XML file in the solution and give the file name as ImageData.xml,it is look like this




Click on image for better view


Step 4

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.



    Gaara
    ../Images/Gaara.png
  

  
    Choji Akimichi
    ../Images/Choji.png
  

  
    Jiraiya
    ../Images/Jiraiya.jpg
  

  
    Kakashi Hatake
    ../Images/Kakashi.png
  


    Kiba Inuzuka
    ../Images/Kiba.png
  

    Naruto Uzumaki
    ../Images/Naruto.jpg
  


     Neji Hyuuga
     ../Images/Neji.jpg
  


     Rock Lee
    ../Images/RockLee.jpg
  


     Sai
    ../Images/Sai.jpg
  


  Shikamaru Nara
    ../Images/Shikamaru.jpg
  


  Shino Aburame
    ../Images/Shino.jpg
  


  Yamato
    ../Images/Yamato.jpg
  



Step 5
Create an ImageEntity Class in the solution,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 SolSilverlightImageGallery
{
    public class ImageEntity
    {

        #region property

        public String ImageName
        {
            get;
            set;
        }

        public String ImagePath
        {
            get;
            set;
        }

        #endregion

    }
}

Step 6
Add a System.Xml.Linq Assemble reference to the project.Right click on the project name in Solution Explorer, select Add Reference and Select System.Xml.Linq  and select OK button,it is look like this


Click on image for better view


Step 7
Create a ImageView static class in a solution for retrieving 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 SolSilverlightImageGallery
{
    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 8
Now design Image gallery on Page.Drag and drop ListBox Control from Toolbox and set a Background Color,it is look like this
<Grid x:Name="LayoutRoot">
  <ListBox x:Name="LsImageGallery">
   <ListBox.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
     <GradientStop Color="Black"/>
     <GradientStop Color="#FF1E2A2F" Offset="1"/>
    </LinearGradientBrush>
   </ListBox.Background>
  
  </ListBox>
 </Grid>


Click on image for better view


Step 9
Create a UniformGrid control in silverlight for display images.Unfortunately UniformGrid Control does nor exists in silverlight aplication either in Silverlight SDK or in Silverlight ToolKit.
Create a class for UniformGrid Control,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 SolSilverlightImageGallery
{
    public class UniformGrid : Panel
    {
        /// 
        /// Gets or sets the computed row value.
        /// 
        private int ComputedRows { get; set; }

        /// 
        /// Gets or sets the computed column value.
        /// 
        private int ComputedColumns { get; set; }

        /// 
        /// Initializes a new instance of UniformGrid.
        /// 
        public UniformGrid()
        {
        }

        /// 
        /// Gets or sets the number of first columns to leave blank.
        /// 
        public int FirstColumn
        {
            get { return (int)GetValue(FirstColumnProperty); }
            set { SetValue(FirstColumnProperty, value); }
        }

        /// 
        /// The FirstColumnProperty dependency property.
        /// 
        public static readonly DependencyProperty FirstColumnProperty =
                DependencyProperty.Register(
                        "FirstColumn",
                        typeof(int),
                        typeof(UniformGrid),
                        new PropertyMetadata(0, OnIntegerDependencyPropertyChanged));

        /// 
        /// Gets or sets the number of columns in the grid. A value of zero 
        /// indicates that the count should be dynamically computed based on the
        /// number of rows and the number of non-collapsed children in the grid.
        /// 
        public int Columns
        {
            get { return (int)GetValue(ColumnsProperty); }
            set { SetValue(ColumnsProperty, value); }
        }

        /// 
        /// DependencyProperty for the Columns property.
        /// 
        public static readonly DependencyProperty ColumnsProperty =
                DependencyProperty.Register(
                        "Columns",
                        typeof(int),
                        typeof(UniformGrid),
                        new PropertyMetadata(0, OnIntegerDependencyPropertyChanged));

        /// 
        /// Validate the new property value and silently revert if the new value
        /// is not appropriate. Used in place of WPF value coercian by the 
        /// dependency properties in UniformGrid.
        /// 
        /// 













The dependency object.
        /// 













The dependency property.
        private static void OnIntegerDependencyPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            // Silently coerce the value back to >= 0 if negative.
            if (!(e.NewValue is int) || (int)e.NewValue < 0)
            {
                o.SetValue(e.Property, e.OldValue);
            }
        }

        /// 
        /// Gets or sets the number of rows in the grid. A value of zero 
        /// indicates that the row count should be dynamically computed based on
        /// the number of columns and the number of non-collapsed children in
        /// the grid.
        /// 
        public int Rows
        {
            get { return (int)GetValue(RowsProperty); }
            set { SetValue(RowsProperty, value); }
        }

        /// 
        /// The Rows DependencyProperty.
        /// 
        public static readonly DependencyProperty RowsProperty =
                DependencyProperty.Register(
                        "Rows",
                        typeof(int),
                        typeof(UniformGrid),
                        new PropertyMetadata(0, OnIntegerDependencyPropertyChanged));

        /// 
        /// Compute the desired size of the UniformGrid by measuring all of the
        /// children with a constraint equal to a cell's portion of the given
        /// constraint. The maximum child width and maximum child height are 
        /// tracked, and then the desired size is computed by multiplying these
        /// maximums by the row and column count.
        /// 
        /// 













The size constraint.
        /// Returns the desired size.
        protected override Size MeasureOverride(Size constraint)
        {
            UpdateComputedValues();

            Size childConstraint = new Size(constraint.Width / ComputedColumns, constraint.Height / ComputedRows);
            double maxChildDesiredWidth = 0.0;
            double maxChildDesiredHeight = 0.0;

            //  Measure each child, keeping track of max desired width & height.
            for (int i = 0, count = Children.Count; i < count; ++i)
            {
                UIElement child = Children[i];
                child.Measure(childConstraint);
                Size childDesiredSize = child.DesiredSize;
                if (maxChildDesiredWidth < childDesiredSize.Width)
                {
                    maxChildDesiredWidth = childDesiredSize.Width;
                }
                if (maxChildDesiredHeight < childDesiredSize.Height)
                {
                    maxChildDesiredHeight = childDesiredSize.Height;
                }
            }
            return new Size((maxChildDesiredWidth * ComputedColumns), (maxChildDesiredHeight * ComputedRows));
        }

        /// 
        /// Arrange the children of the UniformGrid by distributing space evenly
        /// among the children, making each child the size equal to a cell
        /// portion of the arrangeSize parameter.
        /// 
        /// 













The arrange size.
        /// Returns the updated Size.
        protected override Size ArrangeOverride(Size arrangeSize)
        {
            Rect childBounds = new Rect(0, 0, arrangeSize.Width / ComputedColumns, arrangeSize.Height / ComputedRows);
            double xStep = childBounds.Width;
            double xBound = arrangeSize.Width - 1.0;
            childBounds.X += childBounds.Width * FirstColumn;

            // Arrange and Position each child to the same cell size
            foreach (UIElement child in Children)
            {
                child.Arrange(childBounds);
                if (child.Visibility != Visibility.Collapsed)
                {
                    childBounds.X += xStep;
                    if (childBounds.X >= xBound)
                    {
                        childBounds.Y += childBounds.Height;
                        childBounds.X = 0;
                    }
                }
            }

            return arrangeSize;
        }

        /// 
        /// If the Rows or Columns values are set to 0, dynamically compute the
        /// values based on the actual number of non-collapsed children.
        /// 
        /// 
        /// In the case when both Rows and Columns are set to 0, the Rows and 
        /// Columns will be equal, laying out a square grid.
        /// 
        private void UpdateComputedValues()
        {
            ComputedColumns = Columns;
            ComputedRows = Rows;

            // Reset the first column. This is the same logic performed by WPF.
            if (FirstColumn >= ComputedColumns)
            {
                FirstColumn = 0;
            }

            if ((ComputedRows == 0) || (ComputedColumns == 0))
            {
                int nonCollapsedCount = 0;
                for (int i = 0, count = Children.Count; i < count; ++i)
                {
                    UIElement child = Children[i];
                    if (child.Visibility != Visibility.Collapsed)
                    {
                        nonCollapsedCount++;
                    }
                }
                if (nonCollapsedCount == 0)
                {
                    nonCollapsedCount = 1;
                }
                if (ComputedRows == 0)
                {
                    if (ComputedColumns > 0)
                    {
                        ComputedRows = (nonCollapsedCount + FirstColumn + (ComputedColumns - 1)) / ComputedColumns;
                    }
                    else
                    {
                        ComputedRows = (int)Math.Sqrt(nonCollapsedCount);
                        if ((ComputedRows * ComputedRows) < nonCollapsedCount)
                        {
                            ComputedRows++;
                        }
                        ComputedColumns = ComputedRows;
                    }
                }
                else if (ComputedColumns == 0)
                {
                    ComputedColumns = (nonCollapsedCount + (ComputedRows - 1)) / ComputedRows;
                }
            }
        }
    }
}

Step 10
Add class reference in user control tag.so we can access uniformgrid control in XAML,it is look like this
xmlns:Local="clr-namespace:SolSilverlightImageGallery"

Finally it is look like this
<UserControl
 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:Local="clr-namespace:SolSilverlightImageGallery"
 mc:Ignorable="d"
 x:Class="SolSilverlightImageGallery.MainPage"
 d:DesignWidth="640" d:DesignHeight="480">

Step 11
Create a DataTemplate for ListBox Control in UserControl.Resource to bind Image Path and Image Name in Image and TextBlock Control,it is look like this
<DataTemplate x:Key="ImageGalleryDataTemplate">
   <Grid>
    <Grid.RowDefinitions>
     <RowDefinition Height="0.833*"/>
     <RowDefinition Height="0.167*"/>
    </Grid.RowDefinitions>
    
    <Border Grid.Row="0" Grid.Column="0" BorderBrush="#FFADABA8" BorderThickness="2"  Width="200" Height="150" Padding="10" Margin="10" CornerRadius="10">
     <!--Bind Image Path in Image Control-->
     <Image Source="{Binding ImagePath}" Stretch="Fill"  HorizontalAlignment="Center">
      <!--View Large Image on Image Control Tooltip-->
      <ToolTipService.ToolTip>
       <Grid>
        <Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="300" Width="300"></Image>
       </Grid>
      </ToolTipService.ToolTip>
     </Image>
    </Border>
     <!--Bind Image Name in TextBlock Control-->
    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding ImageName}"  Foreground="Orange" HorizontalAlignment="Center"></TextBlock>
      
   </Grid>
  </DataTemplate>

Step 12
Create a ItemPanelTemplate for ListBox Control to Display Images in uniformGrid Control,it is look like this


<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
   
   <!--Display Images on UniformGrid Panel-->
   <Local:UniformGrid Columns="4" HorizontalAlignment="Center" VerticalAlignment="Stretch"></Local:UniformGrid>
   
  </ItemsPanelTemplate>

Finally DataTemplate and ItemPanelTemplate look like this
<UserControl.Resources>
  <DataTemplate x:Key="ImageGalleryDataTemplate">
   <Grid>
    <Grid.RowDefinitions>
     <RowDefinition Height="0.833*"/>
     <RowDefinition Height="0.167*"/>
    </Grid.RowDefinitions>
    
    <Border Grid.Row="0" Grid.Column="0" BorderBrush="#FFADABA8" BorderThickness="2"  Width="200" Height="150" Padding="10" Margin="10" CornerRadius="10">
     <!--Bind Image Path in Image Control-->
     <Image Source="{Binding ImagePath}" Stretch="Fill"  HorizontalAlignment="Center">
      <!--View Large Image on Image Control Tooltip-->
      <ToolTipService.ToolTip>
       <Grid>
        <Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="300" Width="300"></Image>
       </Grid>
      </ToolTipService.ToolTip>
     </Image>
    </Border>
     <!--Bind Image Name in TextBlock Control-->
    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding ImageName}"  Foreground="Orange" HorizontalAlignment="Center"></TextBlock>
      
   </Grid>
  </DataTemplate>
  
  <ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
   
   <!--Display Images on UniformGrid Panel-->
   <Local:UniformGrid Columns="4" HorizontalAlignment="Center" VerticalAlignment="Stretch"></Local:UniformGrid>
   
  </ItemsPanelTemplate>
 </UserControl.Resources>

Step 13
Apply DataTemplate and ItemPanelTemplate on ListBox Control,it is look like this
<ListBox x:Name="LsImageGallery" ItemsSource="{Binding}" ItemTemplate="{StaticResource ImageGalleryDataTemplate}" ItemsPanel="{StaticResource ImageGalleryItemsPanelTemplate}">
   <ListBox.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
     <GradientStop Color="Black"/>
     <GradientStop Color="#FF1E2A2F" Offset="1"/>
    </LinearGradientBrush>
   </ListBox.Background>
  
  </ListBox>


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


ItemTemplate Property - Gets or sets the DataTemplate used to display each item.


ItemPanel Property -  Gets or sets the template that defines the panel that controls the layout of items.



Step 14
Now Bind the data in ListBox Control in Code Behind,it is look like this
using System;
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;

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

   try
   {
    BindImages(); // Call Bind Image Function
   }
   catch (Exception ex)
   {
    MessageBox.Show(ex.Message); 
   }
  }

  /// <summary>
  /// Bind Images in List Box
  /// </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 List Box
     LsImageGallery.DataContext = ListImagesObj;    
    }
   }
   catch (Exception ex)
   {
    throw new Exception(ex.Message);
   }
  }
 }
}

Run the Project


Output


Click on image for better view


Move the Mouse Pointer to the Image



Full XAML Code
<UserControl
 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:Local="clr-namespace:SolSilverlightImageGallery"
 mc:Ignorable="d"
 x:Class="SolSilverlightImageGallery.MainPage"
 d:DesignWidth="640" d:DesignHeight="480">
 
 <UserControl.Resources>
  <DataTemplate x:Key="ImageGalleryDataTemplate">
   <Grid>
    <Grid.RowDefinitions>
     <RowDefinition Height="0.833*"/>
     <RowDefinition Height="0.167*"/>
    </Grid.RowDefinitions>
    
    <Border Grid.Row="0" Grid.Column="0" BorderBrush="#FFADABA8" BorderThickness="2"  Width="200" Height="150" Padding="10" Margin="10" CornerRadius="10">
     <!--Bind Image Path in Image Control-->
     <Image Source="{Binding ImagePath}" Stretch="Fill"  HorizontalAlignment="Center">
      <!--View Large Image on Image Control Tooltip-->
      <ToolTipService.ToolTip>
       <Grid>
        <Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="300" Width="300"></Image>
       </Grid>
      </ToolTipService.ToolTip>
     </Image>
    </Border>
     <!--Bind Image Name in TextBlock Control-->
    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding ImageName}"  Foreground="Orange" HorizontalAlignment="Center"></TextBlock>
      
   </Grid>
  </DataTemplate>
  
  <ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
   
   <!--Display Images on UniformGrid Panel-->
   <Local:UniformGrid Columns="4" HorizontalAlignment="Center" VerticalAlignment="Stretch"></Local:UniformGrid>
   
  </ItemsPanelTemplate>
 </UserControl.Resources>

 <Grid x:Name="LayoutRoot">
  <ListBox x:Name="LsImageGallery" ItemsSource="{Binding}" ItemTemplate="{StaticResource ImageGalleryDataTemplate}" ItemsPanel="{StaticResource ImageGalleryItemsPanelTemplate}">
   <ListBox.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
     <GradientStop Color="Black"/>
     <GradientStop Color="#FF1E2A2F" Offset="1"/>
    </LinearGradientBrush>
   </ListBox.Background>
  
  </ListBox>
 </Grid>
</UserControl>

Download
Download Source Code

Sunday, July 3, 2011

JQuery - Formatting GridView Using JQuery

In this article i will show you how we can assign alternate background color of ASP.NET Grid Views rows using jQuery.


Step 1
Download JQuery Script from the following Link
http://code.jquery.com/jquery-1.6.1.min.js



Step 2
Create a Web Application and give the Solution name as SolFormattingGridView_Jquery


Step 3
Add a grid view control on page it is look like this
<div>
        
        <asp:GridView ID="GvDeveloper" runat="server" >
        </asp:GridView>
        
    </div>

Step 4
Add jQuery file Reference inside the head tag of the page,it is look like this
<head runat="server">
    <title>Formatting GridView using Jquery</title>

    
    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>

</head>

Step 5
Create a CSS for formatting GridView,it is look like this


Step 6
Write a JQuery script for formatting a gridview,it is look like this


jQuery provides  ":odd" and ":even" selector. ":odd" selector which selects only odd elements. ":even" selector which selects even elements.
in short  Rows which are having odd numbers like Row1, Row3, Row5 etc. and even number like   Row2,Row4,Row6 etc.
So we need to filter out all the odd rows and even rows for assign the color.To filter the rows, we will use filter() method of jQuery, which takes selector as argument and returns the elements which matches the selector.
then Adds the specified css classes to each of the set of matched elements.


Run the project.


Note: Dose not show code behind on post.


Output


Click on image for better view


Full Code
          .aspx Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Formatting GridView using Jquery</title>

    <style type="text/css">
        
        .HeaderColor
        {
            background-color:#292421;
            color:#FFFAFA;
            }
        
        .AlterNativeRowColor
       {
           background-color:#EEC591;
           }
           
           .DefaultRowColor
           {
               background-color:#9C661F;
               }    
    </style>

    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">

        $(document).ready(function () {

            // Header Color
            $("#GvDeveloper th").addClass("HeaderColor");

            // Alternative Row Color
            $("#GvDeveloper tr").filter(":odd").addClass("AlterNativeRowColor");

            // Default Row Color 
            $("#GvDeveloper tr").filter(":even").addClass("DefaultRowColor");

           

        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:GridView ID="GvDeveloper" runat="server" >
        </asp:GridView>
        
    </div>
    </form>
</body>
</html>

Download
Download Source Code

Saturday, July 2, 2011

Silverlight - WCF in Silverlight 4

In my last article i discussed about how to use Web service in Silverlight 4 application.Web Service in Silverlight.
now in this article i will show you how to use WCF service in silverlight 4 application.


WCF Service
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or 
word sent as XML, or as complex as a stream of binary data.



In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

What is Difference between Web service and WCF Service ?

  • Web services can be hosted in IIS as well as outside of the IIS. While WCF service can be hosted in IIS, Windows activation service,Self Hosting,WAS and on lots of protocols like Named Pipe,TCP and others.Many people disagree how we can host the web service outside of the IIS but Here is the article.http://msdn.microsoft.com/en-us/library/aa529311.aspx.
  • In Web Services Web Service attribute will added  on the top of class. In WCF there will be a Service Contract attributes will be there. Same way Web Method attribute are added in top of method of Web service while in WCF Service Operation Contract will added on the top method.
  • In Web service System.XML.Serialization is supported while in the WCF Service System.RunTime.Serialization is supported.
  • WCF Services can be multithreaded via ServiceBehavior class while web service can not be.
  • WCF Services supports different type of bindings like BasicHttpBinding, WSHttpBinding, WSDualHttpBinding etc.while Web services only used soap or xml for this.
  • Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive that identifies the class that contains the code for the service and the assembly in which it is located while in WCF.WCF services can readily be hosted within IIS 5.1 or 6.0, the Windows Process Activation Service (WAS) that is provided as part of IIS 7.0, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol.
  • The major difference is that Web Services Use XmlSerializer But WCF Uses DataContractSerializer.

Let See how to create a WCF 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
Create a Silverlight Application and give the solution name as SolSilverlight_WCF.


Click on image for better view

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

Step 3
Select a ASP.net Web application(SolSilverlight_WCF.Web) and Add a WCF Service,right click on solution,select Add New Item,select WCF Service from installed Visual Studio templates and name it DeveloperService.svc and click on add button.

It will add two .cs (named IDeveloperService.cs and DeveloperService.cs)



Click on image for better view

Step 4
Create a Developer entity class in App_Code folder,it is look like this 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// Description for Developer
/// 
public class Developer
{
    #region Property

    public String DeveloperName
    {
        get;
        set;
    }

    public String Speciality
    {
        get;
        set;
    }

    public int Experience
    {
        get;
        set;
    }

    #endregion
}

Step 5
Now we will make some modification to the OperationContract.Remove default DoWork method from the IDeveloperService interface.Add a new Method named as GetDeveloperData,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IDeveloperService" in both code and config file together.
[ServiceContract]
public interface IDeveloperService
{
    [OperationContract]
    List<Developer> GetDeveloperData(); // Get Developer Data and store in List Object
}

Step 6
Implement IDeveloperService interface in Developer service class,Add Developer information and store in list object,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "DeveloperService" in code, svc and config file together.
public class DeveloperService : IDeveloperService
{
    /// 
    ///  Get Developer Data
    /// 
    /// List
    public List<Developer> GetDeveloperData()
    {
        try
        {
            // Create List Object
            List<Developer> DeveloperObj = new List<Developer>();

            // Add Developer Data to the list object
            DeveloperObj.Add(new Developer() 
            { 
                DeveloperName="Bhushan Pawar",
                Speciality="ASP.net",
                Experience=5
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName="Ramdas Bhosale",
                Speciality="ASP.net",
                Experience=3
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName = "Koste Budinoski",
                Speciality="ASP.net MVC",
                Experience=5
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName="Kishor Naik",
                Speciality="WPF",
                Experience=3
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName = "Kedar Deshpande",
                Speciality = "MS-SQL Server",
                Experience = 1
            });


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

Step 7
Add a reference of  WCF Service in silverlight application(SolSilverlight_WCF).Right click the Silverlight project and add a Service reference,it is look like this




Click on image for better view


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




Click on image for better view


Now WCF service Ready now design silverlight page.


Step 9
Add a DataGrid and button on page,it is look like this
<Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="256*" />
            <RowDefinition Height="44*" />
        </Grid.RowDefinitions>
        <sdk:DataGrid x:Name="DgDeveloper" Grid.Row="0" Grid.Column="0" Margin="0,0,0,2" ItemsSource="{Binding}"></sdk:DataGrid>
        <Button x:Name="btnData" Grid.Row="1" Content="Data" Width="100" Height="30" HorizontalAlignment="Right" Click="btnData_Click" Margin="0,6,4,8" />
    </Grid>

Step 10
In Code Behind,On btnData click event call the WCF 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 SolSilverlight_WCF
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Call WCF Service
                DeveloperServiceReference.DeveloperServiceClient DServiceClientObj = new DeveloperServiceReference.DeveloperServiceClient();

                // Wire up the Async Completed  handler
                DServiceClientObj.GetDeveloperDataCompleted += new EventHandler<DeveloperServiceReference.GetDeveloperDataCompletedEventArgs>(DServiceClientObj_GetDeveloperDataCompleted);

                // Call WCF Method
                DServiceClientObj.GetDeveloperDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        void DServiceClientObj_GetDeveloperDataCompleted(object sender, DeveloperServiceReference.GetDeveloperDataCompletedEventArgs e)
        {
            try
            {
                // Bind the Developer Data in DataGrid
                DgDeveloper.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


Click on image for better view


Full XAML Code
<UserControl x:Class="SolSilverlight_WCF.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">
        <Grid.RowDefinitions>
            <RowDefinition Height="256*" />
            <RowDefinition Height="44*" />
        </Grid.RowDefinitions>
        <sdk:DataGrid x:Name="DgDeveloper" Grid.Row="0" Grid.Column="0" Margin="0,0,0,2" ItemsSource="{Binding}"></sdk:DataGrid>
        <Button x:Name="btnData" Grid.Row="1" Content="Data" Width="100" Height="30" HorizontalAlignment="Right" Click="btnData_Click" Margin="0,6,4,8" />
    </Grid>
</UserControl>

Download
Download Source Code

Friday, July 1, 2011

C#.net - Custom Attributes in C#.net

An attribute is an object that represents data you want to associate with an element in your program. The element to which you attach an attribute is referred to as the target of that attribute.
Attributes are special classes that can be applied to classes, properties, and methods at design time. Attributes provide a way to describe certain aspects of an elementor determine the behavior of other classes acting upon the element. Those descriptions and behaviors can then be accessed and examined at runtime. You can think of attributes as a way of adding special modifiers to your class members.


Let See how to create a Custom attribute in C#.net.


Step 1
Create a Console Application and give the solution name as  ConCustomAttribute.


Step 2
Declaring an Attribute,it is look like this
 [AttributeUsage(AttributeTargets.All,AllowMultiple=true)]
    public class DeveloperAttribute:System.Attribute
    {
    }

To create a custom attribute, derive your new custom attribute class from System.Attribute.
AttributeUsage is an attribute applied to attributes: a meta-attribute. It provides, if you will, meta-metadata--that is, data about the metadata. For the AttributeUsage attribute constructor, you pass two arguments. The first argument is a set of flags that indicate the target--in this case, the class and its constructor, fields, methods, and properties. The second argument is a flag that indicates whether a given element might receive more than one such attribute. In this example, AllowMultiple is set to true, indicating that class members can have more than one attributes assigned.


Step 3
Declaring Constructor and Properties,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConCustomAttribute
{
    [AttributeUsage(AttributeTargets.All,AllowMultiple=true)]
    public class DeveloperAttribute:System.Attribute
    {
        #region Enum

        /// 
        ///  User Defined Developer Name
        /// 
        public enum DeveloperName
        {
            BhushanPawar = 0,
            RamdasBhosale = 1,
            KosteBudinoski = 2,
            KishorNaik = 3
        };

        #endregion

        #region Constructor
        
        /// 
        ///  Blank Constructor
        /// 
        public DeveloperAttribute()
        {

        }

        /// 
        ///  Write a Attribute 
        /// 
        /// 






Specify Developer Name
        /// 






Specify the Date
        /// 






Specify the Comment
        public DeveloperAttribute(DeveloperName Developer,String Date,String Comment)
        {
            try
            {
                this.Developer = Developer;
                this.Date = Date;
                this.Comment = Comment;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

        #region Property
        /// 
        ///  Get and Set the Developer Name
        /// 
        public DeveloperName Developer
        {
            get;
            set;
        }

        /// 
        ///  Get and Set the Date
        /// 
        public String Date
        {
            get;
            set;
        }

        /// 
        ///  Get and Set the Comment   
        /// 
        public String Comment
        {
            get;
            set;
        }

        #endregion
    }

    
}

Declaring Constructor
Attributes are initialized with constructors in the same way as traditional classes.Every attribute must have at least one constructor.


Declaring Properties
If we want to define a named parameter or provide an easy way to return the values stored by your attribute, declare a property. Attribute properties should be declared as public entities with a description of the data type that will be returned. Define the variable that will hold the value of your property and associate it with the get and set methods.


Step 4
Using an Attribute in your class,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConCustomAttribute
{
    [Developer(DeveloperAttribute.DeveloperName.KishorNaik,"1/6/2011","Class Created by System")]
    public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Method1();
                Method2();
                Method3();
                Method4();
                Method5();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message); 
            }
        }

        #region Methods

        [Developer(DeveloperAttribute.DeveloperName.KishorNaik,"1/6/2011","Complete")]
        public static void Method1()
        {
            System.Console.WriteLine("Kishor naik Code"); 
        }

        [Developer(DeveloperAttribute.DeveloperName.RamdasBhosale, "1/6/2011", "Complete")]
        public static void Method2()
        {
            System.Console.WriteLine("Ramdas Bhosale Code");
        }

        [Developer(DeveloperAttribute.DeveloperName.KosteBudinoski, "1/6/2011", "Complete")]
        public static void Method3()
        {
            System.Console.WriteLine("Koste Budinoski Code");
        }

        [Developer(DeveloperAttribute.DeveloperName.BhushanPawar, "1/6/2011", "Complete")]
        public static void Method4()
        {
            System.Console.WriteLine("Bhushan Pawar Code");
        }

        [Developer(DeveloperAttribute.DeveloperName.KishorNaik, "1/6/2011", "I Passed below function to Koste Budinoski")]
        [Developer(DeveloperAttribute.DeveloperName.KosteBudinoski,"1/6/2011","I Received this function from kishor naik and i completed")]
        public static void Method5()
        {
            System.Console.WriteLine("kishor Naik Code");
            System.Console.WriteLine("Koste Budinoski Code");
        }

        #endregion
    }
}

Note
The new custom attribute in this example is named DeveloperAttribute. The convention is to append the word Attribute to your attribute name. The compiler supports this by allowing you to call the attribute with the shorter version of the name. Thus, you can write:
 [Developer(DeveloperAttribute.DeveloperName.KishorNaik,"1/6/2011","Complete")]

The compiler will first look for an attribute named Developer and, if it does not find that, will then look for DeveloperAttribute.


Download
Download Source Code