Shalvin Interests

Thursday, September 15, 2011

Insertion Sort in C#





using System;

public class InsertionSort
{
   private int[] data; 
   private static Random generator = new Random();

   public InsertionSort( int size )
   {
      data = new int[ size ]; 

      for ( int i = 0; i < size; i++ )
         data[ i ] = generator.Next( 10, 100 );
   } 

   public void Sort()
   {
      int insert;

      for ( int next = 1; next < data.Length; next++ )
      {
           insert = data[ next ]; 

           int moveItem = next; 

         // search for place to put current element
         while ( moveItem > 0 && data[ moveItem - 1 ] > insert )
         {
            // shift element right one slot
            data[ moveItem ] = data[ moveItem - 1 ];
            moveItem--;
         } 

         data[ moveItem ] = insert; // place inserted element
         PrintPass( next, moveItem ); 
      } 
   } 

   public void PrintPass( int pass, int index )
   {
      Console.Write( "after pass {0}: ", pass );

      for ( int i = 0; i < index; i++ )
         Console.Write( data[ i ] + "  " );

      Console.Write( data[ index ] + "* " ); // indicate swap

      for ( int i = index + 1; i < data.Length; i++ )
         Console.Write( data[ i ] + "  " );
     
      Console.Write( "\n              " ); 

      // indicate amount of array that is sorted
      for( int i = 0; i <= pass; i++ )
         Console.Write( "--  " );
      Console.WriteLine( "\n" ); 
   } 

   public override string ToString()
   {
      string temporary = "";

      foreach ( int element in data )
         temporary += element + "  ";
     
      temporary += "\n"; // add newline character
      return temporary;
   } 
} 


using System;

public class InsertionSortTest
{
   public static void Main( string[] args )
   {
      InsertionSort sortArray = new InsertionSort( 10 );
      
      Console.WriteLine( "Unsorted array:" );
      Console.WriteLine( sortArray ); 
      sortArray.Sort(); 

      Console.WriteLine( "Sorted array:" );
      Console.WriteLine( sortArray );
      Console.ReadLine();
   } 
} 

Selection Sort in C#

using System;

public class SelectionSort
{
   private int[] data; 
   private static Random generator = new Random();

   public SelectionSort( int size )
   {
      data = new int[ size ]; 

       for ( int i = 0; i < size; i++ )
         data[ i ] = generator.Next( 10, 100 );
   } 

    public void Sort()
   {
      int smallest; 

      for ( int i = 0; i < data.Length - 1; i++ )
      {
         smallest = i; 

         // loop to find index of smallest element
         for ( int index = i + 1; index < data.Length; index++ )
            if ( data[ index ] < data[ smallest ] )
               smallest = index;

         Swap( i, smallest ); // swap smallest element into position
         PrintPass( i + 1, smallest ); // output pass of algorithm
      } 
   } 

    public void Swap( int first, int second )
   {
      int temporary = data[ first ]; 
      data[ first ] = data[ second ]; 
      data[ second ] = temporary; 
   } 
 
   public void PrintPass( int pass, int index )
   {
      Console.Write( "after pass {0}: ", pass );

      // output elements through the selected item
      for ( int i = 0; i < index; i++ )
         Console.Write( data[ i ] + "  " );

      Console.Write( data[ index ] + "* " ); // indicate swap

      // finish outputting array
      for ( int i = index + 1; i < data.Length; i++ )
         Console.Write( data[ i ] + "  " );
     
      Console.Write( "\n              " ); // for alignment

      // indicate amount of array that is sorted
      for( int j = 0; j < pass; j++ )
         Console.Write( "--  " );
      Console.WriteLine( "\n" ); // skip a line in output
   } 

   public override string ToString()
   {
      string temporary = "";

      foreach ( int element in data )
         temporary += element + "  ";

      temporary += "\n"; 
      return temporary;
   } 
} 



using System;

public class SelectionSortTest
{
   public static void Main( string[] args )
   {
      SelectionSort sortArray = new SelectionSort( 10 );
      
      Console.WriteLine( "Unsorted array:" );
      Console.WriteLine( sortArray ); 

      sortArray.Sort(); 

      Console.WriteLine( "Sorted array:" );
      Console.WriteLine( sortArray ); 
      Console.ReadLine();
   } 
} 

Binary Search in C#


using System;

public class BinaryArray
{
   private int[] data; 
   private static Random generator = new Random();

   public BinaryArray( int size )
   {
      data = new int[ size ];

       for ( int i = 0; i < size; i++ )
         data[ i ] = generator.Next( 10, 100 );

      Array.Sort( data );
   } 

   public int BinarySearch( int searchElement )
   {
      int low = 0; 
      int high = data.Length - 1; 
      int middle = ( low + high + 1 ) / 2;
      int location = -1; 

      do 
      {
         Console.Write( RemainingElements( low, high ) );

         for ( int i = 0; i < middle; i++ )
            Console.Write( "   " );

         Console.WriteLine( " * " ); 

         if ( searchElement == data[ middle ] )
            location = middle; 

         else if ( searchElement < data[ middle ] )
            high = middle - 1; 
         else 
            low = middle + 1; 

         middle = ( low + high + 1 ) / 2; 
      } while ( ( low <= high ) && ( location == -1 ) );

      return location; 
   }

   public string RemainingElements( int low, int high )
   {
      string temporary = "";

      for ( int i = 0; i < low; i++ )
         temporary += "   ";

      for ( int i = low; i <= high; i++ )
         temporary += data[ i ] + " ";

      temporary += "\n";
      return temporary;
   } 

   public override string ToString()
   {
      return RemainingElements( 0, data.Length - 1 );
   } 
} 


using System;

public class BinarySearchTest
{
   public static void Main( string[] args )
   {
      int searchInt; 
      int position;
   
      BinaryArray searchArray = new BinaryArray( 15 );
      Console.WriteLine( searchArray );

      Console.Write( "Please enter an integer value (-1 to quit): " );
      searchInt = Convert.ToInt32( Console.ReadLine() );
      Console.WriteLine();

      while ( searchInt != -1 )
      {
         position = searchArray.BinarySearch( searchInt );

         if ( position == -1 )
            Console.WriteLine( "The integer {0} was not found.\n",
               searchInt );
         else
            Console.WriteLine( 
               "The integer {0} was found in position {1}.\n",
               searchInt, position);

         Console.Write( "Please enter an integer value (-1 to quit): " );
         searchInt = Convert.ToInt32( Console.ReadLine() );
         Console.WriteLine();
      }
   } 
} 

Linear Search with C#


using System;

public class LinearArray
{
   private int[] data; 
   private static Random generator = new Random();

   public LinearArray( int size )
   {
      data = new int[ size ]; // create space for array

      for ( int i = 0; i < size; i++ )
         data[ i ] = generator.Next( 10, 100 );
   }

   public int LinearSearch( int searchKey )
   {
         for ( int index = 0; index < data.Length; index++ )
         if ( data[ index ] == searchKey )
            return index; // return index of integer

      return -1; // integer was not found      
   }

   public override string ToString()
   {
      string temporary = "";

      foreach ( int element in data )
         temporary += element + " ";

      temporary += "\n";
      return temporary;
   } 
} 





using System;

public class LinearSearchTest
{
   public static void Main( string[] args )
   {
      int searchInt; // search key
      int position; // location of search key in array

           LinearArray searchArray = new LinearArray( 10 );
      Console.WriteLine( searchArray ); // print array

            Console.Write( "Please enter an integer value (-1 to quit): " );
      searchInt = Convert.ToInt32( Console.ReadLine() );

      while ( searchInt != -1 )
      {
         position = searchArray.LinearSearch( searchInt );

         if ( position != -1 ) // integer was not found
            Console.WriteLine(
               "The integer {0} was found in position {1}.\n",
               searchInt, position );
         else // integer was found
            Console.WriteLine( "The integer {0} was not found.\n",
               searchInt );

            Console.Write( "Please enter an integer value (-1 to quit): " );
         searchInt = Convert.ToInt32( Console.ReadLine() );
      } // end while
   } 
} 


Tuesday, July 19, 2011

INotifyPropertyChanged Interface

A change-notification handler notifies a binding target that a change has been
made. This enables a target to automatically respond to changes. Dependency properties
already have this feature built in, but CLR properties don’t. If you want your CLR
properties to broadcast their changes, you must implement the INotifyProperty-
Changed interface.

INotifyPropertyChanged interface belongs to System.ComponentModel namespace.

using System.ComponentModel;

namespace INotifyProperyChangeShalvin
{
    public class Speaker : INotifyPropertyChanged
    {
        private string mSpeakerName;
            public string SpeakerName
            {
                get { return mSpeakerName; }
                set
                {
                    mSpeakerName = value;
                    FirePropertyChanged("SpeakerName");
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;


            void FirePropertyChanged(string property)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,
                        new PropertyChangedEventArgs(property));
                }
            }
        }
    }




private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    Speaker s = new Speaker { SpeakerName = "Shalvin" };
    LayoutRoot.DataContext = s;
}


<Grid x:Name="LayoutRoot" Background="White">
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,47,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding SpeakerName, Mode=TwoWay}" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,147,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding SpeakerName, Mode=TwoWay}" />
</Grid>

Monday, July 18, 2011

Silverlight Layout Container

Silverlight Layout Containers are panels that derive from the abstract System.Windows.Controls.Panel class. The Properties of Panel class as Background and Children.

The Layout Panels are StackPanel, WrapPanel, DockPanel, Grid and Canvas.

Wednesday, July 13, 2011

Silverlight Styles

Styles is a collection of property value you can apply to an element. In a way it is equivalent to the functionality of CSS in HTML. You store style object as a resource.

<UserControl.Resources>
    <Style x:Key="SimpleStyle" TargetType="Button">
        <Setter Property="Foreground" Value="Blue" />
        <Setter Property="Background" Value="Cyan"/>
    </Style>
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">
    <Button Style="{StaticResource SimpleStyle}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="50,76,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="50,137,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>

Monday, July 11, 2011

Attached Property

Attached property is a special kind of Dependency Property. Attached propety applies to a class other than one where it is defined.

The best example of Attached property is the Row and Column Properties of Grid class. You set these properties inside the elements in a Grid.

Silverlight Dependency Property

Dependency Property include a mechanism that at any point of time determines what the value of propery should be based on several incluences working on the property such as databinding, styling and so on. These multiple services are called property providers They can be considered as the enabler for animation, databinding, styling and so on.

These different properties are prioritized. Animation is having the highest priority. This prioritization process is called dynamic value resoultion.

The list is as follows :
1. Animation
2. Local value. If you set a value using Resources or data binding it is considered as locally set
3. Styles
4. Property Value Inheritance
5.Default Value

Silverlight FullScreen

private  void btnFullScreen_Click(object sender, RoutedEventArgs e)
{
Application.Current.Host.Content.IsFullScreen = true;
}

Friday, July 8, 2011

UIElement class in Silverlight

UIElement is an object that represents a visual component. These types of elements
A have built-in support for layout, event handling, and rendering.

Silverlight/WPF Object Tree and Visual Tree

The hierarchical tree of objects in XAML file starting from the root going all the way down to elements make up the Object Tree. Object tree contains all types regardless of whether they participate in rending.

Visual Tree is a filtered view of Object Tree containing only those elements with a visual representation.

Thursday, July 7, 2011

User Group Meeting - 9th July 2011 - Kochi

09:30 - 09:40 Community updates
09:40 - 10:40 C# Test Automation by Praseed

10:40 - 11:20 Silverlight - Prism by Mahima
11:20 - 11:40 Tea Break (15 min)
11:40 - 12:30 Sharepoint 2010 programing by Abraham
12.30 - 01:00 Ask the experts


Register

Tuesday, May 10, 2011

Silverlight WCF Login

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
AirLinesEntities context = new AirLinesEntities();
[OperationContract]
public int Login(string sUserName, string sPassword)
{
    var c = (from p in context.Admins
            where p.AdminName == sUserName & p.Password == sPassword
            select p).Count();
    return c;
}

}


Login Silverlight User Control
ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
sc.LoginCompleted += new EventHandler<ServiceReference1.LoginCompletedEventArgs>(sc_LoginCompleted);
sc.LoginAsync(txtUserName.Text, txtPassword.Text);
}

void sc_LoginCompleted(object sender, ServiceReference1.LoginCompletedEventArgs e)
{
var c = e.Result;
if (c > 0)
{
    this.DialogResult = true;
    GlobalClass.IsLogin = true;
}
else
    MessageBox.Show("Invalid login");
}
}

MainPage
private void Link1_Click(object sender, RoutedEventArgs e)
{
Login l = new Login();
l.Closed += new System.EventHandler(l_Closed);
l.Show();
}

void l_Closed(object sender, System.EventArgs e)
{
Login loginWindow = (Login)sender;
bool? result = loginWindow.DialogResult;
if (result == true)
{
    hlbLocation.Visibility = System.Windows.Visibility.Visible;
}
}

Thursday, May 5, 2011

Asp .Net Cookies

//Default.aspx
protected void btnSubmit_Click(object sender, EventArgs e)
{
    HttpCookie cName = new HttpCookie("Name");
    cName.Value = "Shalvin";
    Response.Cookies.Add(cName );
    Response.Redirect("Welcome.aspx");
}

//Welcome.aspx
protected void Page_Load(object sender, EventArgs e)
{
    HttpCookie cName = Request.Cookies["Name"];
    Response.Write("Hello " + cName.Value );
}

Tuesday, May 3, 2011

WPF, Silverlight Transforms

<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Button" Height="34" HorizontalAlignment="Left" Margin="56,36,0,0" Name="button1" VerticalAlignment="Top" Width="100">
    <Button.RenderTransform>
        <SkewTransform AngleX="25"/>
    </Button.RenderTransform>
</Button>
    
<Button Content="Shalvin" Height="41" HorizontalAlignment="Left" Margin="235,30,0,0" Name="button2" VerticalAlignment="Top" Width="108">
    <Button.RenderTransform>
        <RotateTransform Angle="45"/>
    </Button.RenderTransform>
</Button>
</Grid>

WPF, Silvelight Image Clipping

<Image Height="246" HorizontalAlignment="Left" Margin="81,64,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="245" Source="/SilverlightImageClippingShalvin;component/ShalvinSmall.jpg">
    <Image.Clip>
        <EllipseGeometry RadiusX="100" RadiusY="100" Center="70, 70"/>
    </Image.Clip>
</Image>

Silverlight, WPF Brushes

SolidColorBrush LinearGradientBrush and RadialGradientBrush
<Rectangle Height="94" HorizontalAlignment="Left" Margin="57,42,0,0" Name="rectangle1" Stroke="Black" StrokeThickness="1" VerticalAlignment="Top" Width="201">
<Rectangle.Fill>
    <SolidColorBrush Color="Blue"/>
  
</Rectangle.Fill>

</Rectangle>
<Rectangle Height="92" HorizontalAlignment="Left" Margin="309,41,0,0" Name="rectangle2" Stroke="Black" StrokeThickness="1" VerticalAlignment="Top" Width="210">
<Rectangle.Fill>
    <LinearGradientBrush>
        <GradientStop Color="Blue" Offset="0"/>
        <GradientStop Color="Red" Offset="1"/>
    </LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>

<Rectangle Height="80" HorizontalAlignment="Left" Margin="58,172,0,0" Name="rectangle3" Stroke="Black" StrokeThickness="1" VerticalAlignment="Top" Width="201">
<Rectangle.Fill>
    <RadialGradientBrush>
        <GradientStop Color="Blue" Offset="0"/>
        <GradientStop Color="Red" Offset="1"/>
    </RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>

WPF DataGrid and DataTable, DataColumn and DataRow

using System.Data;
DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            dc = new DataColumn("Name");
            dt.Columns.Add(dc);

            dc = new DataColumn("Blog");
            dt.Columns.Add(dc);

            dr = dt.NewRow();
            dr["Name"] = "Shalvin";
            dr["Blog"] = "ShalvinPD.blogspot.com";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Name"] = "Sunil";
            dr["Blog"] = "Sunil.blogspot.com";
            dt.Rows.Add(dr);

            LayoutRoot.DataContext = dt;
      
        }

<Grid Name="LayoutRoot">
  <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" Height="200" HorizontalAlignment="Left" Margin="73,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" />
</Grid>

Monday, May 2, 2011

WPF Configuring Application Settings

You can access the Project Properties Dialog by selecting ProjectName Properties from Properties menu.
Navige to Setting tab.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
   MessageBox.Show(Properties.Settings.Default.Name);
}

Thursday, April 21, 2011

WPF Animation

Animation in code

using System.Windows.Media.Animation;
private void button1_Click(object sender, RoutedEventArgs e)
{
    DoubleAnimation widthAnimation = new DoubleAnimation();
    widthAnimation.To = cmdGrow.Width * 2;
    widthAnimation.Duration = TimeSpan.FromSeconds(5);

    DoubleAnimation heightAnimation = new DoubleAnimation();
    heightAnimation.To = cmdGrow.Height * 2;
    heightAnimation.Duration = TimeSpan.FromSeconds(5);

    cmdGrow.BeginAnimation(Button.WidthProperty, widthAnimation);
    cmdGrow.BeginAnimation(Button.HeightProperty, heightAnimation);
}

Animation with Styles
<Window x:Class="XamlAnimationShalvin.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
 <Window.Resources>

  <Style x:Key="GrowButtonWindowStyle">
   <Style.Triggers>
    <Trigger Property="Button.IsPressed" Value="True">
     <Trigger.EnterActions>
      <BeginStoryboard>
       <Storyboard>
        <DoubleAnimation Storyboard.TargetProperty="Width"
          To="250" Duration="0:0:5"></DoubleAnimation>
       </Storyboard>
      </BeginStoryboard>
     </Trigger.EnterActions>
    </Trigger>
   </Style.Triggers>
  </Style>

 </Window.Resources>
   <Button Padding="10" Name="cmdGrow" Height="40" Width="160" Style="{StaticResource GrowButtonWindowStyle}"
          HorizontalAlignment="Center" VerticalAlignment="Center">
        Click and Make Me Grow
  </Button>
</Window>

Wednesday, March 23, 2011

Bing Map Silverlight Control Dynamically Adding Pushpins

Silverlight Bing Map controls enables you to have Map functionality in your Silverlight application. Once you install Bing Maps Silverlight Control you will get a directory name Bing Maps Silverlight Controls under Program Files. Inside V1, Libraries you can find the associated dlls.

Add a reference to both the controls.
Add a namespace to Page section pointing to the dll.

  xmlns:Map="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"

 Now you can use the control

 <Map:Map Name="map1">
    <Map:Pushpin Location="9,76" Content="Kochi"/>
 </Map:Map>

Creating dynamic Pushpins
using Microsoft.Maps.MapControl;

Shalvin.Service1Client sc = new Shalvin.Service1Client();
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
           
            sc.getlocationCompleted += new EventHandler<Shalvin.getlocationCompletedEventArgs>(sc_getlocationCompleted);
            sc.getlocationAsync();
        }

        void sc_getlocationCompleted(object sender, Shalvin.getlocationCompletedEventArgs e)
        {
            var locs = e.Result.ToList();
            Pushpin p;
            Location l;
            foreach (var g in locs)
            {
                p = new Pushpin();
                double la = double.Parse(g.Latitude.ToString());
                double lo = double.Parse(g.Longitude.ToString());
                l = new Location { Latitude = la, Longitude = lo };
                p.Content = g.LocationName;
                p.Location = l;
                map1.Children.Add(p);
            }
        }
    }

Thursday, January 27, 2011

Asp .Net Interview Question

1. What are System.Web.Mail and System.Net.Mail?

System.Web.Mail has been deprecated, use System.Net.Mail instead.

System.Net.Mail namespace is used to send electronil mail to Simple Mail Transfer Protocol (SMTP) server for delivery.

2. What is generics?
Generic is a language feature introduced in .Net 2.0. Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Use of generics makes your code type safe. It is a very efficient way to work with collections.

C# does not allow non-type template parameters.

C# does not support explicit specialization; that is, a custom implementation of a template for a specific type.

C# does not allow the type parameter to be used as the base class for the generic type.

In C#, a generic type parameter cannot itself be a generic, although constructed types can be used as generics. C++ does allow template parameters.

Generics and Collection Initializer in .Net

3. What is boxing and unboxing?

Boxing is the process of converting a value type to the type object. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.
Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.
.NET Interview Questions You'll Most Likely Be Askedint i = 12;

object o = i; 
 

 Unboxing

o = 12;
i = (int)o; 


4. What is the difference between DataRowCollection.Remove method and DataRowCollection.Delete method?

DataRowCollection.Remove method removes a DataRow from a DataTable where as DataRowCollection.Delete method marks a row for deletion.


Calling Remove is the same as calling Delete and then calling AcceptChanges.
You can also use the Clear method to remove all members of the collection at one time.

 5. What are Extension Methods?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.



6. What is the use of System.Threading.ReaderWriterLockSlim Class?

Use ReaderWriterLockSlim to protect a resource that is read by multiple threads and written to by one thread at a time. ReaderWriterLockSlim allows multiple threads to be in read mode, allows one thread to be in write mode with exclusive ownership of the lock, and allows one thread that has read access to be in upgradeable read mode, from which the thread can upgrade to write mode without having to relinquish its read access to the resource.

Wednesday, January 19, 2011

Compression in .Net

using System.IO;
using System.IO.Compression;

static void Main(string[] args)
{
CompressFile(@"d:\ShalvinSmall.jpg", @"d:\S.jpg.zip");
DecompressFile(@"d:\s.jpg.zip", @"d:\Aju.jpg");
System.Console.ReadLine();
}

static void CompressFile(string inFilename,
                     string outFilename)
{

FileStream sourceFile = File.OpenRead(inFilename);
FileStream destFile = File.Create(outFilename);

// Create the Compressed stream
GZipStream compStream =
new GZipStream(destFile, CompressionMode.Compress);

// Write the data
int theByte = sourceFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = sourceFile.ReadByte();
}

// Clean it up
sourceFile.Close();
compStream.Close();
destFile.Close();
}

static void DecompressFile(string inFilename, string outFilename)
{
FileStream sourceFile = File.OpenRead(inFilename);
FileStream destFile = File.Create(outFilename);

// Create the Compressed stream
GZipStream compStream =
new GZipStream(sourceFile, CompressionMode.Decompress);

// Write the data
int theByte = compStream.ReadByte();
while (theByte != -1)
{
destFile.WriteByte((byte)theByte);
theByte = compStream.ReadByte();
}

// Clean it up
sourceFile.Close();
compStream.Close();
destFile.Close();
}

Friday, January 14, 2011

jQuery with Visual Studio 2010

Applying CSS based on click event
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="5JQueryCSS.aspx.cs" Inherits="_5JQueryCSS" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

</head> 
    <title></title>
    <script src="Scripts/jquery-1.12.1.js"></script>
    <script>
        $("document").ready(function()
        {
            $("#btnHighlight").click(function ()
            {
                $("p").css("border", "3px solid red");
                return false;
            });
         
        });
        </script>
    <form id="form1" runat="server">
    <div>
    
        <p>Shalvin</p>
        <p>Biju</p>
        <p>Reny</p>

        <h3>JavaScript Technologies</h3>
        <ul>
            <li>JQuery</li>
            <li>AngularJS</li>
            <li>CommonJS</li>
            <li>NodeJS</li>
        </ul>
    </div>
        <asp:Button ID="btnHighlight"  runat="server" Text="Highlight" />
    </form>
</body>
</html>

Tuesday, January 11, 2011

Symmetric Encryption in .Net

using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;


       Rfc2898DeriveBytes passwordKey;
        RijndaelManaged alg;
        FileStream inFile;
        ICryptoTransform encryptor;
        FileStream outFile;
        CryptoStream encryptStream;

        string inFileName;
        string outFileName;
        string password;
        byte[] saltValueBytes;
private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            saltValueBytes = Encoding.ASCII.GetBytes("ShalvinPD");
        }
        private void btnEncrypt_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EncPrepare();

                // Read the unencrypted file into fileData
                inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
                byte[] fileData = new byte[inFile.Length];
                inFile.Read(fileData, 0, (int)inFile.Length);


                encryptor = alg.CreateEncryptor();
                outFile = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
                encryptStream = new CryptoStream(outFile, encryptor, CryptoStreamMode.Write);

                // Write the contents to the CryptoStream
                encryptStream.Write(fileData, 0, fileData.Length);

                // Close the file handles
                encryptStream.Close();
                inFile.Close();
                outFile.Close();
                MessageBox.Show("File encrypted successfully");
                Process.Start("notepad", txtDestination.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

      

        private void btnDecrypt_Click(object sender, RoutedEventArgs e)
        {
            EncPrepare();
 
            // Read the encrypted file into fileData
            ICryptoTransform decryptor = alg.CreateDecryptor();
            inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
            CryptoStream decryptStream = new CryptoStream(inFile, decryptor, CryptoStreamMode.Read);
            byte[] fileData = new byte[inFile.Length];
            decryptStream.Read(fileData, 0, (int)inFile.Length);

            // Write the contents of the unencrypted file
            outFile = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
            outFile.Write(fileData, 0, fileData.Length);

            // Close the file handles
            decryptStream.Close();
            inFile.Close();
            outFile.Close();
            MessageBox.Show("File encrypted successfully");
        }

        private void EncPrepare()
        {
            inFileName = txtSource.Text;
            outFileName = txtDestination.Text;
            password = txtKey.Text;
            passwordKey = new Rfc2898DeriveBytes(password, saltValueBytes);


            alg = new RijndaelManaged();
            alg.Key = passwordKey.GetBytes(alg.KeySize / 8);
            alg.IV = passwordKey.GetBytes(alg.BlockSize / 8);

          
        }
    }

WPF Xaml


<Window x:Class="WpfEncryptionShalvin.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Shalvin Encryption" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Source File Name" Height="28" HorizontalAlignment="Left" Margin="62,42,0,0" Name="label1" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="221,42,0,0" Name="txtSource" VerticalAlignment="Top" Width="120" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="221,135,0,0" Name="txtDestination" VerticalAlignment="Top" Width="120" />
        <Label Content="Destination File Name" Height="28" HorizontalAlignment="Left" Margin="62,130,0,0" Name="label2" VerticalAlignment="Top" />
        <Label Content="Key" Height="28" HorizontalAlignment="Left" Margin="62,88,0,0" Name="label3" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="221,88,0,0" Name="txtKey" VerticalAlignment="Top" Width="120" />
        <Button Content="Encrypt" Height="23" HorizontalAlignment="Left" Margin="62,202,0,0" Name="btnEncrypt" VerticalAlignment="Top" Width="75" Click="btnEncrypt_Click" />
        <Button Content="Decrypt" Height="23" HorizontalAlignment="Left" Margin="221,202,0,0" Name="btnDecrypt" VerticalAlignment="Top" Width="75" Click="btnDecrypt_Click" />
    </Grid>
</Window>


Hashing

using System.Security.Cryptography;

private void btnHash_Click(object sender, EventArgs e)
{
    HashAlgorithm hashA = new SHA1CryptoServiceProvider();
byte[] pwordData = Encoding.Default.GetBytes(txtPlainText.Text);
byte[] hash = hashA.ComputeHash(pwordData);
txtHashCode.Text = BitConverter.ToString(hash);
}