Wednesday, April 13, 2011

Select single column from Datatable

DataTable Dtcompany=new DataTable();

var countryList= Dtcompany.Rows.Cast().Select(row => row["Country"].ToString());

List CList= countryList.ToList();

Wednesday, April 6, 2011

Create Custom Control for Zooming And Panning in Silverlight

About This Article

This article provides the ability to interactively view high resolution images. You can zoom in and zoom out images. This Silverlight custom control enables deep zooming using Storyboard animation and smooth panning by handling the MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove events. The following features are included:
  • Deep zooming
  • Panning an image
  • Small window with thumb to view the exact location of the zoomed image

Background

Deep zooming is a pretty straightforward functionality and is done with the ScaleTransform property. Panning is done by setting the offset X and Y of the content. Silverlight 3 has a MultiscaleImage control for zooming multi-resolution images. It has a Source property to set multiple images.

In this article, I have created a custom zoom control for zooming and panning single images with animation for smooth panning.

Go Through Code

  1. Creating a custom zoom and pan control using Silverlight 4 Class Library
  2. First, create a class for zoom and pan which inherits from ContentControl and implements the IScrollInfo interface to move the thumb image within the area. This class contains Rectangle properties and animation methods for setting the content offset in X,Y coordinates with point zooming. It overrides the Size method to change the image size and scale of images. It has a Generic Style for setting the Template for the control with properties. This style is imported to the class.

  3. Using the control in a Silverlight application
    • Create a Silverlight application to use the zoom and pan custom Silverlight control.
    • In the Silverlight application, create an enum to handle the mouse modes.

      MouseHandlingMode.cs
      public enum MouseHandlingMode
      {
      None,
      DraggingRectangles,
      Panning,
      Zooming,
      DragZooming,
      }

      Create a class having Dependency Properties for setting the scale, width, height, offset etc., and implement the InotifyPropertyChanged interface to change the property value.

    • Declare all the Dependecy properties and the collection for the example.
    • public class DataModel : INotifyPropertyChanged
      {
      private ObservableCollection rectangles =
            new ObservableCollection();
      private double contentScale = 1;
      
      public static DataModel Instance
      {
        get{return instance; }
      }
      public ObservableCollection Rectangles
      {
        get{return rectangles; }
      }
      public double ContentScale
      {
        get{return contentScale; }
        set
        {
            contentScale = value;
            OnPropertyChanged("ContentScale");
        }
      }
      
      . . . . .
      }

      Create a Converter class to convert the scale value to percent for the Slider control:

      public class ScaleToPercentConverter : IValueConverter
      {
      public object Convert(object value, Type targetType, object parameter,
                          CultureInfo culture)
      {
        return (double)(int)((double)value * 100.0);
      }
      
      public object ConvertBack(object value, Type targetType, object parameter,
                              CultureInfo culture)
      {
        return (double)value / 100.0;
      }
      }

      Create a class for drawing the rectangle.

    • Now create the UserControl (HAEZoomingControl.xaml) to use the custom Silverlight control in the page.
      • Add the custom ZoomingAndPanning control to the page.
      • <ZoomAndPan:ZoomAndPanControl Grid.Row="0"
        x:Name="zoomAndPanControl"
        ContentScale= "{Binding Source={StaticResource
                   TypeProvider}, Path=Instance.ContentScale, Mode=TwoWay}"
        ContentOffsetX= "{Binding Source={StaticResource
                   TypeProvider}, Path=Instance.ContentOffsetX, Mode=TwoWay}"
        ContentOffsetY= "{Binding Source={StaticResource TypeProvider},
                   Path=Instance.ContentOffsetY, Mode=TwoWay}"
        ContentViewportWidth="{Binding Source={StaticResource TypeProvider},
                   Path=Instance.ContentViewportWidth, Mode=TwoWay}"
        ContentViewportHeight= "{Binding Source={StaticResource TypeProvider},
                   Path=Instance.ContentViewportHeight, Mode=TwoWay}"
        Background="{StaticResource pageBackground}"
        MouseMove="zoomAndPanControl_MouseMove"
        MouseWheel="zoomAndPanControl_MouseWheel"
        MouseLeftButtonDown="zoomAndPanControl_MouseLeftButtonDown"
        MouseLeftButtonUp="zoomAndPanControl_MouseLeftButtonUp">
        .
        .
        .
        </ZoomAndPan:ZoomAndPanControl>
      • Add ZoomIn, ZoomOut buttons and a Silder:
      • <Button x:Name="btnZoomOut"
        Grid.Column="8"
        Click="btnZoomOut_Click">-</Button>
         <Slider Grid.Column="10"
            x:Name="changeSlider"
            Minimum="{Binding MinPercentage}"
            Maximum="{Binding MaxPercentage}"
            Value= "{Binding ElementName=zoomAndPanControl,
                    Path=ContentScale, Converter={StaticResource
                    scaleToPercentConverter},Mode=TwoWay}" />
         <Button x:Name="btnZoomIn"
            Grid.Column="12"
            Click="btnZoomIn_Click">+</Button>
      • Add a popup the contains a small image in a grid and a thumb (rectangle) to view the zooming image position.
      • <Popup x:Name="MyPOP"
          MouseLeftButtonDown="MyPOP_MouseLeftButtonDown"
          IsOpen="False">
        <StackPanel Width="200" Height="200">
        <ZoomAndPan:ZoomAndPanControl x:Name="overview"
          Width="200" Height="200"
          Background="{StaticResource popupBackground}"
          SizeChanged="overview_SizeChanged"
          Opacity="0.9">
        <Grid Width="{Binding Source={StaticResource TypeProvider},
                      Path=Instance.ContentWidth,Mode=TwoWay}"
         Height="{Binding Source={StaticResource TypeProvider},
                 Path=Instance.ContentHeight,Mode=TwoWay}"
         SizeChanged="overview_SizeChanged">
        <Image x:Name="content2" Source="{Binding ImgSource}"
          VerticalAlignment="Center" HorizontalAlignment="Center"></Image>
        <Canvas>
        <Thumb x:Name="overviewZoomRectThumb"
          Canvas.Left="{Binding Source={StaticResource TypeProvider},
                       Path=Instance.ContentOffsetX, Mode=TwoWay}"
          Canvas.Top="{Binding Source={StaticResource TypeProvider},
                      Path=Instance.ContentOffsetY, Mode=TwoWay}"
          Width="{Binding Source={StaticResource TypeProvider},
                 Path=Instance.ContentViewportWidth, Mode=TwoWay}"
          Height="{Binding Source={StaticResource TypeProvider},
                  Path=Instance.ContentViewportHeight, Mode=TwoWay}"
          DragDelta="overviewZoomRectThumb_DragDelta"
          Opacity="0.5">
        <Thumb.Template>
        
        <ControlTemplate TargetType="Thumb">
        <Border BorderBrush="Black"
        BorderThickness="3" Background="Yellow"
        CornerRadius="3" />
        </ControlTemplate>
        </Thumb.Template>
        </Thumb>
        </Canvas>
        </Grid>
        </ZoomAndPan:ZoomAndPanControl>
        </StackPanel>
        </Popup>
    • In the code-behind (HAEZoomingControl.xaml.cs), write events for MouseMove, LeftButtonDown, LeftButtonUp, and DoubleClcik. The MouseDoubleClick event is not available in Silverlight so you can use MouseLeftButtonDown instead to count clicks.
    • For example:

      • Declare a timer variable to detect double click:
      • DispatcherTimer _timer;
      • Declare an interval variable:
      • private static int INTERVAL = 200;
      • In the default constructor, create an instance of the timer.
      • Collapse
        public HAEZoomingControl()
        {
        InitializeComponent();
        _timer = new DispatcherTimer();
        zoomAndPanControl.ContentOffsetY = 200;
        _timer.Interval = new TimeSpan(0, 0, 0, 0, INTERVAL);
        _timer.Tick += new EventHandler(_timer_Tick);
        }
      • Add an event to stop the timer:
      • void _timer_Tick(object sender, EventArgs e)
        {
        _timer.Stop();
        }
      • In the MouseLeftButtonDown event of the control use, times to check for double click.
      • Collapse
        private void zoomAndPanControl_MouseLeftButtonDown(
          object sender, MouseButtonEventArgs e)
        {
        if (zoomAndPanControl.ContentScale <= (MaxPercentage / 100))
          btnZoomIn.IsEnabled = true;
        if (zoomAndPanControl.ContentScale >= (MinPercentage / 100))
          btnZoomOut.IsEnabled = true;
        if (_timer.IsEnabled)
        {
          if (zoomAndPanControl.ContentScale <= (MaxPercentage / 100))
          {
              _timer.Stop();
              sb = new Storyboard();
              DoubleAnimation db = new DoubleAnimation();
              sb.Children.Add(db);
              sb.Completed += new EventHandler(sb_Completed);
              db.To = zoomAndPanControl.ContentScale + 0.2;
              db.Duration = new Duration(TimeSpan.FromSeconds(0.3));
              Storyboard.SetTarget(db, zoomAndPanControl);
              Storyboard.SetTargetProperty(db,
                         new PropertyPath("ContentScale"));
              sb.Begin();
          }
          else
          {
              btnZoomIn.IsEnabled = false;
          }
        }
        else
        {
          _timer.Start();
          if (zoomAndPanControl.ContentScale >= (MinPercentage / 100))
          {
              origZoomAndPanControlMouseDownPoint =
                      e.GetPosition(zoomAndPanControl);
              origContentMouseDownPoint = e.GetPosition(content);
              mouseHandlingMode = MouseHandlingMode.Panning;
              if (mouseHandlingMode != MouseHandlingMode.None)
              {
                  zoomAndPanControl.CaptureMouse();
                  e.Handled = true;
              }
          }
        }
        }
      • Write code for the other events and run the application.

OUTPUT

In the image below, you can see a zoomed image and a small image on the bottom-right side of the canvas to see the offset position of the zoomed image using the yellow thumb marker.

Download Source Code : Silverlight Zoom And Pan - 1.74 MB

Create function to Split Comma Seperated string and Return Table in Sql Server

Below is Code

ALTER FUNCTION [dbo].[SplitString] (
@String varchar(4000),
@Delimiter char(1)
) RETURNS @tmp TABLE(ProductId int,Quantity int)

AS 
BEGIN
   DECLARE @idx INT
   DECLARE @slice VARCHAR(4000)
   set @idx = 1
   IF len(@String)<1 or @String is null
        return
   WHILE @idx!= 0
   BEGIN
           set @idx = charindex(@Delimiter,@String)
           IF @idx!=0
                set @slice = left(@String,@idx - 1)
           ELSE
                 set @slice = @String
          IF len(@slice)>0
          BEGIN
                  declare @first int
                  declare @second int
                  declare @index int
                  set @index=charindex(':',@slice)
                  set @first=convert(int,left(@slice,@index - 1))
                  set @second=convert(int,right(@slice,len(@slice)-@index))
                  insert into @tmp(ProductId,Quantity)
                     values(@first,@second)
          END
          set @String = right(@String,len(@String) - @idx)
         IF len(@String) = 0
                  break
    END
    RETURN
END

select Multiple distinct coulmns from DataTable to Datarow Collection

DataTable dtCompany=new DataTable();
DataRow drComp;
IEnumerable<DataRow> drColl= dtCompany.AsEnumerable();
var v = (from s in drColl
             select new
            {
                   Country = s.Field<string>("Country"),
                   Province = s.Field<string>("Company State/Province")
            }) .Distinct().ToArray();

Convert Generic List collection to DataTable in C#

This post describes how to convert generic list collection to datatable

First Import following namespace

using System.Xml;
using System.IO;
using System.ComponentModel;

Setp 1 :First Create one Entity

public class City
{
        public string CityCode { get; set; }
        public string CityName { get; set; }
}
 
Step 2: Create Method to bind List Collection and Convert to Datatable

public void BindCityFromXML()
{
         string filepath = @"C:\city.xml";
         DataSet ds = new DataSet();
         ds.ReadXml(filepath);
         List<City> CityColl= new List<City>();
         DataTable CityTable = new DataTable();
         foreach (DataRow dr in ds.Tables[0].Rows)
        {
               City ct = new City();
               ct.CityCode = dr["code"].ToString();
               ct.CityName = dr["Name"].ToString();
               CityColl.Add(ct);
        }
        CityTable = ConvertTo<City>(CityColl);
}

Step 3: Write Following Method

public DataTable ConvertTo<T>(IList<T> lst)
{
      DataTable tbl = CreateTable<T>();
      Type entType = typeof(T);
      PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
      foreach (T item in lst)
     {
              DataRow row = tbl.NewRow();
             foreach (PropertyDescriptor prop in properties)
             {
                    row[prop.Name] = prop.GetValue(item);
             }
             tbl.Rows.Add(row);
      }
      return tbl;
}

public DataTable CreateTable<T>()
{
           Type entType = typeof(T);
           DataTable tbl = new DataTable(entType.Name);
           PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
           foreach (PropertyDescriptor prop in properties)
                 tbl.Columns.Add(prop.Name, prop.PropertyType); return tbl;
}