Monday, January 2, 2012

Microsoft MVP Hat-trick

I am proud to announce that I am awarded Microsoft MVP for the third consecutive year in VB.NET Category. I would like to thank Mr. Abhishek Kant and Microsoft MVP Community, without their support this journey would be quite difficult to achieve. I got this award because of my contribution on MSDN Forum so I would like to thank all the Moderators and MSFT associated with the forum. Also congratulation to all the new and renewed MVP awarded in this quarter.

Email from Microsoft

Dear Gaurav Khanna,

Congratulations! We are pleased to present you with the 2012 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual Basic technical communities during the past year.

The Microsoft MVP Award provides us the unique opportunity to celebrate and honor your significant contributions and say "Thank you for your technical leadership."

Nestor Portillo
Director
Community & Online Support

What is MVP Award?

The Microsoft Most Valuable Professional (MVP) is the award given by Microsoft to those it considers "the best from technology communities around the world who actively share their technical expertise with the community and with Microsoft. An MVP is awarded for contributions over the previous year. Each year, around 4,000 MVPs are honoured.

More information about the Microsoft MVP Program are available on following links

Friday, December 9, 2011

ApplicationContext to run background task

Many of times we need to create an application which need to run in background and doesn’t require a form or a GUI. We have an option of creating a Windows Service but sometime it’s difficult to use it for a normal user. So in this situation we have an option of creating an application by inheriting a ApplicationContext class which is available in Windows Form.

To create a project to run a background task we can perform following steps

  1. Create a new Windows Form project
  2. Delete the available Forms and Application class.
  3. Create a new class which will inherit ApplicationContext where we can perform background task.
  4. Create a new module which will contain main method to run the application.

Below is a simple example where we are inheriting ApplicationContext class. In the constructor of class we are starting a new thread where we can perform some long running task and when the task get completed we can call ExitThread which will close the application.

Public Class CustomApplicationContext
Inherits ApplicationContext

Public Sub New()
MyBase.New()

Try
Dim
th As New Thread(AddressOf StartBackgroundTask)
th.Start()
Catch ex As IOException
ExitThread()
End Try
End Sub

Private Sub
StartBackgroundTask()
Try
'Some background Task
For i As Integer = 0 To 5
Threading.Thread.Sleep(1000)
Next
Finally

'Task completed. Close the application
ExitThread()
End Try
End Sub
End Class

We also have to create a new Module which will contain Main method to start the application using Application.Run and having CustomApplicationContext class as it’s parameter.

Module MainModule
Public Sub Main()
Dim context As New CustomApplicationContext
Application
.Run(context)
End Sub
End Module

Download Code: CustomApplicationContext.rar

Tuesday, November 29, 2011

Multiple Columns in WPF ListBox

In this article we will discuss ways to have multiple columns in WPF ListBox control and layout the ListBox such that each row has 3 items. All WPF controls deriving from ItemsControl provide an ItemsPanel property that allows us to replace the internal layout panel that arranges the items. So to have multiple columns in a ListBox we have to change the ItemsPanel property of the control.

WrapPanel

One of the most simple way of displaying content horizontally in ListBox is to have WrapPanel in ItemsPanel property of Listbox. But if we need to display fixed number of items in a row then we have to disable the horizontal scrollBar so that item get wrap to next row and set fixed width for ListBox. But as item get wrap the ListBoxItem are not positioned uniformly. So we have to set Width for each ListBoxItem so that all the items are positioned in a tabular way.

        <ListBox Width="300" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<
ListBox.ItemsPanel>
<
ItemsPanelTemplate>
<
WrapPanel Orientation="Horizontal"/>
</
ItemsPanelTemplate>
</
ListBox.ItemsPanel>

<
ListBoxItem Content="Visual Basic" Width="80"/>
<
ListBoxItem Content="Silverlight" Width="80"/>
<
ListBoxItem Content="ASP.NET" Width="80"/>
<
ListBoxItem Content="WCF" Width="80"/>
<
ListBoxItem Content="Web Services" Width="80"/>
<
ListBoxItem Content="Windows Service" Width="80"/>
</
ListBox>

UniformGrid


One of the drawback with WrapPanel was we had to disable horizontal scrollbar, set Width for ListBox and also width for ListBoxItem. So we can use UniformGrid instead of WrapPanel in ItemsPanel property and set Columns property of it to the number of items we need to display in a row. Using UniformGrid all the items in the ListBox will have same width and height.


        <ListBox>
<
ListBox.ItemsPanel>
<
ItemsPanelTemplate>
<
UniformGrid Columns="3"/>
</
ItemsPanelTemplate>
</
ListBox.ItemsPanel>

<
ListBoxItem Content="Visual Basic" />
<
ListBoxItem Content="Silverlight" />
<
ListBoxItem Content="ASP.NET" />
<
ListBoxItem Content="WCF" />
<
ListBoxItem Content="Web Services" />
<
ListBoxItem Content="Windows Service" />
</
ListBox>
Grid

Although UniformGrid is the best solution for multiple column ListBox but sometime we don’t want all the columns in the ListBox of same size. Also in some scenario we could have a requirement where we need to merge two or more columns (or rows) for a larger text. In this situation using Grid is very useful option.


        <ListBox>
<
ListBox.ItemsPanel>
<
ItemsPanelTemplate>
<
Grid>
<
Grid.RowDefinitions>
<
RowDefinition Height="*"/>
<
RowDefinition Height="*"/>
<
RowDefinition Height="*"/>
</
Grid.RowDefinitions>
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="0.8*"/>
<
ColumnDefinition Width="*"/>
<
ColumnDefinition Width="Auto"/>
</
Grid.ColumnDefinitions>
</
Grid>
</
ItemsPanelTemplate>
</
ListBox.ItemsPanel>

<
ListBoxItem Content="WCF" Grid.Row="0" Grid.Column="0"/>
<
ListBoxItem Content="ASP.NET" Grid.Row="0" Grid.Column="1"/>
<
ListBoxItem Content="VB.NET" Grid.Row="0" Grid.Column="2"/>
<
ListBoxItem Content="Silverlight" Grid.Row="1" Grid.Column="0"/>
<
ListBoxItem Content="Web Services" Grid.Row="1" Grid.Column="1"/>
<
ListBoxItem Content="Windows Service" Grid.Row="1" Grid.Column="2"/>
<
ListBoxItem Content="Windows Presentation Foundation" Grid.Row="2" Grid.ColumnSpan="3"/>
</
ListBox>

Only headache of using Grid in ItemsPanel is that we have to set RowDefinitions and ColumnDefinitions for the Grid. Also we have to set the Grid.Row and Grid.Column for each item to position them in the ListBox. But in some scenario as described above it is very useful.

Sunday, November 6, 2011

I unlock Joy

At the recent Mobile Developer Summit which took place on November 2, 2011 at Bangalore Microsoft announced the details of the developer programme for Windows Mobile in India with ‘I unlock Joy’, a unique Application Development and Submission Program, where technology professionals and students get an opportunity to develop applications and showcase creativity.

‘I unlock Joy’ programme for developers has started from November 1, 2011 and will continue till June 30, 2012 whereas the program for students will begin on December 18, 2011 and conclude on March 30 next year.

Developer competitive categories:

· “SUBMIT & WIN” CATEGORY: A registered participant submits THREE qualified Windows Phone Application in the Marketplace and gets a chance to win a Windows Phone. In this category, the Applications must be distinct and of non-trivial utility value for the Application User.

· “PORT 2 APPS & WIN” CATEGORY: A registered participant submitting TWO qualified Windows Phone Applications in the Marketplace which are ported from existing Android or iPhone Applications get to win a Windows Phone.

· “WOMEN SPECIAL” CATEGORY: A first of its kind in the developer space. The first 100 registered Woman Developers who submit ONE (1) qualified Windows Phone Application each in the Marketplace qualify to win a Windows Phone each. The applications can be based on Entertainment, Fashion, Leisure, Sports, Recreation or Travel themes.

Student competitive categories:

· “STUDENT” CATEGORY: Calling on the community to be a part of the initiative, the “I unlock Joy” programme is customized to unfold their innovative and creative best and become among the select first few proud owners of the Windows Phone.

The contestants need to build one or more applications using Dev Tools and submit on AppHub. If their apps get certified and published on the Windows Phone Marketplace during the contest period which ends November 18, they can claim goodies like a brand new Windows Phone, certificate of acknowledgment from Microsoft and Windows Phone T-Shirts as well as USB flash drives.

You can find more information from official Website

http://www.microsoft.com/india/iunlockjoy/

Sunday, October 2, 2011

WPF Collapsible Panel

In this article I have describe way to create a collapsible panel in WPF. This is one of the most common questions asked by many developers. Collapsible Panel can be used by user to collapse the content which he doesn't want to use and see only core information and hence keep the screen clean.
WPFCollapsiblePanel
This sample inherits the Expander control which is available in WPF. It support panel collapse in all the four directions (left, right, top and bottom).
public class CollapsiblePanel : Expander
{
static CollapsiblePanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CollapsiblePanel), new FrameworkPropertyMetadata(typeof(CollapsiblePanel)));
}
}

Here is the XAML for CollapsiblePanel

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" 
xmlns:local="clr-namespace:CollapsiblePanelDemo">

<local:MultiplyConverter x:Key="multiplyConverter" />

<Style x:Key="ExpanderHeaderFocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border>
<Rectangle SnapsToDevicePixels="true" Margin="0" Stroke="Black" StrokeDashArray="1 2" StrokeThickness="1" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style x:Key="ExpanderUpHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<Grid.LayoutTransform>
<RotateTransform Angle="90"/>
</Grid.LayoutTransform>


<Path x:Name="trapazoid" Fill="{Binding Path=Background, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}"  HorizontalAlignment="Center"   VerticalAlignment="Center">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="0,0" >
<PathFigure.Segments>

<ArcSegment Size="25,25" RotationAngle="45" IsLargeArc="False" SweepDirection="Clockwise" Point="0,48"/>

</PathFigure.Segments>
</PathFigure >
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>



<Path x:Name="arrow" Data="M 1,1.5 L 9,9 L 1,16 1, 1" HorizontalAlignment="Center" SnapsToDevicePixels="false" Fill="{Binding Path=BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}" StrokeThickness="2" VerticalAlignment="Center"/>

</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Data" TargetName="arrow" Value="M 9,1 L 1,8 L 9,16, 9,1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style x:Key="ExpanderLeftHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">



<Path x:Name="trapazoid" Fill="{Binding Path=Background, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}"  HorizontalAlignment="Center"   VerticalAlignment="Center">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="0,0" >
<PathFigure.Segments>

<ArcSegment Size="25,25" RotationAngle="45" IsLargeArc="False" SweepDirection="Clockwise" Point="0,48"/>

</PathFigure.Segments>
</PathFigure >
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
<Path x:Name="arrow" Data="M 1,1.5 L 9,9 L 1,16 1, 1" HorizontalAlignment="Center" SnapsToDevicePixels="false" Fill="{Binding Path=BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}" StrokeThickness="2" VerticalAlignment="Center"/>

</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Data" TargetName="arrow" Value="M 9,1 L 1,8 L 9,16, 9,1"/>
</Trigger>

</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style x:Key="ExpanderRightHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<Grid.LayoutTransform>
<RotateTransform Angle="180"/>
</Grid.LayoutTransform>

<Path x:Name="trapazoid" Fill="{Binding Path=Background, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}"  HorizontalAlignment="Center"   VerticalAlignment="Center">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="0,0" >
<PathFigure.Segments>

<ArcSegment Size="25,25" RotationAngle="45" IsLargeArc="False" SweepDirection="Clockwise" Point="0,48"/>

</PathFigure.Segments>
</PathFigure >
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
<Path x:Name="arrow" Data="M 1,1.5 L 9,9 L 1,16 1, 1" HorizontalAlignment="Center" SnapsToDevicePixels="false" Fill="{Binding Path=BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}" StrokeThickness="2" VerticalAlignment="Center"/>

</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Data" TargetName="arrow" Value="M 9,1 L 1,8 L 9,16, 9,1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style x:Key="ExpanderDownHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Padding="{TemplateBinding Padding}">
<Grid Background="Transparent" SnapsToDevicePixels="False">
<Grid.LayoutTransform>
<RotateTransform Angle="-90"/>
</Grid.LayoutTransform>


<Path x:Name="trapazoid" Fill="{Binding Path=Background, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}"  HorizontalAlignment="Center"   VerticalAlignment="Center">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="0,0" >
<PathFigure.Segments>

<ArcSegment Size="25,25" RotationAngle="45" IsLargeArc="False" SweepDirection="Clockwise" Point="0,48"/>

</PathFigure.Segments>
</PathFigure >
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
<Path x:Name="arrow" Data="M 1,1.5 L 9,9 L 1,16 1, 1" HorizontalAlignment="Center" SnapsToDevicePixels="false" Fill="{Binding Path=BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorType=local:CollapsiblePanel}}" StrokeThickness="2" VerticalAlignment="Center"/>

</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Data" TargetName="arrow" Value="M 9,1 L 1,8 L 9,16, 9,1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style TargetType="{x:Type local:CollapsiblePanel}">
<Setter Property="Background" Value="LightGray"/>
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Expander}">
<Border SnapsToDevicePixels="true">
<DockPanel>

<ToggleButton x:Name="HeaderSite" ContentTemplate="{TemplateBinding HeaderTemplate}" ContentTemplateSelector="{TemplateBinding HeaderTemplateSelector}" Content="{TemplateBinding Header}" DockPanel.Dock="Top" Foreground="{TemplateBinding Foreground}" FontWeight="{TemplateBinding FontWeight}" FocusVisualStyle="{StaticResource ExpanderHeaderFocusVisual}" FontStyle="{TemplateBinding FontStyle}" FontStretch="{TemplateBinding FontStretch}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsChecked="{Binding IsExpanded, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Margin="0" MinWidth="0" MinHeight="0" Padding="{TemplateBinding Padding}" Style="{StaticResource ExpanderDownHeaderStyle}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>


<Grid  
x:Name="ExpandSiteContainer"  
Visibility="Visible"  
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"  
Margin="{TemplateBinding Padding}"  
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"  
DockPanel.Dock="Bottom"                                        
>

<Grid.Tag>
<sys:Double>0.0</sys:Double>
</Grid.Tag>
<ScrollViewer  
VerticalScrollBarVisibility="Hidden"  
HorizontalScrollBarVisibility="Hidden"  

>
<ContentPresenter  
x:Name="ExpandSite"  
Focusable="false"  
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"  VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
>
</ContentPresenter>
</ScrollViewer>
</Grid>
</DockPanel>
</Border>
<ControlTemplate.Triggers>

<Trigger Property="IsExpanded" Value="true">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName ="ExpandSiteContainer"   
Storyboard.TargetProperty ="Tag"  
To="1.0" Duration ="0:0:0.45" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName ="ExpandSiteContainer"   
Storyboard.TargetProperty ="Tag"  
To="0" Duration ="0:0:0.45"/>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>

<Trigger Property="ExpandDirection" Value="Down">
<Setter Property="Height" TargetName="ExpandSiteContainer">
<Setter.Value>
<MultiBinding Converter="{StaticResource multiplyConverter}">
<Binding Path="ActualHeight" ElementName="ExpandSite"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="ExpandDirection" Value="Right">
<Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Right"/>
<Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Left"/>
<Setter Property="Style" TargetName="HeaderSite" Value="{StaticResource ExpanderRightHeaderStyle}"/>
<Setter Property="Width" TargetName="ExpandSiteContainer">
<Setter.Value>
<MultiBinding Converter="{StaticResource multiplyConverter}">
<Binding Path="ActualWidth" ElementName="ExpandSite"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="ExpandDirection" Value="Up">
<Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Top"/>
<Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Bottom"/>
<Setter Property="Style" TargetName="HeaderSite" Value="{StaticResource ExpanderUpHeaderStyle}"/>
<Setter Property="Height" TargetName="ExpandSiteContainer">
<Setter.Value>
<MultiBinding Converter="{StaticResource multiplyConverter}">
<Binding Path="ActualHeight" ElementName="ExpandSite"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="ExpandDirection" Value="Left">
<Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Left"/>
<Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Right"/>
<Setter Property="Style" TargetName="HeaderSite" Value="{StaticResource ExpanderLeftHeaderStyle}"/>
<Setter Property="Width" TargetName="ExpandSiteContainer">
<Setter.Value>
<MultiBinding Converter="{StaticResource multiplyConverter}">
<Binding Path="ActualWidth" ElementName="ExpandSite"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>

</Style>
</ResourceDictionary>


Following is the example of using CollapsiblePanel control in WPF.

<my:CollapsiblePanel Grid.Row="2" Grid.Column="1" Header="Toolbar Demo" ExpandDirection="Down" x:Name="Expander2" BorderBrush="Yellow" Background="{StaticResource ToggleButtonBrush}" IsExpanded="False">
<my:CollapsiblePanel.Content>
<Image Source="/CollapsiblePanelDemo;component/Images/Koala.jpg" Height="240"  Stretch="Fill"   />
</my:CollapsiblePanel.Content>
</my:CollapsiblePanel>

You can download complete source code from following link
Download Source Code

Sunday, July 31, 2011

Encrypt & Serialize an object

Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

But many of the time we need to encrypt the object before saving it in the file, database, etc to protect from misuse. So we have first serialize the object into bytes and then we can encrypt the bytes using Cryptography.

Below is the code snippet to encrypt/decrypt the object in VB.net. Key in the code snippet is like a password which should be same during encryption and decryption.

Encrypt Code

Public Function Encrypt(Of T)(ByVal value As T, ByVal key As String) As Byte()

        Using strm As New MemoryStream
            Dim crypt As New TripleDESCryptoServiceProvider
            Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
            Dim pdb As New Rfc2898DeriveBytes(key, slt)
            Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
            crypt.Key = bytDerivedKey
            crypt.IV = pdb.GetBytes(8)

            Using cstream As New CryptoStream(strm, crypt.CreateEncryptor, CryptoStreamMode.Write)
                Dim bFormatter As New BinaryFormatter
                bFormatter.Serialize(cstream, value)
                cstream.Close()
                strm.Close()
            End Using

            Return strm.ToArray
        End Using
    End Function

Decrypt Code

Public Function Decrypt(Of T)(ByVal bytes() As Byte, ByVal key As String) As T
        Dim value As T

        Using strm As New MemoryStream(bytes)
            Dim crypt As New TripleDESCryptoServiceProvider
            Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
            Dim pdb As New Rfc2898DeriveBytes(key, slt)
            Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
            crypt.Key = bytDerivedKey
            crypt.IV = pdb.GetBytes(8)

            Using cstream As New CryptoStream(strm, crypt.CreateDecryptor, CryptoStreamMode.Read)
                Dim bFormatter As New BinaryFormatter
                value = bFormatter.Deserialize(cstream)
                cstream.Close()
                strm.Close()
            End Using
        End Using
        Return value
    End Function

Example to use above functions

<Serializable()>
    Public ClassCustomer
      
Public PropertyCustomerID As Integer
        Public Property
CustomerName As String
    End Class

    Private Sub
SaveCustomer()
        Dim d As New Customer
       
d.CustomerID = 1
d.CustomerName = "GAURAV"
       
Dim bytes() As Byte = Encrypt(Of Customer)(d, "54321")
        My.Computer.FileSystem.WriteAllBytes("E:\Test.dat", bytes, False)
    End Sub

    Private Sub
LoadCustomer()
        Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("E:\Test.dat")
        Dim objCustomer As Customer = Decrypt(Of Customer)(bytes, "54321")
    End Sub


Thursday, May 5, 2011

ProcessCmdKey in Windows Form

Many time we need to trap the key pressed in Windows Form and based on it perform some operation. For example, stop user from closing the application when user press Alt+F4. Or want to stop user from moving from one child form to another child in a mdi form using Ctrl+Tab or stop user from moving from one tabpage to another tabpage in TabControl control. In this case ProcessCmdKey method is the best option.

ProcessCmdKey is a method in .NET which process the command key. This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. The method return true to indicate that it has processed the command key, or false to indicate that the key is not a command key. This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control.

The following example with stop user from closing the form when user press Alt+F4 and also stop user from navigate to another tabpage or child form by using Ctrl+Tab.

    Public Class Form1
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
If
keyData = (Keys.Alt Or Keys.F4) Then
Return True
ElseIf
keyData = (Keys.Control Or Keys.Tab) Then
Return True
Else
Return MyBase
.ProcessCmdKey(msg, keyData)
End If
End Function
End Class