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         
}