Oct 7, 2010

Draw line on Windows Form

Drawing simple lines on a Windows form is not easier as there is no Line control. Still you can make a line by using a Panel control and setting its width or height to a few pixels. But if you want a real line, the secret is in understanding the correct set of library methods you need.

To draw a line with code you need to use GDI +(i.e. the .NET graphics library)

In VB:




Private Sub btnOk_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint 
    Dim g As Graphics = e.Graphics 
    Dim penLine As Pen = New Pen(Color.CornflowerBlue, 12) 
    g.DrawLine(penLine, 15, 0, 15, Me.Height) 
    penLine.Dispose() 
End Sub


In C#:



private void btnOk_Paint(object sender,System.Windows.Forms.PaintEventArgs e) 
{ 
  Graphics g = e.Graphics; 
  Pen penLine = new Pen(Color.CornflowerBlue, 12); 
  g.DrawLine(penLine, 15, 0, 15, this.Height); 
  penLine.Dispose(); 
} 

Oct 6, 2010

Using SHA1 algorithm

The following code demonstrates using SHA1 algorithm to hash a password:

In VB:


Imports System.Security.Cryptography 
Public Function ComputeSHA1(ByVal textToHash As String) As String 
    Dim SHA1 As SHA1CryptoServiceProvider = New SHA1CryptoServiceProvider 
    Dim byteV As Byte() = System.Text.Encoding.UTF8.GetBytes(textToHash) 
    Dim byteH As Byte() = SHA1.ComputeHash(byteV) 
    SHA1.Clear() 
    Return Convert.ToBase64String(byteH) 
End Function 


In C#:

using System.Security.Cryptography; 
public static String ComputeSHA1(string textToHash) 
{ 
    SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider(); 
    byte[] byteV = System.Text.Encoding.UTF8.GetBytes(textToHash); 
    byte[] byteH = SHA1.ComputeHash(byteV); 
    SHA1.Clear(); 
    return Convert.ToBase64String(byteH); 
} 

Oct 5, 2010

DirectCast better than CType

DirectCast

performs better than using CType when casting from an object to a more specific type because it does not use runtime helper functions.

The below example shows way to cast from type Object to another type with VB:

Private Sub txt_Submit(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtUId.Submit 
    DirectCast(sender, TextBox).BackColor = Color.Yellow
End Sub 


The DirectCast statement in this example casts the sender variable that is of type Object to a TextBox control in order to access the TextBox properties.

You can use DirectCast only when casting from a type to a related but more specific type, called a derived type. 

For example, you can use DirectCast to cast from type Control to type TextBox because TextBox is derived from Control. You cannot use DirectCast to convert from an Integer to a String type because String is not derived from Integer. DirectCast can always be used to cast from type Object to any other type because all other types derive from type Object.
Bookmark and Share