Friday, December 28, 2012

Get Silverlight Application Last Updated Version & Date

  • Get Silverlight XAP Version
  •    
    1. Open App.xaml.cs file in your silverlight application and write following code.
      Assembly assembly = Assembly.GetExecutingAssembly(); 
      if (assembly.FullName != null) 
         string versionPart = assembly.FullName.Split(',')[1]; 
         string version = versionPart.Split('=')[1]; 
      } 

  • Get Silverlight XAP Last Updated Date.

    Below are steps to find XAP last modified date.

    1. open aspx page in which your xap file is called
    2. write following code in page_load event.

     
    
    
 
<script runat="server">
   
 public string VersionDate { get; set; }
 protected void Page_Load(object sender, EventArgs e)
 {
   string xapSource = @"ClientBin/SilverlightTest.xap";  
   string xapPath = 
       HttpContext.Current.Server.MapPath(@"") + @"\" + xapSource;
   DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xapPath);
   VersionDate = xapCreationDate.ToString(new 
           System.Globalization.CultureInfo("en-US").DateTimeFormat); 
        
 }    
 </script> 
    
         3. Pass date in initParams in object tag.
 
     <object data="data:application/x-silverlight-2," 
            type="application/x-silverlight-2"
            width="100%" height="100%">
        <param name="source" value="ClientBin/SilverlightTest.xap" />
        <param name="onError" value="onSilverlightError" />
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="5.0.61118.0" />
        <param name="autoUpgrade" value="true" />
        <param name="onLoad" value="pluginLoaded" />
        <param name="initParams" 
               value="<%= string.Format("VersionDate={0}",VersionDate) %>" />
        <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" 
                    style="text-decoration: none">
          <img src="http://go.microsoft.com/fwlink/?LinkId=161376" 
                    alt="Get Microsoft Silverlight"
                    style="border-style: none" />
        </a>
     </object> 
 
     
         4. Go to Silverlight application and open App.xaml.cs file.

         5. you will get passed parameter in Application_Startup event.
 
    private void Application_Startup(object sender, StartupEventArgs e)
    {   
   
       if (e.InitParams.ContainsKey("VersionDate"))
       {
            System.Globalization.DateTimeFormatInfo fmt = 
                (new System.Globalization.CultureInfo("en-US")).DateTimeFormat;    
            string versionDate = DateTime.Parse(e.InitParams["VersionDate"], fmt);
       }
    }

Wednesday, September 26, 2012

Convert Generic List to XML and Using XML DataType In Stored Procedure

Step 1 : First create generic class

 public class Employee
 {
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public string City { get; set; }
    public double Salary { get; set; }
 }
 

Step 2 : Create Collection of Employee and Convert into XML type

first add following references

System.Xml.Linq;
- System.Xml;
- System.Data.SqlTypes;


List<Employee> employeeCollection = new List<Employee>();

  var xEle = new XElement("Employees",
       from emp in employeeCollection
       select new XElement("Employee",
                   new XElement("EmployeeId", emp.EmployeeId),
                   new XElement("EmployeeName", emp.EmployeeName),
                   new XElement("City", emp.City),
                   new XElement("Salary",emp.Salary)
        )); 
 

Step 3 : Passing XML to Stored Procedure as Parameter


 SqlCommand cmd = new SqlCommand();
 cmd.Parameters.AddWithValue("@EmployeeXML", 
       new SqlXml(new XmlTextReader(xEle.ToString(), XmlNodeType.Document, null))); 

  

Step 4 : Using XML Data Type in Stored Procedure


CREATE PROCEDURE [dbo].[sp_GetEmployee]            
    @EmployeeXML XML=NULL
AS
BEGIN

    SET NOCOUNT ON;
    DECLARE @RETURNVAL INT=0
   

    DECLARE @emp TABLE(EmployeeId INT,EmployeeName VARCHAR(200),City VARCHAR(100),Salary FLOAT)
    INSERT INTO @emp
    SELECT  A.B.value('(EmployeeId)[1]', 'int' ) EmployeeId,
            A.B.value('(EmployeeName)[1]', 'varchar(200)' ) EmployeeName,
            A.B.value('(City)[1]', 'varchar(100)' ) City,
            A.B.value('(Salary)[1]', 'float' ) Salary
    FROM    @EmployeeXML.nodes('/Employees/Employee') A(B)

   SELECT * FROM @emp
END
 


Monday, August 20, 2012

Creating Random Password and Send Mail in C#

1 . Below is methods for Encrypt and Decrypt Data

 public static string EncryptData(string Message)
    {
        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes("hiren"));
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;
        byte[] DataToEncrypt = UTF8.GetBytes(Message);
        try
        {
            ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
            Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
        }
        finally
        {
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }
        return Convert.ToBase64String(Results);
    }
    public static string DecryptString(string Message)
    {
        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes("hiren"));
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;
        byte[] DataToDecrypt = Convert.FromBase64String(Message);
        try
        {
            ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
            Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
        }
        finally
        {
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }
        return UTF8.GetString(Results);
    }

2. Now Create Method for Creating New Password

public static string CreateRandomPassword(int passwordLength)
    {
        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
        char[] chars = new char[passwordLength];
        Random rd = new Random();
        for (int i = 0; i < passwordLength; i++)
        {
            chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }
        return new string(chars);
    }

3. Below is method to send newly created password.

 public string SendMail(string toAddress)
        {
            try
            {
                string newpwd =   CreateRandomPassword(7);
                string encrypted = EncryptData(newpwd);
                MailMessage mail = new MailMessage();
                mail.To.Add(toAddress);
                mail.From = new MailAddress(toAddress);
                mail.Subject = "your new  password";
                string Body = "Your new password is : <b>" + newpwd + "</b>";
                mail.Body = Body;
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Credentials = new System.Net.NetworkCredential("<Credential User email>","<Credential Password>");
                smtp.EnableSsl = true;
                smtp.Send(mail);

                return "Email Sent";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

Get Return Value From Confirm Box in C# (ASP.Net)

private void Button_click(object sender, EventArgs e)
    {
        var sbConfirm = new StringBuilder();
        string strMessage = string.Format("Are you sure to go ahead.");           
        sbConfirm.AppendFormat("var result = window.confirm('" + strMessage + "');\n");
        sbConfirm.Append("if (result)\n");
        sbConfirm.Append("__doPostBack('ConfirmTarget', result);\n");
        ClientScript.RegisterStartupScript(GetType(), "MyConfirmScript", sbConfirm.ToString(), true);
      
    }


In Page Load you have to write :

protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.GetPostBackEventReference(this, string.Empty);
         string eventTarget = Request["__EVENTTARGET"] ?? string.Empty;
         string eventArgument = Request["__EVENTARGUMENT"] ?? string.Empty;

            switch (eventTarget)
            {
                case "ConfirmTarget":
                    if (Convert.ToBoolean(eventArgument))
                    {
                          //.....your code
                    }
                    break;
            }
 }

Tuesday, July 10, 2012

Creating and Using EventLog in WindowService

First Drag and Drop EventLog component into Component design from ToolBox 


Event log (named : eventLog1) is added into you component class.


Create New Event Log in your window service Component class


 public EmployeeStatusService()
 {
     InitializeComponent();
     if (!System.Diagnostics.EventLog.SourceExists("MyLogInfo"))
     {
          System.Diagnostics.EventLog.CreateEventSource(
                    "MyLogInfo", "HirenLog");
     }
     eventLog1.Source = "SmartNetDeviceInfo";
     eventLog1.Log = "SmartNetLog";
 } 

Write Log entry on created log


 protected override void OnStart(string[] args)
 {
     eventLog1.WriteEntry("Service Started");
 } 

Page Transition within Frame in WPF

Create Resource for each RenderTransform

 <Window.Resources>
         <!-- Slide and Fade -->
        <Storyboard x:Key="SlideAndFadeIn">
            <ThicknessAnimation Duration="0:0:.75"
                                Storyboard.TargetProperty="Margin"
                                From="500,0,-500,0"
                                To="0"
                                DecelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.25"
                             Storyboard.TargetProperty="Opacity"
                             From="0"
                             To="1" />
        </Storyboard>
        <Storyboard x:Key="SlideAndFadeOut">
            <ThicknessAnimation Duration="0:0:.5"
                                Storyboard.TargetProperty="Margin"
                                To="-500,0,500,0"
                                AccelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.5"
                             Storyboard.TargetProperty="Opacity"
                             To="0" />
        </Storyboard>
        <!-- Fade -->
        <Storyboard x:Key="FadeIn">
            <DoubleAnimation Duration="0:0:.25"
                             Storyboard.TargetProperty="Opacity"
                             From="0"
                             To="1" />
        </Storyboard>
        <Storyboard x:Key="FadeOut">
            <DoubleAnimation Duration="0:0:.5"
                             Storyboard.TargetProperty="Opacity"
                             To="0" />
        </Storyboard>
        <!-- Slide -->
        <Storyboard x:Key="SlideIn">
            <ThicknessAnimation Duration="0:0:.75"
                                Storyboard.TargetProperty="Margin"
                                From="500,0,-500,0"
                                To="0"
                                DecelerationRatio=".9" />
        </Storyboard>
        <Storyboard x:Key="SlideOut">
            <ThicknessAnimation Duration="0:0:.5"
                                Storyboard.TargetProperty="Margin"
                                To="-500,0,500,0"
                                AccelerationRatio=".9" />
        </Storyboard>
        <!-- Grow -->
        <Storyboard x:Key="GrowIn">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
        </Storyboard>
        <Storyboard x:Key="GrowOut">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
        </Storyboard>
        <!-- Grow and Fade -->
        <Storyboard x:Key="GrowAndFadeIn">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.25"
                             Storyboard.TargetProperty="Opacity"
                             From="0"
                             To="1" />
        </Storyboard>
        <Storyboard x:Key="GrowAndFadeOut">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.75"
                             Storyboard.TargetProperty="Opacity"
                             To="0" />
        </Storyboard>
        <!-- Flip -->
        <Storyboard x:Key="FlipIn">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleX)"
                             From="-100"
                             To="0"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)"
                             From="-100"
                             To="0"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
        </Storyboard>
        <Storyboard x:Key="FlipOut">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleX)"
                             To="100"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)"
                             To="100"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
        </Storyboard>
        <!-- Flip and Fade -->
        <Storyboard x:Key="FlipAndFadeIn">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleX)"
                             From="-100"
                             To="0"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)"
                             From="-100"
                             To="0"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.25"
                             Storyboard.TargetProperty="Opacity"
                             From="0"
                             To="1" />
        </Storyboard>
        <Storyboard x:Key="FlipAndFadeOut">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleX)"
                             To="100"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)"
                             To="100"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.75"
                             Storyboard.TargetProperty="Opacity"
                             To="0" />
        </Storyboard>
        <!-- Spin -->
        <Storyboard x:Key="SpinIn">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)"
                             From="-360"
                             To="0"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
        </Storyboard>
        <Storyboard x:Key="SpinOut">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)"
                             To="360"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
        </Storyboard>
        <!-- Spin and Fade -->
        <Storyboard x:Key="SpinAndFadeIn">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)"
                             From="-360"
                             To="0"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             From="0"
                             To="1"
                             Duration="0:0:.75"
                             DecelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.25"
                             Storyboard.TargetProperty="Opacity"
                             From="0"
                             To="1" />
        </Storyboard>
        <Storyboard x:Key="SpinAndFadeOut">
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)"
                             To="360"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
                             To="0"
                             Duration="0:0:.75"
                             AccelerationRatio=".9" />
            <DoubleAnimation Duration="0:0:.75"
                             Storyboard.TargetProperty="Opacity"
                             To="0" />
        </Storyboard>
    </Window.Resources> 

Add Frame Control into your Page and Set Transforms in TransformGroups


<Frame x:Name="FrameWithinGrid"
               ContentRendered="FrameWithinGrid_ContentRendered"
               Source="Home.xaml">
            <Frame.RenderTransform>
               <TransformGroup>
                    <ScaleTransform ScaleX="1"
                                    ScaleY="1"
                                    CenterX="{Binding ElementName=FrameWithinGrid, Path=ActualWidth, Converter={StaticResource CenterConverter}}"
                                    CenterY="{Binding ElementName=FrameWithinGrid, Path=ActualHeight, Converter={StaticResource CenterConverter}}" />
                    <SkewTransform AngleX="0"
                                   AngleY="0"
                                   CenterX="{Binding ElementName=FrameWithinGrid, Path=ActualWidth, Converter={StaticResource CenterConverter}}"
                                   CenterY="{Binding ElementName=FrameWithinGrid, Path=ActualHeight, Converter={StaticResource CenterConverter}}" />
                    <RotateTransform Angle="0"
                                     CenterX="{Binding ElementName=FrameWithinGrid, Path=ActualWidth, Converter={StaticResource CenterConverter}}"
                                     CenterY="{Binding ElementName=FrameWithinGrid, Path=ActualHeight, Converter={StaticResource CenterConverter}}" />
                    <TranslateTransform X="0"
                                        Y="0" />
                </TransformGroup>
            </Frame.RenderTransform>
        </Frame> 

Use Your Resource as a Storyboard in FrameWithinGrid_ContentRendered Event


  private void FrameWithinGrid_ContentRendered(object sender, EventArgs e)
  {  
     Storyboard sb = this.Resources["GrowOut"] as Storyboard;
     sb.Completed += new EventHandler(sb_Completed);
     sb.Begin(FrameWithinGrid);
  }
  void sb_Completed(object sender, EventArgs e)
  {
     Storyboard sb = this.Resources["GrowIn"] as Storyboard;          
     sb.Begin(FrameWithinGrid);
  } 

WPF Frame Navigation Animation : TranslateTransform and RotateTransform

RotateTransform

MainWindow.xaml

<Frame Name="FrameWithinGrid"
               ContentRendered="FrameWithinGrid_ContentRendered"             
               Source="Home.xaml">
            <Frame.RenderTransform>
              <RotateTransform Angle="0"
                               CenterX="425"
                               CenterY="300" />
            </Frame.RenderTransform>
</Frame>

MainWindow.xaml.cs

 
 private void FrameWithinGrid_ContentRendered(object sender, EventArgs e)
 {
    Storyboard storyboard = new Storyboard();
    DoubleAnimation rotateAnimation = new DoubleAnimation();
    rotateAnimation.Duration = TimeSpan.FromMilliseconds(1000);
    rotateAnimation.From = 0;
    rotateAnimation.To = 180;        
    storyboard.Children.Add(rotateAnimation);
    Storyboard.SetTargetProperty(rotateAnimation,
          new PropertyPath("RenderTransform.Angle"));
    Storyboard.SetTarget(rotateAnimation, FrameWithinGrid);
    storyboard.Begin(); 
 }
 
 
TranslateTransform

MainWindow.xaml

<Frame Name="FrameWithinGrid"
               ContentRendered="FrameWithinGrid_ContentRendered"             
               Source="Home.xaml">
            <Frame.RenderTransform>
                <TranslateTransform X="0"
                                    Y="0" />
            </Frame.RenderTransform>
</Frame>

MainWindow.xaml.cs

 
 private void FrameWithinGrid_ContentRendered(object sender, EventArgs e)
 {
    Storyboard storyboard = new Storyboard();
    DoubleAnimation transAnimation = new DoubleAnimation();
    transAnimation.Duration = TimeSpan.FromMilliseconds(500);
    transAnimation.From = 0;
    transAnimation.To = 800;
    storyboard.Children.Add(transAnimation);
    Storyboard.SetTargetProperty(transAnimation, new PropertyPath("RenderTransform.X"));
    //Storyboard.SetTargetProperty(transAnimation, new PropertyPath("RenderTransform.Y"));
    Storyboard.SetTarget(transAnimation, FrameWithinGrid);
    storyboard.Completed += new EventHandler(storyboard_Completed);
    storyboard.Begin();
 }
 void storyboard_Completed(object sender, EventArgs e)
 {
    Storyboard storyboard = new Storyboard();
    DoubleAnimation growAnimation = new DoubleAnimation();
    growAnimation.Duration = TimeSpan.FromMilliseconds(500);
    growAnimation.From = -800;
    growAnimation.To = 0;
    storyboard.Children.Add(growAnimation);

    Storyboard.SetTargetProperty(growAnimation, new PropertyPath("RenderTransform.X"));
    //Storyboard.SetTargetProperty(growAnimation, new PropertyPath("RenderTransform.Y"));
    Storyboard.SetTarget(growAnimation, FrameWithinGrid);        
    storyboard.Begin();
 } 

Wednesday, July 4, 2012

WPF : Handling Event on View From ViewModel

1. First Create Event Handler in ViewModel 

LoginViewModel

   public event EventHandler LoginCompleted = delegate { };
   public void OnLoginCompleted()
   {
        LoginCompleted(this, new EventArgs());
   }

2. Handle ViewModel Event in View


LoginView.Xaml.cs

 
public LoginView()
{
   this.DataContext = new LoginViewModel(); 
   (this.DataContext as LoginViewModel).LoginCompleted += 
              new EventHandler(LoginViewModel_LoginCompleted); 
}
void LoginViewModel_LoginCompleted(object sender, EventArgs e)
{
   //your Coode goes here         
}

Friday, June 29, 2012

Logging using Log4Net in WPF

log4net is best logging framework available for .Net.

Let's start with step by step, how to log error in your application.

Step 1:first download latest log4net dll.

click Log4Net dll to download and add reference in your project.

Step 2: Create log4net.config application configuration file for configuration settings.

FileName : log4net.config

there are many ways to create log file and message/error format.

I have created 2 formats, one for create log file within folder, one for create log file directly within Debug folder.

Format 1 : Create folder named Log and create log file dynamically date wise and save in Debug folder.

<log4net debug="true">
    <appender name="RollingLogFileAppender" 
                type="log4net.Appender.RollingFileAppender">
      <file value="Logs\log" />
      <staticLogFileName value="false"/>
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=" yyyy-MM-dd&quot;.xml&quot;"/>
      <layout type="log4net.Layout.PatternLayout">        
        <!--<param name="ConversionPattern" 
               value="%d [%t] %-5p %c %m%n" />-->
        <conversionPattern 
           value="%date [%thread] %-5level %logger ==> %message%newline"/>
      </layout>
    </appender>

    <root>
      <level value="INFO" />
      <appender-ref ref="RollingLogFileAppender" />
      <appender-ref ref="AdoNetAppender" />
    </root>
  </log4net>

Format 2 : Create log file named hirenlog.txt and save in Debug folder.

<log4net debug="true">
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
    <param name="File" value="hirenlog.txt" />
    <param name="AppendToFile" value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="Header" value="[Header]\r\n" />
      <param name="Footer" value="[Footer]\r\n" />
      <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
    </layout>
  </appender>
  <root>
    <level value="INFO" />
    <appender-ref ref="LogFileAppender" />
  </root>
</log4net>
 
Step 3: Right click on log4net.config file and go to properties and set 
"Copy to Output Directory" property value to "Copy if newer" as highlighted in below image.


Step 4: Open AssemblyInfo.cs file from properties and add below line at end of file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]


Step 5 : Create Logger Class.

    public interface ILogger
    {
        void LogException(Exception exception);
        void LogError(string message);
        void LogWarningMessage(string message);
        void LogInfoMessage(string message);
    }
    public class Logger : ILogger
    {      
        private static ILog log = null; 
        static Logger()
        {
            //var log4NetConfigDirectory = 
            //AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
            //var log4NetConfigFilePath = Path.Combine(log4NetConfigDirectory, "log4net.config");
            //log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(log4NetConfigFilePath));
            log = LogManager.GetLogger(typeof(Logger));
            log4net.GlobalContext.Properties["host"] = Environment.MachineName;
        }
        public Logger(Type logClass)
        {
            log = LogManager.GetLogger(logClass);
        }

        #region ILogger Members
        public void LogException(Exception exception)
        {
            if (log.IsErrorEnabled)
                log.Error(string.Format(CultureInfo.InvariantCulture, "{0}", exception.Message), exception);
        }
        public void LogError(string message)
        {
            if (log.IsErrorEnabled)
                log.Error(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }
        public void LogWarningMessage(string message)
        {
            if (log.IsWarnEnabled)
                log.Warn(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }
        public void LogInfoMessage(string message)
        {
            if (log.IsInfoEnabled)
                log.Info(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }
        #endregion
    }

Above class configures log4net using xml file (log4net.config) and creates instance of ILog, now you will use this class for logging errors from ViewModels.

Step 6 : In you ViewModel Initialize ILogger class and logs errors.

  internal class MainWindowViewModel
  {
     ILogger logger = new Logger(typeof(MainWindowViewModel));
     public MainWindowViewModel()
     {
        logger.LogError("Error while downloading data"); 
     } 
  }

so, this is simple way to logs you error and exception details.

Thursday, June 28, 2012

Split Comma Seperated String using XML in Sql Server

DECLARE @strDeviceData varchar(MAX) = '1:1,1:0,2:0,2:1'
DECLARE @X xml
DECLARE @split char(1)
SET @split=','
SELECT @X=CONVERT(xml,'<root><h>' + REPLACE(@strDeviceData,@Split,'</h><h>') + '</h></root>')
SELECT [DeviceInfo] = T.c.value('.','varchar(20)')
FROM @X.nodes('/root/h') T(c)

When you run query, you will get following output.

 

Thursday, June 21, 2012

Dynamically Creating Pie/Bar Chart in C# WinForms

Chart control is available in Data Category of ToolBox in Windows Form Application.

If not available then

First Download Microsoft Chart Controls for Microsoft .NET Framework 3.5  and install it. 



After that, right click on ToolBox, select Choose Items and then select namespaces checked in above image.

now Chart control is added into your toolbox.


Add Reference System.Windows.Forms.DataVisualization
Create Chart

Step 1 : Add New Windows Form in your Application.


Add Two panels in your Form, one for Pie chart and one for Bar chart as in shown below image.




Step 2 : Go to Code Behind (C#) and initialize chart controls.

public partial class Form1 : Form
    {
        Chart pieChart;
        Chart barChart;
        public Form1()
        {
            InitializeComponent();
            InitializeChart();
        }
        private void InitializeChart()
        {

            this.components = new System.ComponentModel.Container();
            ChartArea chartArea1 = new ChartArea();
            Legend legend1 = new Legend() 
              { BackColor = Color.Green, ForeColor = Color.Black, Title = "Salary" };
            Legend legend2 = new Legend() 
              { BackColor = Color.Green, ForeColor = Color.Black, Title = "Salary" };
            pieChart = new Chart();
            barChart = new Chart();

            ((ISupportInitialize)(pieChart)).BeginInit();
            ((ISupportInitialize)(barChart)).BeginInit();

            SuspendLayout();

            //===Pie chart
            chartArea1.Name = "PieChartArea";
            pieChart.ChartAreas.Add(chartArea1);
            pieChart.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            pieChart.Legends.Add(legend1);
            pieChart.Location = new System.Drawing.Point(0, 50);

            //====Bar Chart
            chartArea1 = new ChartArea();
            chartArea1.Name = "BarChartArea";
            barChart.ChartAreas.Add(chartArea1);
            barChart.Dock = System.Windows.Forms.DockStyle.Fill;
            legend2.Name = "Legend3";
            barChart.Legends.Add(legend2);

            AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.ClientSize = new System.Drawing.Size(284, 262);           
            this.Load += new EventHandler(Form1_Load);
            ((ISupportInitialize)(this.pieChart)).EndInit();
            ((ISupportInitialize)(this.barChart)).EndInit();
            this.ResumeLayout(false);

        }

        void Form1_Load(object sender, EventArgs e)
        {
            LoadPieChart();
            LoadBarChart();
        }
} 

Step 3 : Create Methods to Create Pie and Bar charts and load into Panels.
 
        void LoadPieChart()
        {
            pieChart.Series.Clear();
            pieChart.Palette = ChartColorPalette.Fire;
            pieChart.BackColor = Color.LightYellow;
            pieChart.Titles.Add("Employee Salary");
            pieChart.ChartAreas[0].BackColor = Color.Transparent;
            Series series1 = new Series
            {
                Name = "series1",
                IsVisibleInLegend = true,
                Color = System.Drawing.Color.Green,
                ChartType = SeriesChartType.Pie
            };
            pieChart.Series.Add(series1);
            series1.Points.Add(70000);
            series1.Points.Add(30000);
            var p1 = series1.Points[0];
            p1.AxisLabel = "70000";
            p1.LegendText = "Hiren Khirsaria";
            var p2 = series1.Points[1];
            p2.AxisLabel = "30000";
            p2.LegendText = "ABC XYZ";
            pieChart.Invalidate();
            pnlPie.Controls.Add(pieChart);
        }
        void LoadBarChart()
        {
            barChart.Series.Clear();
            barChart.BackColor = Color.LightYellow;           
            barChart.Palette = ChartColorPalette.Fire;
            barChart.ChartAreas[0].BackColor = Color.Transparent;
            barChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            barChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            Series series = new Series
            {
                Name = "series2",
                IsVisibleInLegend = false,
                ChartType = SeriesChartType.Column
            };
            barChart.Series.Add(series);
            series.Points.Add(70000);
            var p1 = series.Points[0];
            p1.Color = Color.Red;
            p1.AxisLabel = "Hiren Khirsaria";
            p1.LegendText = "Hiren Khirsaria";
            p1.Label = "70000";
           
            series.Points.Add(30000);
            var p2 = series.Points[1];
            p2.Color = Color.Yellow;
            p2.AxisLabel = "ABC XYZ";
            p2.LegendText = "ABC XYZ";
            p2.Label = "30000";
            barChart.Invalidate();
            
            pnlBar.Controls.Add(barChart);
        }


Above methods create Pie chart and Bar chart, that display employee salary.

Below image shows final result ( showing Pie and Bar charts)


Monday, June 4, 2012

Modify XML Attribute value in SQL Server


     DECLARE @xmlData xml
    SET @xmlData=convert(xml,
    ' <Data>
      <Employee>
        <Item Section="1" primaryKeyId="11" name="HD1">
          <Details>
            <Column surname="Khirsaria" firstname="Hiren" salary="10000" />
          </Details>
        </Item>
        <Item Section="2" primaryKeyId="12" name="HD2">
          <Details>
            <Column surname="AAA" firstname="aaa"  salary="8000" />
          </Details>
        </Item>
        <Item Section="2" primaryKeyId="14" name="HD3">
          <Details>
            <Column surname="BBB" firstname="bbb"  salary="8000" />
          </Details>
        </Item>
      </Employee>
    </Data>
    ')

SELECT @xmlData

SET @xmlData.MODIFY('
  replace value of (/Data/Employee/Item[1]/Details/Column/@salary)[1]
  with     "20000" ')


set @xmlData.MODIFY(' replace value of (/Data/Employee/Item[2]/Details/Column/@surname)[1]   with     "Hello" ')

SELECT @xmlData

Saturday, June 2, 2012

Shapes and Drawing in WPF/Silverlight

In WPF/Silverlight Shape object is used to draw a shapes like (Line,Rectangle,Ellipse,Polygon etc.)

In this post we go through how to create and use ready to use shape and create custom shape using path property.

Shape object contains three common properties listed below.

1. Fill      :- This property is used to fill shape with color.
2. Stroke :- This property describes border color for the shape.
3. StokeThickness :- This property set shape border thickness.

Now, we will discuss various shapes into details.

Line

Line element is used to draw a line between two points. there are four attributes to draw a line (X1,Y1,X2,Y2) represents start point and end point for X and Y co-ordinates of line.


            <Line Stroke="Red" HorizontalAlignment="Center"
                  StrokeThickness="5"
                  X1="0"
                  Y1="0"
                  X2="200"
                  Y2="100" />


Ellipse

This shape create ellipse to circle in specified width and height.
 


            <Ellipse Height="80"
                     Width="200"
                     StrokeThickness="5"
                     Stroke="Red"
                     Fill="Black" />

Rectangle
This shape draw a rectangle.

 
       <Grid Grid.Row="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="5*" />
                <ColumnDefinition Width="5*" />
            </Grid.ColumnDefinitions>
            <Rectangle Width="120"
                       Grid.Column="0"
                       Height="80"                      
                       Stroke="Red"
                       StrokeThickness="5"
                       Fill="Black" />
            <Rectangle Width="120" Grid.Column="1"
                       Height="80"
                       RadiusX="25"
                       RadiusY="25"
                       Stroke="Red"
                       StrokeThickness="5"
                       Fill="Black" />
       </Grid>

As shown in above figure, first is simple rectangle and second figure indicates rounded rectangle. To draw rounded rectangle we have to set two more properties (RadiusX and RadiusY) for round corner.

Polyline

This shape is used draw a series of connected strait line.
  
            <Polyline Points="0,50 20,0 40,50 60,0 80,50 100,0 120,50 -4,50"
                      Stroke="Blue"
                      StrokeThickness="10"
                      Canvas.Left="75"
                      Canvas.Top="50" /> 

Polygon

This shape i used to draw a polygon, which is a connected series of lines that form a closed shape.
Following examples shows how to creates different types of shapes using polygon

Example 1 :


                <Polygon Points="0,50 0,100 100,100 100,10 70,50"
                         Fill="Magenta"
                         Stroke="Black"
                         StrokeThickness="3" />

Example 2 :

           <Grid Grid.Column="1">
                <Polygon Fill="LightBlue"
                         Points="26,4 0,8 0,115 4,120 4,12 30,8 26,4"
                         Stroke="Gray"
                         StrokeDashArray="0" />
                <Polygon Fill="LightCoral"
                         Points="30,8 4,12 4,120 115,110 115,82 30,90"
                         Stroke="Yellow" />
                <Polygon Fill="LightBlue"
                         Points="115,82 30,90 30,85 110,78" />
            </Grid>

As shown in above example 2, i have created three polygon one for shade upper part of L shape, one for create L shape and one for shade inner part of L shape.

Example 3 :


          <Grid Grid.Column="2"
                  Margin="10"
                  VerticalAlignment="Center">
                <Grid.Effect>
                    <DropShadowEffect Color="Black"
                                      Direction="5"
                                      ShadowDepth="2"
                                      BlurRadius="5"
                                      Opacity="0.7" />
                </Grid.Effect>
                <Polygon Stroke="Gray"
                         Points="45,0 0,8 0,61 4,65 4,12 49,4 45,0">
                    <Polygon.Fill>
                        <LinearGradientBrush StartPoint="0.7,0"
                                             EndPoint="0.7,0.5">
                            <GradientStop Color="#E2E4E6"
                                          Offset="1" />
                            <GradientStop Color="#AFAFAF" />
                        </LinearGradientBrush>
                    </Polygon.Fill>
                </Polygon>
                <Polygon x:Name="mypolygon"
                         Points="49,4 4,12 4,65 49,54 49,52 49,52"
                         Fill="LightBlue" />
                <Polygon Points="30,4 4,12 4,65 50,50 50,28 30,30">
                    <Polygon.Fill>
                        <RadialGradientBrush GradientOrigin="1,0.5"
                                             RadiusX="1"
                                             RadiusY="1"
                                             Opacity="0.7">
                            <GradientStop Color="Pink"
                                          Offset="0" />
                            <GradientStop Color="Pink"
                                          Offset="0.62" />
                            <GradientStop Color="Transparent"
                                          Offset="0.62" />
                        </RadialGradientBrush>
                    </Polygon.Fill>
                </Polygon>
                <Polygon Fill="#C8B2AB"
                         Points="50,28 30,35 30,30 45,24" />
            </Grid>

Custom shape using Path

Now we can move onto how to create custom shapes using Path and Data property of Path element.

Path class is used to draw Curves and complex shapes. it describes using Geometry object.There are a various types of Geometry objects describes shpaes are LineGeometry, RectangleGeometry, and EllipseGeometry.

Data attribute in path is used to create complex shapes. it has following commands.

Commands

    M :- Move command establishes a start point for the path.The capital M indicates an absolute         location for the new current point. A lowercase m would indicate relative coordinates.

    L :- Line command creates a straight line between the current point and the specified end point.

    H :- Horizontal Line command creates a horizontal line between the current point and the specified x-coordinate.
 
    V :- Vertical Line command creates a vertical line between the current point and the specified y-coordinate.

   C :- Curve command creates a cubic Bezier curve between the current point and the specified end point by using the two specified control points.
            Syntex  : C controlPoint1 controlPoint2 endPoint
  
  A :- Arc command creates an elliptical arc between the current point and the specified end point.
           Syntex : A size(x-radius, y-radius) rotationAngle isLargeArcFlag sweepDirectionFlag   endPoint
           Example : A 10,5 180 0 1 100,0

  Z :- Close command ends the current figure and creates a line that connects the current point to the starting point of the figure.


Example 1 :


                <Path Data="M0,0 150,0 150,150 50,150 70,200 30,150 0,150 0,0z"
                      Fill="DarkBlue" />

Example 2 :

     <Path Fill="BlanchedAlmond"
           Data="M 0,50 C 30,30 30,30 50,0 C 65,30 65,30 100,50 C 68,68 68,68 50,100 C 30,65 30,65 0,50 Z"
           Stroke="Black"
           StrokeThickness="5" />

In above example 2, I have created shape using curve command.
In C 30,30 30,30 50,0 command C indicates curve ; 30,30 indicates first curve point ; 30,30 indicates second curve point and 50,0 indicates endpoint.

Example 3 :


   <Grid Grid.Column="2">
      <Path Data="M88,25 C86,21 78,7 59,1 C59,1 55,0 48,0 C44,0 39,0 34,2                   
             C20,6 13,16 11,18 C11,18 5,26 4,32 C4,32 1,40 0,50 C0,58 0,65 1,73                        
             C1,80 3,86 5,92 C5,92 8,102 10,105 C11,108 18,119 22,124                                     
             C24,125 35,137 44,145 C51,150 62,160 90,172                  
             C118,160 129,150 136,145 C146,137 157,125 158,124 C163,119 169,108.8 170,105                  
             C172,102 175,92 175,92 C177,86 179,80 180,73 C181,65 181,58 180,50                  
             C179,40 176,32 176,32 C175,26 169,18 169,18 C167,16 160,6 146,2                  
             C141,0 136,0 132,0 C125,0 121,1 121,1 C102,7 93,21 92,25                  
             C91,27 91,27 90,27 C90,27 89,28 88,25z"
            Fill="Red"
            Opacity="0.6"
            Stroke="Black"
            StrokeThickness="3" />
   </Grid>
 
 
Example 4 :



   <Path Canvas.Left="15"
         Canvas.Top="50"
         Stroke="Black"
         Data="M0,0 A10,5 180 0 1 100,0 L100,0 L100,100 L50,100 L50,50 L0,50 Z"
         Fill="DarkBlue"
         Opacity="0.8" />

In above example 4, I have created shape using Line command and Arc command.
In  A10,5 180 0 1 100,0 command A indicates Arc; 10,5 indicates X and Y radius; 180 indicates rotation angle ; 0 indicates large arc flag; 1 indicates sweep direction flag and 100,0 indicates end point.


Clip Property


UIElement.Clip Property takes a Geometry type like (LineGeometry, RectangleGeometry, EllipseGeometry etc.) 
Clip Property is used to define the outline of the contents of a UIElement by get/set the Geometry. It display some area of region by setting outline of region.

Example 1 :
 
    <Image Source="/SilverlightApplication1;component/Images/Penguins.jpg"
           Width="300"
           Grid.Column="0"
           Height="300">
           <Image.Clip>
              <EllipseGeometry RadiusX="100"
                               Center="150,100"
                               RadiusY="100" />
           </Image.Clip>
    </Image>

In above example 1, I have used EllipseGeometry to crop image in a circle.

Example 2 :


   <Image Source="/SilverlightApplication1;component/Images/Penguins.jpg"
          Width="300"
          Grid.Column="1"
          Height="300">
          <Image.Clip>
              <RectangleGeometry Rect="60,50,150,100"
                                 RadiusX="20"
                                 RadiusY="20" />
          </Image.Clip>
   </Image>

So, this way you can create shapes using Geometry types or Custom shapes using Path.

In this article I have tried to explained everything about creating and drawing shapes, clipping objects and custom shapes using commands.

Tuesday, May 29, 2012

Find Child Control from ControlTemplate in Silverlight

In Silverlight application development sometimes you need to find ControlTemplates Child control from silverlight control.

Below is code that will return child control from TemplateChild of passed parent DependencyObject.

 public static FrameworkElement GetTemplateChildByName
       (DependencyObject parent, string name)
 {
    int childnum = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childnum; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is FrameworkElement && 
                ((FrameworkElement)child).Name == name)
        {
           return child as FrameworkElement;
        }
        else
        {
           var s = GetTemplateChildByName(child, name);
           if (s != null)
             return s;
        }
    }
    return null;
 }

Above method will return passed named child control from parent control.

Here is the code that call GetTemplateChildByName method.

 private void TabHeaderBackgroundBorder_MouseLeftButtonUp
                (object sender, MouseButtonEventArgs e)
 {
    FrameworkElement selectedItem = TabHeader as FrameworkElement;
    FrameworkElement TabPanel= 
           GetTemplateChildByName(selectedItem, "MyTabContentPanel");
    FrameworkElement parentBorder = 
           GetTemplateChildByName(TabPanel, "parentBorder");
            
 } 

In above code, I am finding ScalePanel from TabHeader Items and finding Border within ScalePanel.

so yon can find Hierarchy of control from parent control.

Thursday, May 24, 2012

Convert Hexa string to Color in Silverlight

Below method will convert Color from Hexa string.

 public static Color GetColorFromHexa(string hexaColor)
 {
    if (string.IsNullOrEmpty(hexaColor))
                return Colors.Transparent;
    if (hexaColor.Length == 9)
    {
       return Color.FromArgb(
        Convert.ToByte(hexaColor.Substring(1, 2), 16),
        Convert.ToByte(hexaColor.Substring(3, 2), 16),
        Convert.ToByte(hexaColor.Substring(5, 2), 16),
        Convert.ToByte(hexaColor.Substring(7, 2), 16));
    }
    else if (hexaColor.Length == 7)
    {
        return Color.FromArgb(
         Convert.ToByte("FF", 16),
         Convert.ToByte(hexaColor.Substring(1, 2), 16),
         Convert.ToByte(hexaColor.Substring(3, 2), 16),
         Convert.ToByte(hexaColor.Substring(5, 2), 16)
        );
    }
    else
    {
        return Colors.Transparent;
    }

 }

I have created method that convert hexa string to SolidColor.Color value.

If i am passing Hexa string to 7 cahracter then it will add  first two character for opacity.

so above method will return SolidColor.Color value from Hexa string

Monday, May 21, 2012

LINQ to SQL Query Examples

Please refere below MSDN link, you can find lots of examples with explanation.

LINQ to SQL Query Sample

Below link for only LINQ samples.

LINQ Examples 

Friday, May 18, 2012

Silverlight : Creating and Using Service Oriented Architecture in Silverlight

Service Oriented Architecture is a methodologies for  development and integration where functionality is grouped  and packaged as interoperable services.

In this post we go through creating custom response and request classes that use to get response from service and convert it to response type.

I have created sample that convert JSON result to DataContract ( passed generic types).
I have used Newtonsoft.Json dll to Deserialize JSON value.

Step 1 : Create Request Class.

 public class MyRequest
 {
    public List<KeyValuePair<string, string>> Parameter { get; set; }
 }

this class used as request for method that have list of  parameters.

Step 2 : Create Class for ResponseType.

 public enum MyResponseType
 {
        SUCCESS,
        ERROR       
 }

Step 3 : Create Class for Response
 
public class MyResponse<T>
{
    public String ResponseType { get; set; }
    public T Data { get; set; }
}

This class will return result of type passed (generic type),
ResponseType parameter will return Success or Error while getting response from service
Data parameter return data converted to passed Type.

Step 4 :Create Service Helper class and into that class Create Method that have Request and Response as a Parameter.
 
public class MyServiceHelper 
{
 
  public string URL { get; set; } 
  public MyServiceHelper(string uri)
  {
    URL=uri; 
  }
  public void CallJSON<T>(string methodName, List<KeyValuePair<string, string>> parameter,
         Action<MyResponse<T>> callbackMethod)
  {
      CallMethod<T>(methodName, parameter, callbackMethod);
  }
 
  public void CallMethod<T>(string methodName, List<KeyValuePair<string, string>> parameter,
          Action<MyResponse<T>> callbackMethod)
  {
      WebClient client = new WebClient();
      client.Headers["contentType"] = "application/json; charset=utf-8";      

      string fullUrl = 
          AppendQueryStringToUrl(URL + methodName, parameter);
      client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_WebRequestCompleted<T>);
      client.OpenReadAsync(new Uri(fullUrl), callbackMethod);
      break;

  }
  void client_WebRequestCompleted<T>(object sender, 
            System.ComponentModel.AsyncCompletedEventArgs e)
  {
     var result = new MyResponse<T>();
     if (e.Error != null)
     {
         result.ResponseType = MyResponseType.ERROR.ToString();             
     }
     else if (e is UploadStringCompletedEventArgs)
     {
         result = JsonConvert.DeserializeObject<MyResponse<T>>(((UploadStringCompletedEventArgs)e).Result);
     }
     else
     {
         StreamReader reader = new StreamReader(((OpenReadCompletedEventArgs)e).Result);
         string strResult = reader.ReadToEnd();
         result = JsonConvert.DeserializeObject<MyResponse<T>>(strResult);
     }
     Action<MyResponse<T>> responseResult= (Action<MyResponse<T>>)e.UserState;
     responseResult(result);
  }
  public string AppendQueryStringToUrl(string url, List<KeyValuePair<string, string>> parameters)
  {
    StringBuilder combinedParams = new StringBuilder();
    if (parameters != null)
    {
       parameters.ForEach((parameter) =>
       {
           combinedParams.AppendFormat("&{0}={1}", parameter.Key, 
                         HttpUtility.UrlEncode(parameter.Value));
       });
       if (combinedParams.Length > 0)
       {
           combinedParams.Replace("&", "?", 0, 1);
       }
    }
    return url + combinedParams.ToString();
  } 
} 

As shown in above code, first i have created CallJSON method that contains methodname, list of paramters and callback response that targeted to Action result.

In CallMethod<T> method, i have created object WebClient class.
WebClient is used to call service Url with querystring parameter and it has Header contenttype.
Header ContentType carry content type info that specify which type of result are you getting from service.

In client_WebRequestCompletedMethod<T> we are getting response of JSON string.

Now we have to Deserialize JSON value to Type of <T> generic class provided in response type.

Step 5 : Create Generic Class for result

   [DataContract]
    public class Employee
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
    }

Step 6 : Call ServiceHelper Method to Get Response

 private void GetSiteDownInfoList()
 {            
     List<Employee> empList=new List<Employee>();
     MyServiceHelper service = new MyServiceHelper("http://localhost/EmployeeService");
     List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();
     data.Add(new KeyValuePair<string, string>("userid", "1"));
 
     service.CallJSON<List<Employee>>("GetEmployees", data, (response) =>
     {
         if (response.ResponseType.ToString().Equals(MyResponseType.SUCCESS.ToString()))
         {
             response.Data.ForEach(t => empList.Add(t));
         }

     });
           
  }

So, this way you can create your own reusable class for your application.
 

Thursday, May 17, 2012

Windows Phone 7 : Unit Testing (Create Test Project)

To Create Test Project in windows phone 7, you require to install NuGet and Windows Phone Test Project Templates.

It is a Visual Studio extension that makes it easy to install third-party libraries and tools in Visual Studio.

WP7Essentials library is used to create WindowsPhoneEssentials.Testing project that contains Silverlight Unit Test Framework which has been updated for use with Mango, as well as a few testing helpers.

Let’s go through Step by steps.

Step 1 :Download and  Install NuGet.

    Click NuGet.org To Download NuGet.
  
Step 2 : Download and Install Windows Phone Test Project Template.


   Click WP7 Test Project Template To Download phone test project template.

 
Step 3 : Create Windows Phone Test Project.

After installing NuGet and WP7 test project template, Start with creating new test project.
Open Visual studio and click on New Project.

In New Project dialog left panel select Test from Installed Template.

There are two items listed Test Project and Windows Phone Test Project as in below screen.

Select Windows Phone Test Project and click OK button.


your Project solution Explorer look like below screen.


When you build you project it gives error related to assembly missing (Microsoft.Silverlight.Testing , Microsoft.VisualStudio.TestTools.UnitTesting)

For that we have to use NuGet to get the latest versions of either Silverlight Unit Test Framework for Windows Phone (No Mango Support yet!) or Windows Phone Essentials Testing.

Step 4 : Install WindowsPhoneEssentials.Testing Package.

Click on Tools Menu and select Manage NuGet packages from Library Package Manager as in below screen.


Manage NuGet Packages Dialog will opened.

In this dialog, Search windowsphoneessentials from Search Online Textbox.
 it gives a list of packages, select WindowsPhoneEssentials.Testing item from the list and click on Install button (See below image).


it will install packages in current project, now close the dialog.

Now expand references in project, few assemblies are added into project reference (see image below).


As shown in above image, highlighted assemblies are added into reference and also one package.config file added into project.


Now Build you project, it build succeeds.
Run the Application, you testcase run within 5 seconds and you will get result (see below image).




Conclusion

In this way you can create you own Test Project using NuGet and WindowsPhoneEssentials Package.