Preview DataGridView

Hi there,
Very nice sample to preview your data grid view !
As the Form is complex so i'll give the designer code

The Form Code

Public Class Form1
Private oStringFormat As StringFormat

Private oStringFormatComboBox As StringFormat

Private oButton As Button

Private oCheckbox As CheckBox

Private oComboBox As ComboBox

Private nTotalWidth As Int16

Private nRowPos As Int16

Private NewPage As Boolean

Private nPageNo As Int16

Private Header As String = "Header Test"

Private sUserName As String = "Will"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.PrintDocument1.Print()

Me.PrintPreviewDialog1.Document = Me.PrintDocument1

Me.PrintPreviewDialog1.Show()



End Sub

Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
oStringFormat = New StringFormat
oStringFormat.Alignment = StringAlignment.Near

oStringFormat.LineAlignment = StringAlignment.Center

oStringFormat.Trimming = StringTrimming.EllipsisCharacter

oStringFormatComboBox = New StringFormat
oStringFormatComboBox.LineAlignment = StringAlignment.Center

oStringFormatComboBox.FormatFlags = StringFormatFlags.NoWrap

oStringFormatComboBox.Trimming = StringTrimming.EllipsisCharacter

oButton = New Button
oCheckbox = New CheckBox
oComboBox = New ComboBox
nTotalWidth = 0


For Each oColumn As DataGridViewColumn In dgvTest.Columns
nTotalWidth += oColumn.Width


Next
nPageNo = 1

NewPage = True
nRowPos = 0


End Sub



Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

Static oColumnLefts As New ArrayList

Static oColumnWidths As New ArrayList

Static oColumnTypes As New ArrayList

Static nHeight As Int16

Dim nWidth, i, nRowsPerPage As Int16

Dim nTop As Int16 = e.MarginBounds.Top

Dim nLeft As Int16 = e.MarginBounds.Left

If nPageNo = 1 Then

For Each oColumn As DataGridViewColumn In dgvTest.Columns
nWidth = CType(Math.Floor(oColumn.Width / nTotalWidth * nTotalWidth * (e.MarginBounds.Width / nTotalWidth)), Int16)
nHeight = e.Graphics.MeasureString(oColumn.HeaderText, oColumn.InheritedStyle.Font, nWidth).Height + 11

oColumnLefts.Add(nLeft)

oColumnWidths.Add(nWidth)

oColumnTypes.Add(oColumn.GetType)

nLeft += nWidth


Next

End If

Do While nRowPos < dgvTest.Rows.Count - 1

Dim oRow As DataGridViewRow = dgvTest.Rows(nRowPos)

If nTop + nHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then
DrawFooter(e, nRowsPerPage)

NewPage = True
nPageNo += 1

e.HasMorePages = True

Exit Sub

Else

If NewPage Then

' Draw Header
e.Graphics.DrawString(Header, New Font(dgvTest.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString(Header, New Font(dgvTest.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)

' Draw Columns
nTop = e.MarginBounds.Top

i = 0


For Each oColumn As DataGridViewColumn In dgvTest.Columns
e.Graphics.FillRectangle(New SolidBrush(Drawing.Color.LightGray), New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight))
e.Graphics.DrawRectangle(Pens.Black, New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight))
e.Graphics.DrawString(oColumn.HeaderText, oColumn.InheritedStyle.Font, New SolidBrush(oColumn.InheritedStyle.ForeColor), New RectangleF(oColumnLefts(i), nTop, oColumnWidths(i), nHeight), oStringFormat)
i += 1


Next
NewPage = False

End If
nTop += nHeight

i = 0


For Each oCell As DataGridViewCell In oRow.Cells

If oColumnTypes(i) Is GetType(DataGridViewTextBoxColumn) OrElse oColumnTypes(i) Is GetType(DataGridViewLinkColumn) Then
e.Graphics.DrawString(oCell.Value.ToString, oCell.InheritedStyle.Font, New SolidBrush(oCell.InheritedStyle.ForeColor), New RectangleF(oColumnLefts(i), nTop, oColumnWidths(i), nHeight), oStringFormat)

ElseIf oColumnTypes(i) Is GetType(DataGridViewButtonColumn) Then
oButton.Text = oCell.Value.ToString

oButton.Size = New Size(oColumnWidths(i), nHeight)

Dim oBitmap As New Bitmap(oButton.Width, oButton.Height)
oButton.DrawToBitmap(oBitmap, New Rectangle(0, 0, oBitmap.Width, oBitmap.Height))
e.Graphics.DrawImage(oBitmap, New Point(oColumnLefts(i), nTop))

ElseIf oColumnTypes(i) Is GetType(DataGridViewCheckBoxColumn) Then
oCheckbox.Size = New Size(14, 14)
oCheckbox.Checked = CType(oCell.Value, Boolean)

Dim oBitmap As New Bitmap(oColumnWidths(i), nHeight)

Dim oTempGraphics As Graphics = Graphics.FromImage(oBitmap)
oTempGraphics.FillRectangle(Brushes.White, New Rectangle(0, 0, oBitmap.Width, oBitmap.Height))
oCheckbox.DrawToBitmap(oBitmap, New Rectangle(CType((oBitmap.Width - oCheckbox.Width) / 2, Int32), CType((oBitmap.Height - oCheckbox.Height) / 2, Int32), oCheckbox.Width, oCheckbox.Height))
e.Graphics.DrawImage(oBitmap, New Point(oColumnLefts(i), nTop))

ElseIf oColumnTypes(i) Is GetType(DataGridViewComboBoxColumn) Then
oComboBox.Size = New Size(oColumnWidths(i), nHeight)

Dim oBitmap As New Bitmap(oComboBox.Width, oComboBox.Height)
oComboBox.DrawToBitmap(oBitmap, New Rectangle(0, 0, oBitmap.Width, oBitmap.Height))
e.Graphics.DrawImage(oBitmap, New Point(oColumnLefts(i), nTop))
e.Graphics.DrawString(oCell.Value.ToString, oCell.InheritedStyle.Font, New SolidBrush(oCell.InheritedStyle.ForeColor), New RectangleF(oColumnLefts(i) + 1, nTop, oColumnWidths(i) - 16, nHeight), oStringFormatComboBox)

ElseIf oColumnTypes(i) Is GetType(DataGridViewImageColumn) Then

Dim oCellSize As Rectangle = New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight)

Dim oImageSize As Size = CType(oCell.Value, Image).Size
e.Graphics.DrawImage(oCell.Value, New Rectangle(oColumnLefts(i) + CType(((oCellSize.Width - oImageSize.Width ) / 2), Int32), nTop + CType(((oCellSize.Height - oImageSize.Height) / 2), Int32), CType(oCell.Value, Image).Width, CType(oCell.Value, Image).Height))

End If
e.Graphics.DrawRectangle(Pens.Black, New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight))
i += 1


Next

End If
nRowPos += 1

nRowsPerPage += 1


Loop
DrawFooter(e, nRowsPerPage)

e.HasMorePages = False

End Sub

Private Sub DrawFooter(ByVal e As System.Drawing.Printing.PrintPageEventArgs, ByVal RowsPerPage As Int32)

Dim sPageNo As String = nPageNo.ToString + " of " + Math.Ceiling(dgvTest.Rows.Count / RowsPerPage).ToString

' Right Align - User Name
e.Graphics.DrawString(sUserName, dgvTest.Font, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(sPageNo, dgvTest.Font, e.MarginBounds.Width).Width), e.MarginBounds.Top + e.MarginBounds.Height + 7)


' Left Align - Date/Time
e.Graphics.DrawString(Now.ToLongDateString + " " + Now.ToShortTimeString, dgvTest.Font, Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + e.MarginBounds.Height + 7)

' Center - Page No. Info
e.Graphics.DrawString(sPageNo, dgvTest.Font, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(sPageNo, dgvTest.Font, e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top + e.MarginBounds.Height + 31)




End Sub

End Class


The Designer Code


_
Partial Class Form1
Inherits System.Windows.Forms.Form

'Form overrides dispose to clean up the component list.
_
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
_
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1))
Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument
Me.PrintPreviewDialog1 = New System.Windows.Forms.PrintPreviewDialog
Me.Button1 = New System.Windows.Forms.Button
Me.dgvtest = New System.Windows.Forms.DataGridView
Me.Column1 = New System.Windows.Forms.DataGridViewTextBoxColumn
Me.Column2 = New System.Windows.Forms.DataGridViewTextBoxColumn
Me.Column3 = New System.Windows.Forms.DataGridViewTextBoxColumn
CType(Me.dgvtest, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'PrintDocument1
'
'
'PrintPreviewDialog1
'
Me.PrintPreviewDialog1.AutoScrollMargin = New System.Drawing.Size(0, 0)
Me.PrintPreviewDialog1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
Me.PrintPreviewDialog1.ClientSize = New System.Drawing.Size(400, 300)
Me.PrintPreviewDialog1.Enabled = True
Me.PrintPreviewDialog1.Icon = CType(resources.GetObject("PrintPreviewDialog1.Icon"), System.Drawing.Icon)
Me.PrintPreviewDialog1.Name = "PrintPreviewDialog1"
Me.PrintPreviewDialog1.Visible = False
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(13, 279)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
'
'dgvtest
'
Me.dgvtest.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dgvtest.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.Column1, Me.Column2, Me.Column3})
Me.dgvtest.Location = New System.Drawing.Point(44, 28)
Me.dgvtest.Name = "dgvtest"
Me.dgvtest.RowTemplate.Height = 24
Me.dgvtest.Size = New System.Drawing.Size(240, 150)
Me.dgvtest.TabIndex = 1
'
'Column1
'
Me.Column1.HeaderText = "Column1"
Me.Column1.Name = "Column1"
'
'Column2
'
Me.Column2.HeaderText = "Column2"
Me.Column2.Name = "Column2"
'
'Column3
'
Me.Column3.HeaderText = "Column3"
Me.Column3.Name = "Column3"
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 16.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(360, 314)
Me.Controls.Add(Me.dgvtest)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.dgvtest, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

End Sub
Friend WithEvents PrintDocument1 As System.Drawing.Printing.PrintDocument
Friend WithEvents PrintPreviewDialog1 As System.Windows.Forms.PrintPreviewDialog
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents dgvtest As System.Windows.Forms.DataGridView
Friend WithEvents Column1 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents Column2 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents Column3 As System.Windows.Forms.DataGridViewTextBoxColumn

End Class


hope it works and helps ::::)

The Easy Dot Net Project

For how long will you try to search and waste your time to found information.
How time did you waste searching for these snippets and customizing them for your need ?
You and many programers are every day wasting time serfing the web for code in sites, blogs, forums... Asking and waiting for a reply...
Now you have to change ! A new idea come to my mind... A simple namespace, very simple, quite simple that will solve the whole problem.
And how does this do the work ?
You want grantue that you'll find what you are searching for, but the class will be easy to manipulate.
How this works ?
Simply add the "DLL" to your reference in your project then use imports to import it !
And how much it helps ?
Here the adventure start, the small DLL will contain many many classes in various categories.
For example you can compress, resize, rotate, mirror a picture in the imaging class.
Or encrypt decrypt string, generate passwords.. in the Data Class
And many many more.
Developer : Omar Abid (only me, the starting is always hard)
Time : About 1 Year
Estimated numbers of line : About 20.000 line

Now imagine about 20.000 that becomes only 1!
Yes when it finishs you don't have to ;)

Calculate Folder Size in Dot Net

Thinking of it ? Why Dot Net or My don't provide th ease of knowing the folder size ?
k Bro you have to do it ur self, but if you didn't this is the code 4 u


Public abort As Boolean
Function GetFolderSize(ByVal DirPath As String, ByVal includeSubFolders As Boolean) As Long
Try
Dim size As Long = 0
Dim diBase As New DirectoryInfo(DirPath)
Dim files() As FileInfo
If includeSubFolders Then
files = diBase.GetFiles("*", SearchOption.AllDirectories)

Else
files = diBase.GetFiles("*", SearchOption.TopDirectoryOnly)
End If
Dim ie As IEnumerator = files.GetEnumerator
While ie.MoveNext And Not abort
size += DirectCast(ie.Current, FileInfo).Length
End While
Return size
Catch ex As Exception
MsgBox("Error: " & ex.Message)
Return -1
End Try
End Function

Send an Email With VB.net

Very Easy and I think all we know it, but want to add it...
'Need to declare this
' Add it also !!!
Imports System.Web.mail

Then this do all the work you need ...

'send the email
Try
Dim insMail As New MailMessage()
With insMail
.From = "omar.abid2006@gmail.com"
.To = "omar.abid2006@gmail.com"
.Subject = "test"
.Body = "test sending email"
End With
SmtpMail.SmtpServer = "your smtp server"
SmtpMail.Send(insMail)
Console.WriteLine("Successfully sent email message" + vbCrLf)
Catch err As Exception
Console.WriteLine("EXCEPTION " + err.Message + vbCrLf)
End Try

Rebooting the System

You read the old sample of shutting down Windows ??
Sure it works but I tried it with Vista and it doesn't !!
Bref, we don't have permission
So I made a search again, and let's fight to get this permission !

The Windows Class
Use the following to Shut, Reboot and logoff
Windows.ExitViaShutdown()
Windows.ExitViaReboot( )
Windows.ExitViaLogoff( )

Public Class windows
' ----- Windows constants used in shutdown permissions.
Const SE_PRIVILEGE_ENABLED As Integer = &H2
Const TOKEN_QUERY As Integer = &H8
Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
Const SE_SHUTDOWN_NAME As String = "SeShutdownPrivilege"

' ----- Shutdown method flags.
Private Enum ShutdownMethods As Integer
Logoff = 0
Shutdown = 1
Reboot = 6
End Enum

_
Private Structure TokenPrivileges
Public PrivilegeCount As Integer
Public Luid As Long
Public Attributes As Integer
End Structure

' ----- External features needed to exit Windows.
Private Declare Ansi Function AdjustTokenPrivileges _
Lib "advapi32.dll" _
(ByVal tokenHandle As IntPtr, _
ByVal disableAllPrivileges As Boolean, _
ByRef newState As TokenPrivileges, _
ByVal bufferLength As Integer, _
ByVal previousState As IntPtr, _
ByVal returnLength As IntPtr) As Boolean

Private Declare Ansi Function ExitWindowsEx _
Lib "user32.dll" _
(ByVal flags As Integer, _
ByVal reason As Integer) As Boolean

Private Declare Ansi Function GetCurrentProcess _
Lib "kernel32.dll" ( ) As IntPtr

Private Declare Ansi Sub LockWorkStation _
Lib "user32.dll" ( )

Private Declare Ansi Function LookupPrivilegeValueA _
Lib "advapi32.dll" _
(ByVal
systemName As String, _
ByVal privilegeName As String, _
ByRef lookupID As Long) As Boolean

Private Declare Ansi Function OpenProcessToken _
Lib "advapi32.dll" _
(ByVal processHandle As IntPtr, _
ByVal desiredAccess As Integer, _
ByRef tokenHandle As IntPtr) As Boolean

Private Shared Sub PerformExit( _
ByVal usingMethod As Integer)
' ----- Log off, reboot, or shut down the
system.
Dim shutdownPrivileges As TokenPrivileges
Dim processHandle As IntPtr
Dim tokenHandle As IntPtr = IntPtr.Zero

' ----- Give ourselves the privilege of shutting
' down the system. First, obtain the token.
processHandle = GetCurrentProcess( )
OpenProcessToken(processHandle, _
TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, tokenHandle)

' ----- Adjust the token to enable shutdown permissions.
shutdownPrivileges.PrivilegeCount = 1
shutdownPrivileges.Luid = 0
shutdownPrivileges.Attributes = SE_PRIVILEGE_ENABLED
LookupPrivilegeValueA(Nothing, SE_SHUTDOWN_NAME, _
shutdownPrivileges.Luid)
AdjustTokenPrivileges(tokenHandle, False, _
shutdownPrivileges, 0, IntPtr.Zero, IntPtr.Zero)

' ----- Now shut down the system.
ExitWindowsEx(usingMethod, 0)
End Sub

Public Shared Sub ExitViaLockWorkstation( )
' ----- Lock the workstation.
LockWorkStation( )
End Sub

Public Shared Sub ExitViaLogoff( )
' ----- Log off the current user.
PerformExit(ShutdownMethods.Logoff)
End Sub

Public Shared Sub ExitViaReboot( )
' ----- Reboot the system.
PerformExit(ShutdownMethods.Reboot)
End Sub

Public Shared Sub ExitViaShutdown( )
' ----- Shut down the system.
PerformExit(ShutdownMethods.Shutdown)
End Sub
End Class

The Compression Class

That's new and extremly unique !!! The compression class in .net Frame Work 2.0
Add the class, ready to use !

Imports System
Imports System.Text
Imports System.IO
Imports System.IO.Compression

Module Compress
Public Function StringCompress( _
ByVal originalText As String) As Byte( )
' ----- Generate a compressed version of a string.
' First, convert the string to a byte array.
Dim workBytes( ) As Byte = _
Encoding.UTF8.GetBytes(originalText)

' ----- Bytes will flow through a memory stream.
Dim memoryStream As New MemoryStream( )

' ----- Use the newly created memory stream for the
' compressed data.
Dim zipStream As New GZipStream(memoryStream, _
CompressionMode.Compress, True)
zipStream.Write(workBytes, 0, workBytes.Length)
zipStream.Flush( )

' ----- Close the compression stream.
zipStream.Close( )

' ----- Return the compressed bytes.
Return memoryStream.ToArray
End Function

Public Function BytesDecompress( _
ByVal compressed( ) As Byte) As String
' ----- Uncompress a previously compressed string.
' Extract the length for the decompressed string.
Dim lastFour(3) As Byte
Array.Copy(compressed, compressed.Length - 4, _
lastFour, 0, 4)
Dim bufferLength As Integer = _
BitConverter.ToInt32(lastFour, 0)

' ----- Create an uncompressed bytes buffer.
Dim buffer(bufferLength - 1) As Byte

' ----- Bytes will flow through a memory stream.
Dim memoryStream As New MemoryStream(compressed)

' ----- Create the decompression stream.
Dim decompressedStream As New GZipStream( _
memoryStream, CompressionMode.Decompress, True)

' ----- Read and decompress the data into the buffer.
decompressedStream.Read(buffer, 0, bufferLength)

' ----- Convert the bytes to a string.
Return Encoding.UTF8.GetString(buffer)
End Function

Public Sub FileCompress(ByVal sourceFile As String, _
ByVal destinationFile As String)
' ----- Decompress a previously compressed string.
' First, create the input file stream.
Dim sourceStream As New FileStream( _
sourceFile, FileMode.Open, FileAccess.Read)

' ----- Create the output file stream.
Dim destinationStream As New FileStream( _
destinationFile, FileMode.Create, FileAccess.Write)

' ----- Bytes will be processed by a compression
' stream.
Dim compressedStream As New GZipStream( _
destinationStream, CompressionMode.Compress, True)

' ----- Process bytes from one file into the other.
Const BlockSize As Integer = 4096
Dim buffer(BlockSize) As Byte
Dim bytesRead As Integer
Do
bytesRead = sourceStream.Read(buffer, 0, BlockSize)
If (bytesRead = 0) Then Exit Do
compressedStream.Write(buffer, 0, bytesRead)
Loop

' ----- Close all the streams.
sourceStream.Close( )
compressedStream.Close( )
destinationStream.Close( )
End Sub

Public Sub FileDecompress(ByVal sourceFile As String, _
ByVal destinationFile As String)
' ----- Compress the entire contents of a file, and
' store it in a new file. First, get the files
' as streams.
Dim sourceStream As New FileStream( _
sourceFile, FileMode.Open, FileAccess.Read)
Dim destinationStream As New FileStream( _
destinationFile, FileMode.Create, FileAccess.Write)

' ----- Bytes will be processed through a
' decompression stream.
Dim decompressedStream As New GZipStream( _
sourceStream, CompressionMode.Decompress, True)

' ----- Process bytes from one file into the other.
Const BlockSize As Integer = 4096
Dim buffer(BlockSize) As Byte
Dim bytesRead As Integer
Do
bytesRead = decompressedStream.Read(buffer, _
0, BlockSize)
If (bytesRead = 0) Then Exit Do
destinationStream.Write(buffer, 0, bytesRead)
Loop

' ----- Close all the streams.
sourceStream.Close( )
decompressedStream.Close( )
destinationStream.Close( )
End Sub
End Module

The Encryption Class

Hello,
One of the things the most used "Encryption" Take a look @ this super (Really Super) Class !!!
Encryption + Decryption

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

Class Encryption
Public Function GetHash(ByVal plainText As String) As String
' ----- Generate a hash. Return an empty string
' if there are any problems.
Dim plainBytes As Byte()
Dim hashEngine As MD5CryptoServiceProvider
Dim hashBytes As Byte()
Dim hashText As String

Try
' ----- Convert the plain text to a byte array.
plainBytes = Encoding.UTF8.GetBytes(plainText)

' ----- Select one of the hash engines.
hashEngine = New MD5CryptoServiceProvider

' ----- Get the hash of the plain text bytes.
hashBytes = hashEngine.ComputeHash(plainBytes)

' ----- Convert the hash bytes to a hexadecimal string.
hashText = Replace(BitConverter.ToString(hashBytes), "-", "")
Return hashText
Catch
Return ""
End Try
End Function

Public Function StringEncrypt(ByVal plainText As String, _
ByVal keyText As String) As String
' ----- Encrypt some text. Return an empty string
' if there are any problems.
Try
' ----- Remove any possible null characters.
Dim workText As String = plainText.Replace(vbNullChar, "")

' ----- Convert plain text to byte array.
Dim workBytes() As Byte = Encoding.UTF8.GetBytes(plainText)

' ----- Convert key string to 32-byte key array.
Dim keyBytes() As Byte = _
Encoding.UTF8.GetBytes(GetHash(keyText))

' ----- Create initialization vector.
Dim IV() As Byte = { _
50, 199, 10, 159, 132, 55, 236, 189, _
51, 243, 244, 91, 17, 136, 39, 230}

' ----- Create the Rijndael engine.
Dim rijndael As New RijndaelManaged

' ----- Bytes will flow through a memory stream.
Dim memoryStream As New MemoryStream()

' ----- Create the cryptography transform.
Dim cryptoTransform As ICryptoTransform
cryptoTransform = _
rijndael.CreateEncryptor(keyBytes, IV)

' ----- Bytes will be processed by CryptoStream.
Dim cryptoStream As New CryptoStream( _
memoryStream, cryptoTransform, _
CryptoStreamMode.Write)

' ----- Move the bytes through the processing stream.
cryptoStream.Write(workBytes, 0, workBytes.Length)
cryptoStream.FlushFinalBlock()

' ----- Convert binary data to a viewable string.
Dim encrypted As String = _
Convert.ToBase64String(memoryStream.ToArray)

' ----- Close the streams.
memoryStream.Close()
cryptoStream.Close()

' ----- Return the encrypted string result.
Return encrypted
Catch
Return ""
End Try
End Function

Public Function StringDecrypt(ByVal encrypted As String, _
ByVal keyText As String) As String
' ----- Decrypt a previously encrypted string. The key
' must match the one used to encrypt the string.
' Return an empty string on error.
Try
' ----- Convert encrypted string to a byte array.
Dim workBytes() As Byte = _
Convert.FromBase64String(encrypted)

' ----- Convert key string to 32-byte key array.
Dim keyBytes() As Byte = _
Encoding.UTF8.GetBytes(GetHash(keyText))

' ----- Create initialization vector.
Dim IV() As Byte = { _
50, 199, 10, 159, 132, 55, 236, 189, _
51, 243, 244, 91, 17, 136, 39, 230}

' ----- Decrypted bytes will be stored in
' a temporary array.
Dim tempBytes(workBytes.Length - 1) As Byte

' ----- Create the Rijndael engine.
Dim rijndael As New RijndaelManaged

' ----- Bytes will flow through a memory stream.
Dim memoryStream As New MemoryStream(workBytes)

' ----- Create the cryptography transform.
Dim cryptoTransform As ICryptoTransform
cryptoTransform = _
rijndael.CreateDecryptor(keyBytes, IV)

' ----- Bytes will be processed by CryptoStream.
Dim cryptoStream As New CryptoStream( _
memoryStream, cryptoTransform, _
CryptoStreamMode.Read)

' ----- Move the bytes through the processing stream.
cryptoStream.Read(tempBytes, 0, tempBytes.Length)

' ----- Close the streams.
memoryStream.Close()
cryptoStream.Close()

' ----- Convert the decrypted bytes to a string.
Dim plainText As String = _
Encoding.UTF8.GetString(tempBytes)

' ----- Return the decrypted string result.
Return plainText.Replace(vbNullChar, "")
Catch
Return ""
End Try
End Function

Public Sub FileEncrypt(ByVal sourceFile As String, _
ByVal destinationFile As String, _
ByVal keyText As String)
' ----- Create file streams.
Dim sourceStream As New FileStream( _
sourceFile, FileMode.Open, FileAccess.Read)
Dim destinationStream As New FileStream( _
destinationFile, FileMode.Create, FileAccess.Write)

' ----- Convert key string to 32-byte key array.
Dim keyBytes() As Byte = _
Encoding.UTF8.GetBytes(GetHash(keyText))

' ----- Create initialization vector.
Dim IV() As Byte = { _
50, 199, 10, 159, 132, 55, 236, 189, _
51, 243, 244, 91, 17, 136, 39, 230}

' ----- Create a Rijndael engine.
Dim rijndael As New RijndaelManaged

' ----- Create the cryptography transform.
Dim cryptoTransform As ICryptoTransform
cryptoTransform = _
rijndael.CreateEncryptor(keyBytes, IV)

' ----- Bytes will be processed by CryptoStream.
Dim cryptoStream As New CryptoStream( _
destinationStream, cryptoTransform, _
CryptoStreamMode.Write)

' ----- Process bytes from one file into the other.
Const BlockSize As Integer = 4096
Dim buffer(BlockSize) As Byte
Dim bytesRead As Integer
Do
bytesRead = sourceStream.Read(buffer, 0, BlockSize)
If (bytesRead = 0) Then Exit Do
cryptoStream.Write(buffer, 0, bytesRead)
Loop

' ----- Close the streams.
cryptoStream.Close()
sourceStream.Close()
destinationStream.Close()
End Sub

Public Sub FileDecrypt(ByVal sourceFile As String, _
ByVal destinationFile As String, _
ByVal keyText As String)

' ----- Create file streams.
Dim sourceStream As New FileStream( _
sourceFile, FileMode.Open, FileAccess.Read)
Dim destinationStream As New FileStream( _
destinationFile, FileMode.Create, FileAccess.Write)

' ----- Convert key string to 32-byte key array.
Dim keyBytes() As Byte = _
Encoding.UTF8.GetBytes(GetHash(keyText))

' ----- Create initialization vector.
Dim IV() As Byte = { _
50, 199, 10, 159, 132, 55, 236, 189, _
51, 243, 244, 91, 17, 136, 39, 230}

' ----- Create a Rijndael engine.
Dim rijndael As New RijndaelManaged

' ----- Create the cryptography transform.
Dim cryptoTransform As ICryptoTransform
cryptoTransform = _
rijndael.CreateDecryptor(keyBytes, IV)

' ----- Bytes will be processed by CryptoStream.
Dim cryptoStream As New CryptoStream( _
destinationStream, cryptoTransform, _
CryptoStreamMode.Write)

' ----- Process bytes from one file into the other.
Const BlockSize As Integer = 4096
Dim buffer(BlockSize) As Byte
Dim bytesRead As Integer
Do
bytesRead = sourceStream.Read(buffer, 0, BlockSize)
If (bytesRead = 0) Then Exit Do
cryptoStream.Write(buffer, 0, bytesRead)
Loop

' ----- Close the streams.
cryptoStream.Close()
sourceStream.Close()
destinationStream.Close()
End Sub
End class

Resolve IP Address and Host Name

Hi!
If you are making the chat (TCP/IP) program, just I tape the strating on the previous I found this step helpful for you so that your user can determine the Name of the IP Address that they are sending to !
Vice versa, the IP address of the host ;)
This is the code :
First imports "System.Net.Dns"
Now learn how to get the IP address of the Local Computer !
Dim hostAddresses() As Net.IPAddress
Dim ipList As String = ""
Dim Address As Net.IPAddress

hostAddresses = Net.Dns.GetHostAddresses(Net.Dns.GetHostName())
For Each Address In hostAddresses
ipList &= vbCrLf & Address.ToString()
Next Address
MsgBox(Net.Dns.GetHostName() & vbNewLine & ipList)
and then get the host name of an ip :
MsgBox(Net.Dns.GetHostEntry("127.0.0.1").HostName)
or Resolve the IP address of a host
Dim hostEntry As Net.IPHostEntry
Dim scanAddress As Net.IPAddress
Dim hostAddresses As String = ""
hostEntry = Net.Dns.GetHostEntry("vectra")
For Each scanAddress In hostEntry.AddressList
MsgBox(scanAddress.ToString())
Next scanAddress

DNS expert will know why resolving IP Address is more complex :)

Chat over TCP/IP

Hi again,
Did you though before of a chat over TCP/IP (Local Network).
If you decided to make a project of this chat, so let me help you begin (just the basics an then you can do all)
What you need is to know how, you can make it easily with the Net command!
the command "Net Send ComputerName(or IP address) message"
It accept IP Address, so even on an Internet Network !!
You have the command so you can make it !
This the code (if you don't know how to code)
dim Message as string = "Hello"
dim TragetComputer as string = "192.168.2.1"
Process.Start("net.exe", _
"send " & TargetComputer & _
" """ & Message & """")

But thar doesn't send !!
So you have to check the Messenger Service !
Click Start Control Panel, and open the Administrative Tools panel.
Within the Administrative Tools panel, open Services.
Locate Messenger, and double-click its icon to open the Messenger Properties window.
Set the Startup Type to Automatic, and click the Start button.
Click the OK button, and close all open Control Panel windows.

Automatics will make it run every time the windows open !
have a good time :)

Download POP3 Emails

I know that all can send mails because it's easy, lol ! but when thinking about how to receive them!
So see and try !
Well we'll use here the TCPClient Class in the System.net.socket
The following class code creates Pop3 objects to simplify accessing emails from a standard POP3 server.But keep in mind that some servers require SSL or other authentication.
First create the class "POP3" and put this code on it :

Public Class Pop3
' ----- The default TCP/IP port number for POP3 is 110.
Public Port As Integer = 110
Public Messages As Integer = 0

Private Const CommandFailure As String = "-ERR"

Private Pop3Server As TcpClient
Private CommandSender As NetworkStream
Private ContentReceiver As StreamReader

Public Sub Connect(ByVal serverName As String, _
ByVal userName As String, ByVal password As String)
' ----- Initiate the connection to a POP3 server.
Dim commandData As String
Dim contentBuffer() As Byte
Dim responseString As String
Dim parts() As String

' ----- Connect to the POP3 server.
Try
Pop3Server = New TcpClient(serverName, Port)
CommandSender = Pop3Server.GetStream()
ContentReceiver = New StreamReader(CommandSender)
Catch
Throw
End Try

If (userName <> "") Then
' ----- Authenticate with the user ID.
commandData = "USER " & userName & vbCrLf
contentBuffer = _
System.Text.Encoding.ASCII.GetBytes( _
commandData.ToCharArray())
CommandSender.Write(contentBuffer, 0, _
contentBuffer.Length)
responseString = ContentReceiver.ReadLine()
If (Left(responseString, Len(CommandFailure)) = _
CommandFailure) Then
Throw New Exception("Invalid user name.")
End If

' ----- Send the authenticating password.
commandData = "PASS " & password & vbCrLf
contentBuffer = _
System.Text.Encoding.ASCII.GetBytes( _
commandData.ToCharArray())
CommandSender.Write(contentBuffer, 0, _
contentBuffer.Length)
responseString = ContentReceiver.ReadLine()
If (Left(responseString, Len(CommandFailure)) = _
CommandFailure) Then
Throw New Exception("Invalid password.")
End If
End If

' ----- Logged in. On some servers, the PASS command
' is not enough to push the server into a
' transaction state. Send a STAT command twice.
commandData = "STAT" + vbCrLf
contentBuffer = System.Text.Encoding.ASCII.GetBytes( _
commandData.ToCharArray())
CommandSender.Write(contentBuffer, 0, _
contentBuffer.Length)
responseString = ContentReceiver.ReadLine()

' ----- Get a count of the messages.
commandData = "STAT" + vbCrLf
contentBuffer = System.Text.Encoding.ASCII.GetBytes( _
commandData.ToCharArray())
CommandSender.Write(contentBuffer, 0, _
contentBuffer.Length)
responseString = ContentReceiver.ReadLine()
If (Left(responseString, Len(CommandFailure)) = _
CommandFailure) Then
Throw New Exception( _
"Could not retrieve message count.")
End If

' ----- The response includes two integers: a count
' and a size, separated by a space. Skip over
' the "+OK" part also.
parts = Split(responseString, " ")
Messages = Val(parts(1))
End Sub

Public Sub Disconnect()
' ----- Disconnect from the
POP3 server.
Dim commandData As String
Dim contentBuffer() As Byte
Dim responseString As String

' ----- Tell the server we're through.
commandData = "QUIT" & vbCrLf
contentBuffer = System.Text.Encoding.ASCII.GetBytes( _
commandData.ToCharArray())
CommandSender.Write(contentBuffer, 0, _
contentBuffer.Length)
responseString = ContentReceiver.ReadLine()

' ----- End the connection.
ContentReceiver.Close()
CommandSender.Close()

Pop3Server.Close()
End Sub

Function GetMessage(ByVal whichMessage As Integer) _
As String
' ----- Retrieve a single email message.
Dim commandData As String
Dim contentBuffer() As Byte
Dim responseString As String
Dim theMessage As New System.Text.StringBuilder
Dim oneLine As String

' ----- Check for an invalid message.
If (whichMessage <> Messages) Then
Throw New ArgumentOutOfRangeException(whichMessage, _
"Messages are numbered from 1 to the number " & _
"identified by the Messages property.")
End If

Try
' ----- Request the message.
commandData = "RETR " & whichMessage & vbCrLf
contentBuffer = _
System.Text.Encoding.ASCII.GetBytes( _
commandData.ToCharArray())
CommandSender.Write(contentBuffer, 0, _
contentBuffer.Length)
responseString = ContentReceiver.ReadLine()
If (Left(responseString, Len(CommandFailure)) = _
CommandFailure) Then
Throw New Exception("Message retrieval failed.")
End If

' ----- The message is all data until a line with
' a single dot (.) appears.
Do While (ContentReceiver.EndOfStream = False)
oneLine = ContentReceiver.ReadLine()
If (oneLine = ".") Then Exit Do
theMessage.AppendLine(oneLine)
Loop
Catch ex As InvalidOperationException
MsgBox("Message retrieval failed: " & ex.Message)
End Try

' ----- Return the constructed message.
Return theMessage.ToString()
End Function
End Class

Now let's Manage the form (make a new form) so add three TextBox controls named ServerName, UserName, and UserPassword. Set the UserPassword control's PasswordChar field to the asterisk character (*). Add a ListBox control named MessageList and two Button controls named ActGet and ActView. Set the Button controls' Text properties to Get Messages and View Message, respectively.


and then put this code

Private POP3Connection As Pop3 = Nothing

Private Sub ActGet_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ActGet.Click
' ----- Initiate a POP3 connection.
Dim counter As Integer

' ----- First, disconnect any previous connection.
If (POP3Connection IsNot Nothing) Then
Try
POP3Connection.Disconnect()
Catch ex As Exception
' ----- Ignore.
End Try
End If
POP3Connection = Nothing

' ----- Clear any previous messages.
MessageList.Items.Clear()

' ----- Try the new connection.
Try

POP3Connection = New Pop3
POP3Connection.Connect(ServerName.Text, _
UserName.Text, UserPassword.Text)
Catch ex As Exception
MsgBox("Connection failure: " & ex.Message)
POP3Connection = Nothing
Return
End Try

' ----- How many messages?
If (POP3Connection.Messages = 0) Then
MsgBox("No messages found.")
POP3Connection.Disconnect()
POP3Connection = Nothing
Return
End If

' ----- Show each message.
For counter = 1 To POP3Connection.Messages
MessageList.Items.Add("Message Number " & counter)
Next counter
End Sub

Private Sub ActView_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ActView.Click
' ----- Show a message.
Dim whichMessage As Integer
Dim parts As String()
Dim content As String

' ----- Which message? Each item has the format:
' Message Number x
If (MessageList.SelectedIndex = -1) Then Return
parts = Split(CStr(MessageList.SelectedItem), " ")
whichMessage = CInt(Val(parts(2)))

' ----- Get the content.
content = POP3Connection.GetMessage(whichMessage)

' ----- Show the content.
MsgBox(content)
End Sub

Private Sub MessageList_DoubleClick(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MessageList.DoubleClick
' ----- Same as the View button.
ActView.PerformClick()
End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles Me.FormClosing
' ----- Disconnect before leaving.
On Error Resume Next

If (
POP3Connection IsNot Nothing) Then
POP3Connection.Disconnect()
POP3Connection = Nothing
End If
End Sub


Now try ! Works or not ?

Get All Windows Fonts

Hi,
This is a sample code to get all windows fonts

Dim familyName As String
Dim familyList As String = ""
Dim fontFamilies() As FontFamily
Dim installedFontCollection As New Drawing.Text.InstalledFontCollection
fontFamilies = installedFontCollection.Families
Dim count As Integer = fontFamilies.Length
Dim j As Integer
MsgBox("Number of fonts:" & count)

While j < count
familyName = fontFamilies(j).Name
ComboBox1.Items.Add(familyName)
j += 1
End While

Find all opened program

A simple sample but very helpful when you want to know active windows and process around you !

Dim Proc() As Process = Process.GetProcesses
For Each p As Process In Proc
Me.ListBox1.Items.Add("Process Name - " & p.ProcessName)
Next
For Each p2 As Process In Proc
If p2.MainWindowTitle <> "" Then
Me.ListBox1.Items.Add("Process window title - " & p2.MainWindowTitle)
End If
Next

Printing Tutorial

Yeah,
This is the first part of my Print Tutorial ! OK will help you begin =)


In this small tutor I 'll show you some basics of printing with VB 2005, I made and tested my self.
Ok may be the first thing to think on is to find printers on the computer.
So take a look @ this code
Ok add a new combo box and all should works well !
Dim InstalledPrinters As String
' Find all printers installed
For Each InstalledPrinters In _
PrinterSettings.InstalledPrinters
combobox1.Items.Add(InstalledPrinters)
Next InstalledPrinters
' Set the combo to the first printer in the list
If combobox1.Items.Count > 0 Then
combobox1.SelectedIndex = 0
End If
Now let's learn some basics of preview and print. So let's think on how to preview a document.
First let's make a design to our preview (some limits) we need then to use VB Pen
Take a look, the following code will help you to show a pageview !
This is the whole code to more help you !
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnPreview As System.Windows.Forms.Button
Friend WithEvents pdocTest As System.Drawing.Printing.PrintDocument
Friend WithEvents ppdTest As System.Windows.Forms.PrintPreviewDialog
Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
Me.btnPreview = New System.Windows.Forms.Button
Me.pdocTest = New System.Drawing.Printing.PrintDocument
Me.ppdTest = New System.Windows.Forms.PrintPreviewDialog
Me.SuspendLayout()
'
'btnPreview
'
Me.btnPreview.Location = New System.Drawing.Point(79, 43)
Me.btnPreview.Name = "btnPreview"
Me.btnPreview.TabIndex = 0
Me.btnPreview.Text = "Preview"
'
'pdocTest
'
'
'ppdTest
'
Me.ppdTest.AutoScrollMargin = New System.Drawing.Size(0, 0)
Me.ppdTest.AutoScrollMinSize = New System.Drawing.Size(0, 0)
Me.ppdTest.ClientSize = New System.Drawing.Size(400, 300)
Me.ppdTest.Document = Me.pdocTest
Me.ppdTest.Enabled = True
Me.ppdTest.Icon = CType(resources.GetObject("ppdTest.Icon"), System.Drawing.Icon)
Me.ppdTest.Location = New System.Drawing.Point(144, 18)
Me.ppdTest.MinimumSize = New System.Drawing.Size(375, 250)
Me.ppdTest.Name = "ppdTest"
Me.ppdTest.TransparencyKey = System.Drawing.Color.Empty
Me.ppdTest.Visible = False
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(232, 109)
Me.Controls.Add(Me.btnPreview)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click
' Convert the dialog into a Form.
Dim dlg As Form = DirectCast(ppdTest, Form)
' Set a "restore" size.
dlg.Width = 600
dlg.Height = 400
' Start the dialog maximized.
dlg.WindowState = FormWindowState.Maximized
' Show the dialog.
ppdTest.ShowDialog()
End Sub
Private Sub pdocTest_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pdocTest.PrintPage
Dim the_pen As New Pen(Color.Blue, 10)
e.Graphics.DrawRectangle(the_pen, e.MarginBounds)
the_pen.Dispose()
e.HasMorePages = False
End Sub
End Class

That's quite good for today come some days later coz me only I don't know much and I'm learning ;)

Simple Note Pad

Hi Future Office developers,

Take this is a simple sample notepad. Perhaps helpful for lots of you . Especially who just begin !


Imports System.io
Public Class FrmWpad
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
Friend WithEvents StatusBarPanel1 As System.Windows.Forms.StatusBarPanel
Friend WithEvents StatusBarPanel2 As System.Windows.Forms.StatusBarPanel
Friend WithEvents StatusBarPanel3 As System.Windows.Forms.StatusBarPanel
Friend WithEvents MenuItem6 As System.Windows.Forms.MenuItem
Friend WithEvents MenuItem9 As System.Windows.Forms.MenuItem
Friend WithEvents WPad As System.Windows.Forms.RichTextBox
Friend WithEvents MenuItem14 As System.Windows.Forms.MenuItem
Friend WithEvents MenuItem18 As System.Windows.Forms.MenuItem
Friend WithEvents MnuFile As System.Windows.Forms.MenuItem
Friend WithEvents MnuNew As System.Windows.Forms.MenuItem
Friend WithEvents MnuOpen As System.Windows.Forms.MenuItem
Friend WithEvents MnuSave As System.Windows.Forms.MenuItem
Friend WithEvents MnuSaveAs As System.Windows.Forms.MenuItem
Friend WithEvents MnuPrint As System.Windows.Forms.MenuItem
Friend WithEvents MnuPreview As System.Windows.Forms.MenuItem
Friend WithEvents MnuExit As System.Windows.Forms.MenuItem
Friend WithEvents MnuEdit As System.Windows.Forms.MenuItem
Friend WithEvents MnuUndo As System.Windows.Forms.MenuItem
Friend WithEvents MnuRedo As System.Windows.Forms.MenuItem
Friend WithEvents MnuCut As System.Windows.Forms.MenuItem
Friend WithEvents MnuCopy As System.Windows.Forms.MenuItem
Friend WithEvents MnuPaste As System.Windows.Forms.MenuItem
Friend WithEvents MnuSelectAll As System.Windows.Forms.MenuItem
Friend WithEvents MnuTime As System.Windows.Forms.MenuItem
Friend WithEvents MnuFormat As System.Windows.Forms.MenuItem
Friend WithEvents MnuWordWrap As System.Windows.Forms.MenuItem
Friend WithEvents MnuFont As System.Windows.Forms.MenuItem
Friend WithEvents MnuView As System.Windows.Forms.MenuItem
Friend WithEvents MnuStatusBar As System.Windows.Forms.MenuItem
Friend WithEvents MnuHelp As System.Windows.Forms.MenuItem
Friend WithEvents MnuAbout As System.Windows.Forms.MenuItem
Friend WithEvents MnuBackColor As System.Windows.Forms.MenuItem
Friend WithEvents StbWPad As System.Windows.Forms.StatusBar
Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
Friend WithEvents MnuALeft As System.Windows.Forms.MenuItem
Friend WithEvents MnuARight As System.Windows.Forms.MenuItem
Friend WithEvents MnuCenter As System.Windows.Forms.MenuItem
Friend WithEvents FontDialog1 As System.Windows.Forms.FontDialog
Friend WithEvents ColorDialog1 As System.Windows.Forms.ColorDialog
Friend WithEvents PrintDialog1 As System.Windows.Forms.PrintDialog
Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog
Friend WithEvents SaveFileDialog1 As System.Windows.Forms.SaveFileDialog
Friend WithEvents PrintPreviewDialog1 As System.Windows.Forms.PrintPreviewDialog
Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(FrmWpad))
Me.MainMenu1 = New System.Windows.Forms.MainMenu
Me.MnuFile = New System.Windows.Forms.MenuItem
Me.MnuNew = New System.Windows.Forms.MenuItem
Me.MnuOpen = New System.Windows.Forms.MenuItem
Me.MnuSave = New System.Windows.Forms.MenuItem
Me.MnuSaveAs = New System.Windows.Forms.MenuItem
Me.MenuItem6 = New System.Windows.Forms.MenuItem
Me.MnuPrint = New System.Windows.Forms.MenuItem
Me.MnuPreview = New System.Windows.Forms.MenuItem
Me.MenuItem9 = New System.Windows.Forms.MenuItem
Me.MnuExit = New System.Windows.Forms.MenuItem
Me.MnuEdit = New System.Windows.Forms.MenuItem
Me.MnuUndo = New System.Windows.Forms.MenuItem
Me.MnuRedo = New System.Windows.Forms.MenuItem
Me.MenuItem14 = New System.Windows.Forms.MenuItem
Me.MnuCut = New System.Windows.Forms.MenuItem
Me.MnuCopy = New System.Windows.Forms.MenuItem
Me.MnuPaste = New System.Windows.Forms.MenuItem
Me.MenuItem18 = New System.Windows.Forms.MenuItem
Me.MnuSelectAll = New System.Windows.Forms.MenuItem
Me.MnuTime = New System.Windows.Forms.MenuItem
Me.MnuFormat = New System.Windows.Forms.MenuItem
Me.MnuWordWrap = New System.Windows.Forms.MenuItem
Me.MnuFont = New System.Windows.Forms.MenuItem
Me.MnuBackColor = New System.Windows.Forms.MenuItem
Me.MenuItem1 = New System.Windows.Forms.MenuItem
Me.MnuALeft = New System.Windows.Forms.MenuItem
Me.MnuARight = New System.Windows.Forms.MenuItem
Me.MnuCenter = New System.Windows.Forms.MenuItem
Me.MnuView = New System.Windows.Forms.MenuItem
Me.MnuStatusBar = New System.Windows.Forms.MenuItem
Me.MnuHelp = New System.Windows.Forms.MenuItem
Me.MnuAbout = New System.Windows.Forms.MenuItem
Me.StbWPad = New System.Windows.Forms.StatusBar
Me.StatusBarPanel1 = New System.Windows.Forms.StatusBarPanel
Me.StatusBarPanel2 = New System.Windows.Forms.StatusBarPanel
Me.StatusBarPanel3 = New System.Windows.Forms.StatusBarPanel
Me.WPad = New System.Windows.Forms.RichTextBox
Me.FontDialog1 = New System.Windows.Forms.FontDialog
Me.ColorDialog1 = New System.Windows.Forms.ColorDialog
Me.PrintDialog1 = New System.Windows.Forms.PrintDialog
Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog
Me.SaveFileDialog1 = New System.Windows.Forms.SaveFileDialog
Me.PrintPreviewDialog1 = New System.Windows.Forms.PrintPreviewDialog
CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.StatusBarPanel2, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.StatusBarPanel3, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'MainMenu1
'
Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MnuFile, Me.MnuEdit, Me.MnuFormat, Me.MnuView, Me.MnuHelp})
'
'MnuFile
'
Me.MnuFile.Index = 0
Me.MnuFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MnuNew, Me.MnuOpen, Me.MnuSave, Me.MnuSaveAs, Me.MenuItem6, Me.MnuPrint, Me.MnuPreview, Me.MenuItem9, Me.MnuExit})
Me.MnuFile.Text = "&File"
'
'MnuNew
'
Me.MnuNew.Index = 0
Me.MnuNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN
Me.MnuNew.Text = "&New"
'
'MnuOpen
'
Me.MnuOpen.Index = 1
Me.MnuOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO
Me.MnuOpen.Text = "&Open..."
'
'MnuSave
'
Me.MnuSave.Index = 2
Me.MnuSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS
Me.MnuSave.Text = "Save"
Me.MnuSave.Visible = False
'
'MnuSaveAs
'
Me.MnuSaveAs.Index = 3
Me.MnuSaveAs.Text = "Save As..."
'
'MenuItem6
'
Me.MenuItem6.Index = 4
Me.MenuItem6.Text = "-"
Me.MenuItem6.Visible = False
'
'MnuPrint
'
Me.MnuPrint.Index = 5
Me.MnuPrint.Shortcut = System.Windows.Forms.Shortcut.CtrlP
Me.MnuPrint.Text = "Print..."
Me.MnuPrint.Visible = False
'
'MnuPreview
'
Me.MnuPreview.Index = 6
Me.MnuPreview.Text = "Print Preview"
Me.MnuPreview.Visible = False
'
'MenuItem9
'
Me.MenuItem9.Index = 7
Me.MenuItem9.Text = "-"
'
'MnuExit
'
Me.MnuExit.Index = 8
Me.MnuExit.Text = "Exit"
'
'MnuEdit
'
Me.MnuEdit.Index = 1
Me.MnuEdit.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MnuUndo, Me.MnuRedo, Me.MenuItem14, Me.MnuCut, Me.MnuCopy, Me.MnuPaste, Me.MenuItem18, Me.MnuSelectAll, Me.MnuTime})
Me.MnuEdit.Text = "&Edit"
'
'MnuUndo
'
Me.MnuUndo.Index = 0
Me.MnuUndo.Shortcut = System.Windows.Forms.Shortcut.CtrlZ
Me.MnuUndo.Text = "Undo"
'
'MnuRedo
'
Me.MnuRedo.Index = 1
Me.MnuRedo.Shortcut = System.Windows.Forms.Shortcut.CtrlY
Me.MnuRedo.Text = "Redo"
'
'MenuItem14
'
Me.MenuItem14.Index = 2
Me.MenuItem14.Text = "-"
'
'MnuCut
'
Me.MnuCut.Index = 3
Me.MnuCut.Shortcut = System.Windows.Forms.Shortcut.CtrlX
Me.MnuCut.Text = "Cut"
'
'MnuCopy
'
Me.MnuCopy.Index = 4
Me.MnuCopy.Shortcut = System.Windows.Forms.Shortcut.CtrlC
Me.MnuCopy.Text = "Copy"
'
'MnuPaste
'
Me.MnuPaste.Enabled = False
Me.MnuPaste.Index = 5
Me.MnuPaste.Shortcut = System.Windows.Forms.Shortcut.CtrlV
Me.MnuPaste.Text = "Paste"
'
'MenuItem18
'
Me.MenuItem18.Index = 6
Me.MenuItem18.Text = "-"
'
'MnuSelectAll
'
Me.MnuSelectAll.Index = 7
Me.MnuSelectAll.Shortcut = System.Windows.Forms.Shortcut.CtrlA
Me.MnuSelectAll.Text = "Select All"
'
'MnuTime
'
Me.MnuTime.Index = 8
Me.MnuTime.Shortcut = System.Windows.Forms.Shortcut.F5
Me.MnuTime.Text = "Time/Date"
'
'MnuFormat
'
Me.MnuFormat.Index = 2
Me.MnuFormat.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MnuWordWrap, Me.MnuFont, Me.MnuBackColor, Me.MenuItem1, Me.MnuALeft, Me.MnuARight, Me.MnuCenter})
Me.MnuFormat.Text = "F&ormat"
'
'MnuWordWrap
'
Me.MnuWordWrap.Checked = True
Me.MnuWordWrap.Index = 0
Me.MnuWordWrap.Text = "Word Wrap"
'
'MnuFont
'
Me.MnuFont.Index = 1
Me.MnuFont.Text = "Font..."
'
'MnuBackColor
'
Me.MnuBackColor.Index = 2
Me.MnuBackColor.Text = "Background Color..."
'
'MenuItem1
'
Me.MenuItem1.Index = 3
Me.MenuItem1.Text = "-"
'
'MnuALeft
'
Me.MnuALeft.Index = 4
Me.MnuALeft.Text = "Left Align"
'
'MnuARight
'
Me.MnuARight.Index = 5
Me.MnuARight.Text = "Right Align"
'
'MnuCenter
'
Me.MnuCenter.Index = 6
Me.MnuCenter.Text = "Center"
'
'MnuView
'
Me.MnuView.Index = 3
Me.MnuView.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MnuStatusBar})
Me.MnuView.Text = "&View"
'
'MnuStatusBar
'
Me.MnuStatusBar.Checked = True
Me.MnuStatusBar.Index = 0
Me.MnuStatusBar.Text = "Status Bar"
'
'MnuHelp
'
Me.MnuHelp.Index = 4
Me.MnuHelp.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MnuAbout})
Me.MnuHelp.Text = "&Help"
'
'MnuAbout
'
Me.MnuAbout.Index = 0
Me.MnuAbout.Shortcut = System.Windows.Forms.Shortcut.F1
Me.MnuAbout.Text = "About SAM_WordPad"
'
'StbWPad
'
Me.StbWPad.Location = New System.Drawing.Point(0, 427)
Me.StbWPad.Name = "StbWPad"
Me.StbWPad.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.StatusBarPanel1, Me.StatusBarPanel2, Me.StatusBarPanel3})
Me.StbWPad.ShowPanels = True
Me.StbWPad.Size = New System.Drawing.Size(704, 22)
Me.StbWPad.TabIndex = 0
'
'StatusBarPanel1
'
Me.StatusBarPanel1.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring
Me.StatusBarPanel1.BorderStyle = System.Windows.Forms.StatusBarPanelBorderStyle.None
Me.StatusBarPanel1.Text = "Press F1 for Help"
Me.StatusBarPanel1.Width = 600
'
'StatusBarPanel2
'
Me.StatusBarPanel2.Width = 50
'
'StatusBarPanel3
'
Me.StatusBarPanel3.Width = 38
'
'WPad
'
Me.WPad.AcceptsTab = True
Me.WPad.Dock = System.Windows.Forms.DockStyle.Fill
Me.WPad.Font = New System.Drawing.Font("Times New Roman", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.WPad.HideSelection = False
Me.WPad.Location = New System.Drawing.Point(0, 0)
Me.WPad.Name = "WPad"
Me.WPad.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedBoth
Me.WPad.Size = New System.Drawing.Size(704, 427)
Me.WPad.TabIndex = 1
Me.WPad.Text = ""
'
'PrintPreviewDialog1
'
Me.PrintPreviewDialog1.AutoScrollMargin = New System.Drawing.Size(0, 0)
Me.PrintPreviewDialog1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
Me.PrintPreviewDialog1.ClientSize = New System.Drawing.Size(400, 300)
Me.PrintPreviewDialog1.Enabled = True
Me.PrintPreviewDialog1.Icon = CType(resources.GetObject("PrintPreviewDialog1.Icon"), System.Drawing.Icon)
Me.PrintPreviewDialog1.Location = New System.Drawing.Point(125, 17)
Me.PrintPreviewDialog1.MinimumSize = New System.Drawing.Size(375, 250)
Me.PrintPreviewDialog1.Name = "PrintPreviewDialog1"
Me.PrintPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty
Me.PrintPreviewDialog1.Visible = False
'
'FrmWpad
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(704, 449)
Me.Controls.Add(Me.WPad)
Me.Controls.Add(Me.StbWPad)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Menu = Me.MainMenu1
Me.Name = "FrmWpad"
Me.Text = "Untitled - SAM_WordPad"
CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.StatusBarPanel2, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.StatusBarPanel3, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub MnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuExit.Click
End
End Sub
Private Sub MnuStatusBar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuStatusBar.Click
StbWPad.Visible = Not StbWPad.Visible
MnuStatusBar.Checked = Not MnuStatusBar.Checked
End Sub
Private Sub MnuWordWrap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuWordWrap.Click
WPad.WordWrap = Not WPad.WordWrap
MnuWordWrap.Checked = Not MnuWordWrap.Checked
End Sub
Private Sub MnuTime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuTime.Click
WPad.Text = WPad.Text & TimeString & " " & DateString
End Sub
Private Sub FrmWpad_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub MnuSelectAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuSelectAll.Click
WPad.SelectionStart = 0
WPad.SelectionLength = Len(WPad.Text)
End Sub
Private Sub MnuALeft_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuALeft.Click
WPad.SelectionAlignment = HorizontalAlignment.Left
End Sub
Private Sub MnuARight_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuARight.Click
WPad.SelectionAlignment = HorizontalAlignment.Right
End Sub
Private Sub MnuCenter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCenter.Click
WPad.SelectionAlignment = HorizontalAlignment.Center
End Sub
Private Sub MnuCut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCut.Click
System.Windows.Forms.Clipboard.SetDataObject(WPad.SelectedText)
WPad.SelectedText = ""
MnuPaste.Enabled = True
End Sub
Private Sub MnuCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MnuCopy.Click
System.Windows.Forms.Clipboard.SetDataObject(WPad.SelectedText)
MnuPaste.Enabled = True
End Sub
Private Sub MnuPaste_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MnuPaste.Click
WPad.Paste()
End Sub
Private Sub MnuUndo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuUndo.Click
WPad.Undo()
End Sub
Private Sub MnuRedo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuRedo.Click
WPad.Redo()
End Sub
Private Sub MnuFormat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFormat.Click
End Sub
Private Sub MnuFont_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFont.Click
FontDialog1.ShowColor = True
FontDialog1.ShowEffects = True
FontDialog1.ShowHelp = True
If FontDialog1.ShowDialog = DialogResult.OK Then
WPad.Font = FontDialog1.Font
WPad.ForeColor = FontDialog1.Color
End If
End Sub

Private Sub MnuBackColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuBackColor.Click
ColorDialog1.FullOpen = True
If ColorDialog1.ShowDialog = DialogResult.OK Then
WPad.BackColor = ColorDialog1.Color
End If
End Sub
Private Sub MnuOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuOpen.Click
Dim str As String
OpenFileDialog1.Filter = "Text Files (*.txt)*.txt All Files (*.*)*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
str = OpenFileDialog1.FileName
Dim ob As StreamReader = New StreamReader(str)
WPad.Text = ob.ReadToEnd()
ob.Close()
End If
End Sub
Private Sub MnuSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuSaveAs.Click
Dim str As String
SaveFileDialog1.Filter = "Text Files (*.txt)*.txt"
SaveFileDialog1.AddExtension = True
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
str = SaveFileDialog1.FileName
Dim ob As StreamWriter = New StreamWriter(str, False)
ob.Write(WPad.Text)
ob.Close()
End If
End Sub
End Class

Make a new *.vb class and post it all. Clear all the form before pasting.
Or create new (empty) one

How to get high traffic

Hi traffic seeker and adsense pirates !
I think that lots of you search for traffic for it's site so that spaming the whole pla(net) . Ok I'm not against especially lot of groups accept spam. and they accept it for having large traffic lol.
But the thing that I mentionned well that google (this ultra big traffic) can redirect it's traffic for you!

How to upload your content to google ?
First submit your site and I think that all of you have done this step, but submit it @ least to ten search engine like Yahoo, MSN, Live, Ask, Altavista...
Second let's begin with Google Webmaster tools !
First on it , subscribe to google web master tools and add a site profile.
Then make the site verification. I'll suggest that you upload a HTML file, if you change your home page later you'll need to put the tag again !

Now we need a site map. (only if pages < href="http://www.xml-sitemaps.com/">www.xml-sitemaps.com and make a site map to your site (web based application so you want download anything with you !)

But google still doesn't index your pages or let say slowley indexes your pages.
So something is going wrong... ON YOUR SITE!
Your page header must be clear and well organised and will give you a sample to focus on it: the sample of SQL Warrior that I optimized for Search engine especially the forums you can see the head (http://sqlwarrior.freehostia.com) and (http://sqlwarrior.freehostia.com/forum)

See how it's organised to get an idea for your page !

wAAAk google indexed my page but i'm not the first !
Dear,
No one can guarantee a #1 ranking on Google
So how ?
Now you can go to other forums and show your site but... don't spam

Many Web master face this problem.
Many hits but no clicks !
Ask your self somequestions @ least !
Are your visitors interested on your site ?
Does your site contain important information ?
I know I can have 5000 hit / day but if all visitors see the first page then out !! no clicks !
You 'll need to have interesting things on your site and ads won't have revenue unless 3 or 4 week or activities !

Hope this comments helps you have a great site !

Being confused !

Hi Pro-do ;)

Take a look @ this tutor
No isn't me who write it all ! but just organise information found on the web


Connecting to an OLE DB Data Source
OLE DB is a specification for wrapping data sources in a COM-based API so that data sources can be accessed in a polymorphic way. The concept is the same as ADO.NET's concept of managed providers. OLE DB predates ADO.NET and will eventually be superseded by it. However, over the years, OLE DB providers have been written for many data sources, including Oracle, Microsoft Access, Microsoft Exchange, and others, whereas currently only one product--SQL Server--is natively supported by an ADO.NET managed provider. To provide immediate support in ADO.NET for a wide range of data sources, Microsoft has supplied an ADO.NET managed provider for OLE DB. That means that ADO.NET can work with any data source for which there is an OLE DB data provider. Furthermore, because there is an OLE DB provider that wraps ODBC (an even older data-access technology), ADO.NET can work with virtually all legacy data, regardless of the source.
Connecting to an OLE DB data source is similar to connecting to SQL Server, with a few differences: the OleDbConnection class (from the System.Data.OleDb namespace) is used instead of the SqlConnection class, and the connection string is slightly different. When using the OleDbConnection class, the connection string must specify the OLE DB provider that is to be used as well as additional information that tells the OLE DB provider where the actual data is. For example, the following code opens a connection to the Northwind sample database in Microsoft Access:
' Open a connection to the database.
Dim strConnection As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& "C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb"
Dim cn As OleDbConnection = New OleDbConnection(strConnection)
cn.Open( )
Similarly, this code opens a connection to an Oracle database:
' Open a connection to the database.
Dim strConnection As String = _
"Provider=MSDAORA.1;User ID=MyID;Password=MyPassword;" _
& "Data Source=MyDatabaseService.MyDomain.com"
Dim cn As OleDbConnection = New OleDbConnection(strConnection)
cn.Open( )
The values of each setting in the connection string, and even the set of settings that are allowed in the connection string, are dependent on the specific OLE DB provider being used. Refer to the documentation for the specific OLE DB provider for more information.
Table 8-2 shows the provider names for several of the most common OLE DB providers.
Table 8-2: Common OLE DB provider names
Data source
OLE DB provider name
Microsoft Access
Microsoft.Jet.OLEDB.4.0
Microsoft Indexing Service
MSIDXS.1
Microsoft SQL Server
SQLOLEDB.1
Oracle
MSDAORA.1
Reading Data into a DataSet
The DataSet class is ADO.NET's highly flexible, general-purpose mechanism for reading and updating data. Example 8-1 shows how to issue a SQL SELECT statement against the SQL Server Northwind sample database to retrieve and display the names of companies located in London. The resulting display is shown in Figure 8-1.
Figure 8-1. The output generated by the code in Example 8-1
FPRIVATE "TYPE=PICT;ALT=Figure 1"
Example 8-1: Retrieving data from SQL Server using a SQL SELECT statement
' Open a connection to the database.
Dim strConnection As String = _
"Data Source=localhost; Initial Catalog=Northwind;" _
& "Integrated Security=True"
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Set up a data set command object.
Dim strSelect As String = "SELECT * FROM Customers WHERE City = 'London'"
Dim dscmd As New SqlDataAdapter(strSelect, cn)
' Load a data set.
Dim ds As New DataSet( )
dscmd.Fill(ds, "LondonCustomers")
' Close the connection.
cn.Close( )
' Do something with the data set.
Dim dt As DataTable = ds.Tables.Item("LondonCustomers")
Dim rowCustomer As DataRow
For Each rowCustomer In dt.Rows
Console.WriteLine(rowCustomer.Item("CompanyName"))
Next
The code in Example 8-1 performs the following steps to obtain data from the database:
Opens a connection to the database using a SqlConnection object.
Instantiates an object of type SqlDataAdapter in preparation for filling a DataSet object. In Example 8-1, a SQL SELECT command string and a Connection object are passed to the SqlDataAdapter object's constructor.
Instantiates an object of type DataSet and fills it by calling the SqlDataAdapter object's Fill method.

The DataSet class encapsulates a set of tables and the relations between those tables. Figure 8-2 shows a class model diagram containing the DataSet and related classes. The DataSet is always completely disconnected from any data source. In fact, the DataSet has no knowledge of the source of its tables and relations. They may be dynamically created using methods on the DataSet, or they may be loaded from a data source. In the case of the SQL Server managed provider, a DataSet can be loaded from a SQL Server database using an SqlDataAdapter object. This is what was done in Example 8-1.
Figure 8-2. A class model diagram for the DataSet and related classes
FPRIVATE "TYPE=PICT;ALT=Figure 2"
After a DataSet is loaded, its data can be changed, added to, or deleted, all without affecting the data source. Indeed, a database connection does not need to be maintained during these updates. When ready, the updates can be written back to the database by establishing a new connection and calling the SqlDataAdapter object's Update method. Examples of writing updates to a database are shown later in this chapter.Navigating the DataSet
In this section you'll learn how to find specific data in a DataSet object, how to make changes to that data, and how to write those changes back to a database.
Finding Tables
The DataSet object's Tables property holds a TablesCollection object that contains the DataTable objects in the DataSet. The following code loops through all the tables in the DataSet and displays their names:
' Iterate through the tables in the DataSet ds.
Dim dt As DataTable
For Each dt In ds.Tables
Console.WriteLine(dt.TableName)
Next
This code does the same thing, using a numeric index on the TablesCollection object:
' Iterate through the tables in the DataSet ds.
Dim n As Integer
For n = 0 To ds.Tables.Count - 1
Console.WriteLine(ds.Tables(n).TableName)
Next
The TablesCollection object can also be indexed by table name. For example, if the DataSet ds contains a table named "Categories", this code gets a reference to it:
Dim dt As DataTable = ds.Tables("Categories")
Finding Rows
The DataTable object's Rows property holds a DataRowCollection object that in turn holds the table's DataRow objects. Each DataRow object holds the data for that particular row. The following code loops through all the rows in the DataTable and displays the value of the first column (column 0) in the row:
' Iterate through the rows.
Dim row As DataRow
For Each row In dt.Rows
Console.WriteLine(row(0))
Next
This code does the same thing, using a numeric index on the RowsCollection object:
' Iterate through the rows.
Dim n As Integer
For n = 0 To dt.Rows.Count - 1
Console.WriteLine(dt.Rows(n)(0))
Next
To assist with locating specific rows within a table, the DataTable class provides a method called Select. The Select method returns an array containing all the rows in the table that match the given criteria. The syntax of the Select method is:
Public Overloads Function Select( _
ByVal filterExpression As String, _
ByVal sort As String, _
ByVal recordStates As System.Data.DataViewRowState _
) As System.Data.DataRow( )
The parameters of the Select method are:
filterExpression
This parameter gives the criteria for selecting rows. It is a string that is in the same format as the WHERE clause in an SQL statement.
sort
This parameter specifies how the returned rows are to be sorted. It is a string that is in the same format as the ORDER BY clause in an SQL statement.
recordStates
This parameter specifies the versions of the records that are to be retrieved. Record versions are discussed in the later section "Changing, Adding, and Deleting Rows." The value passed in this parameter must be one of the values given by the System.Data.DataViewRowState enumeration. Its values are:
CurrentRows
Returns the current version of each row, regardless of whether it is unchanged, new, or modified.
Deleted
Returns only rows that have been deleted.
ModifiedCurrent
Returns only rows that have been modified. The values in the returned rows are the current values of the rows.
ModifiedOriginal
Returns only rows that have been modified. The values in the returned rows are the original values of the rows.
New
Returns only new rows.
None
Returns no rows.
OriginalRows
Returns only rows that were in the table prior to any modifications. The values in the returned rows are the original values.
Unchanged
Returns only unchanged rows.
These values can be combined using the And operator to achieve combined results. For example, to retrieve both modified and new rows, pass this value:
DataViewRowState.ModifiedCurrent And DataViewRowState.New
The return value of the Select method is an array of DataRow objects.
The Select method is overloaded. It has a two-parameter version that is the same as the full version, except that it does not take a recordStates parameter:
Public Overloads Function Select( _
ByVal filterExpression As String, _
ByVal sort As String _
) As System.Data.DataRow( )
Calling this version of the Select method is the same as calling the full version with a recordStates value of DataViewRowState.CurrentRows.
Similarly, there is a one-parameter version that takes only a filterExpression:
Public Overloads Function Select( _
ByVal filterExpression As String _
) As System.Data.DataRow( )
This is the same as calling the three-parameter version with sort equal to "" (the empty string) and recordStates equal to DataViewRowState.CurrentRows.
Lastly, there is the parameterless version of Select:
Public Overloads Function Select( ) As System.Data.DataRow( )
This is the same as calling the three-parameter version with filterExpression and sort equal to "" (the empty string) and recordStates equal to DataViewRowState.CurrentRows.
As an example of using the Select method, this line of code returns all rows whose Country column contains the value "Mexico":
Dim rows( ) As DataRow = dt.Select("Country = 'Mexico'")
Because the sort and recordStates parameters were not specified, they default to "" (the empty string) and DataViewRowState.CurrentRows, respectively.
The Select method versus the SQL SELECT statement
If an application is communicating with a database over a fast, persistent connection, it is more efficient to issue SQL SELECT statements that load the DataSet with only the desired records, rather than to load the DataSet with a large amount of data and then pare it down with the DataTable's Select method. The Select method is useful for distributed applications that might not have a fast connection to the database. Such an application might load a large amount of data from the database into a DataSet object, then use several calls to the DataTable's Select method to locally view and process the data in a variety of ways. This is more efficient in this case because the data is moved across the slow connection only once, rather than once for each query.

Finding Column Values
The DataRow class has an Item property that provides access to the value in each column of a row. For example, this code iterates through all the columns of a row, displaying the value from each column (assume that row holds a reference to a DataRow object):
' Iterate through the column values.
Dim n As Integer
For n = 0 To row.Table.Columns.Count - 1
Console.WriteLine(row(n))
Next
Note the expression used to find the number of columns: row.Table.Columns.Count. The DataRow object's Table property holds a reference to the DataTable object of which the row is a part. As will be discussed shortly, the Table object's Columns property maintains a collection of column definitions for the table. The Count property of this collection gives the number of columns in the table and therefore in each row.
The DataRow object's Item property is overloaded to allow a specific column value to be accessed by column name. The following code assumes that the DataRow row contains a column named "Description". The code displays the value of this column in this row:
Console.WriteLine(row("Description"))
Finding Column Definitions
The DataTable object's Columns property holds a ColumnsCollection object that in turn holds the definitions for the columns in the table. The following code iterates through the columns in the table and displays their names:
' Iterate through the columns.
Dim column As DataColumn
For Each column In dt.Columns
Console.WriteLine(column.ColumnName)
Next
This code does the same thing, using a numeric index on the ColumnsCollection object:
' Iterate through the columns.
Dim n As Integer
For n = 0 To dt.Columns.Count - 1
Console.WriteLine(dt.Columns(n).ColumnName)
Next
The ColumnsCollection object can also be indexed by column name. For example, if DataTable dt contains a column named "Description", this code gets a reference to the associated DataColumn object:
Dim column As DataColumn = dt.Columns("Description")
Changing, Adding, and Deleting Rows
To change data in a DataSet, first navigate to a row of interest and then assign new values to one or more of its columns. For example, the following line of code assumes that row is a DataRow object that contains a column named "Description". The code sets the value of the column in this row to be "Milk and cheese":
row("Description") = "Milk and cheese"
Adding a new row to a table in a DataSet is a three-step process:
Use the DataTable class's NewRow method to create a new DataRow. The method takes no parameters.
Set the values of the columns in the row.
Add the new row to the table.
For example, assuming that dt is a DataTable object, and that the table has columns named "CategoryName" and "Description", this code adds a new row to the table:
' Add a row.
Dim row As DataRow = dt.NewRow( )
row("CategoryName") = "Software"
row("Description") = "Fine code and binaries"
dt.Rows.Add(row)
The DataRow object referenced by row in this code can be indexed by the names "CategoryName" and "Description" because the DataRow object was created by the DataTable object's NewRow method and so has the same schema as the table. Note that the NewRow method does not add the row to the table. Adding the new row to the table must be done explicitly by calling the DataRowCollection class's Add method through the DataTable class's Rows property.
Deleting a row from a table is a one-liner. Assuming that row is a reference to a DataRow, this line deletes the row from its table:
row.Delete( )
When changes are made to a row, the DataRow object keeps track of more than just the new column values. It also keeps track of the row's original column values and the fact that the row has been changed. The Item property of the DataRow object is overloaded to allow you to specify the desired version of the data that you wish to retrieve. The syntax of this overload is:
Public Overloads ReadOnly Property Item( _
ByVal columnName As String, _
ByVal version As System.Data.DataRowVersion _
) As Object
The parameters are:
columnName
The name of the column whose value is to be retrieved.
version
The version of the data to retrieve. This value must be a member of the System.Data.DataRowVersion enumeration. Its values are:
Current
Retrieve the current (changed) version.
Default
Retrieve the current version if the data has been changed, the original version if not.
Original
Retrieve the original (unchanged) version.
Proposed
Retrieve the proposed change. Proposed changes are changes that are made after a call to a DataRow object's BeginEdit method but before a call to its EndEdit or CancelEdit methods.
For example, after making some changes in DataRow row, the following line displays the original version of the row's Description column:
Console.WriteLine(row("Description", DataRowVersion.Original))
The current value of the row would be displayed using any of the following lines:
Console.WriteLine(row("Description", DataRowVersion.Current))
Console.WriteLine(row("Description", DataRowVersion.Default))
Console.WriteLine(row("Description"))
Calling the DataSet object's AcceptChanges method commits outstanding changes. Calling the DataSet object's RejectChanges method rolls records back to their original versions.
TIP: The code shown in this section affects only the DataSet object, not the data source. To propagate these changes, additions, and deletions back to the data source, use the Update method of the SqlDataAdapter class, as described in the next section, "Writing Updates Back to the Data Source."
If there are relations defined between the DataTables in the DataSet, it may be necessary to call the DataRow object's BeginEdit method before making changes.

Writing Updates Back to the Data Source
Because DataSets are always disconnected from their data sources, making changes in a DataSet never has any effect on the data source. To propagate changes, additions, and deletions back to a data source, call the SqlDataAdapter class's Update method, passing the DataSet and the name of the table that is to be updated. For example, the following call to Update writes changes from the DataTable named Categories back to the SQL Server table of the same name:
da.Update(ds, "Categories")
Before using the Update method, however, you should understand how an SqlDataAdapter object performs updates. To change, add, or delete records, an SqlDataAdapter object must send SQL UPDATE, INSERT, or DELETE statements, respectively, to SQL Server. The forms of these statements either can be inferred from the SELECT statement that was provided to the SqlDataAdapter object or can be explicitly provided to the SqlDataAdapter object.
Example 8-2 shows an example of allowing an SqlDataAdapter object to infer the SQL UPDATE, INSERT, and DELETE statements required for applying updates to a database.
Example 8-2: Allowing an SqlDataAdapter object to infer SQL UPDATE, INSERT, and DELETE statements from a SELECT statement
' Open a database connection.
Dim strConnection As String = _
"Data Source=localhost;Initial Catalog=Northwind;" _
& "Integrated Security=True"
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Create a data adapter object and set its SELECT command.
Dim strSelect As String = _
"SELECT * FROM Categories"
Dim da As SqlDataAdapter = New SqlDataAdapter(strSelect, cn)
' Set the data adapter object's UPDATE, INSERT, and DELETE
' commands. Use the SqlCommandBuilder class's ability to auto-
' generate these commands from the SELECT command.
Dim autogen As New SqlCommandBuilder(da)
' Load a data set.
Dim ds As DataSet = New DataSet( )
da.Fill(ds, "Categories")
' Get a reference to the "Categories" DataTable.
Dim dt As DataTable = ds.Tables("Categories")
' Modify one of the records.
Dim row As DataRow = dt.Select("CategoryName = 'Dairy Products'")(0)
row("Description") = "Milk and stuff"
' Add a record.
row = dt.NewRow( )
row("CategoryName") = "Software"
row("Description") = "Fine code and binaries"
dt.Rows.Add(row)
' Delete a record.
row = dt.Select("CategoryName = 'MyCategory'")(0)
row.Delete( )
' Update the database.
da.Update(ds, "Categories")
' Close the database connection.
cn.Close( )
Note the following in Example 8-2:
A SqlDataAdapter object is constructed with an argument of "SELECT * FROM Categories". This initializes the value of the SqlDataAdapter object's SelectCommand property.
A SqlCommandBuilder object is constructed with the SqlDataAdapter object passed as an argument to its constructor. This step hooks the SqlDataAdapter object to the SqlCommandBuilder object so that later, when the SqlDataAdapter object's Update method is called, the SqlDataAdapter object can obtain SQL UPDATE, INSERT, and DELETE commands from the SqlCommandBuilder object.
The SqlDataAdapter object is used to fill a DataSet object. This results in the DataSet object containing a DataTable object, named "Categories", that contains all the rows from the Northwind database's Categories table.
One record each in the table is modified, added, or deleted.
The SqlDataAdapter object's Update method is called to propagate the changes back to the database.
Step 5 forces the SqlCommandBuilder object to generate SQL statements for performing the database update, insert, and delete operations.When the Update method is called, the SqlDataAdapter object notes that no values have been set for its UpdateCommand, InsertCommand, and DeleteCommand prperties, and therefore queries the SqlCommandBuilder object for these commands. If any of these properties had been set on the SqlDataAdapter object, those values would have been used instead.
The SqlCommandBuildObject can be examined to see what commands were created. To see the commands that are generated in Example 8-2, add the following lines anywhere after the declaration and assignment of the autogen variable:
Console.WriteLine("UpdateCommand: " & autogen.GetUpdateCommand.CommandText)
Console.WriteLine("InsertCommand: " & autogen.GetInsertCommand.CommandText)
Console.WriteLine("DeleteCommand: " & autogen.GetDeleteCommand.CommandText)
The auto-generated UPDATE command contains the following text (note that line breaks have been added for clarity in the book):
UPDATE Categories
SET CategoryName = @p1 , Description = @p2 , Picture = @p3
WHERE (
(CategoryID = @p4)
AND
((CategoryName IS NULL AND @p5 IS NULL) OR (CategoryName = @p6)) )
Similarly, the INSERT command is:
INSERT INTO Categories( CategoryName , Description , Picture )
VALUES ( @p1 , @p2 , @p3)
And the DELETE command is:
DELETE FROM Categories
WHERE (
(CategoryID = @p1)
AND
((CategoryName IS NULL AND @p2 IS NULL) OR (CategoryName = @p3)) )
Note the use of formal parameters (@p0, @p1, etc.) in each of these statements. For each row that is to be changed, added, or deleted, the parameters are replaced with values from the row, and the resulting SQL statement is issued to the database. The choice of which value from the row to use for which parameter is controlled by the SqlCommand object's Parameters property. This property contains an SqlParameterCollection object that in turn contains one SqlParameter object for each formal parameter. The SqlParameter object's ParameterName property matches the name of the formal parameter (including the "@"), the SourceColumn property contains the name of the column from which the value is to come, and the SourceVersion property specifies the version of the value that is to be used. Row versions were discussed in the previous section, "Changing, Adding, and Deleting Rows."
If desired, a DataSet object's UpdateCommand, InsertCommand, and DeleteCommand properties can be set directly. Example 8-3 sets the value of UpdateCommand and then performs an update using this command.
Example 8-3: Setting a DataSet object's UpdateCommand property
' Open a database connection.
Dim strConnection As String = _
"Data Source=localhost;Initial Catalog=Northwind;" _
& "Integrated Security=True"
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Set up a data adapter object.
Dim da As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Categories", cn)
' Create an UPDATE command.
'
' This is the command text.
' Note the parameter names: @Description and @CategoryID.
Dim strUpdateCommand As String = _
"UPDATE Categories" _
& " SET Description = @Description" _
& " WHERE CategoryID = @CategoryID"
'
' Create a SqlCommand object and assign it to the UpdateCommand property.
da.UpdateCommand = New SqlCommand(strUpdateCommand, cn)
'
' Set up parameters in the SqlCommand object.
Dim param As SqlParameter
'
' @CategoryID
param = da.UpdateCommand.Parameters.Add( _
New SqlParameter("@CategoryID", SqlDbType.Int))
param.SourceColumn = "CategoryID"
param.SourceVersion = DataRowVersion.Original
'
' @Description
param = da.UpdateCommand.Parameters.Add( _
New SqlParameter("@Description", SqlDbType.NChar, 16))
param.SourceColumn = "Description"
param.SourceVersion = DataRowVersion.Current
' Load a data set.
Dim ds As DataSet = New DataSet( )
da.Fill(ds, "Categories")
' Get the table.
Dim dt As DataTable = ds.Tables("Categories")
' Get a row.
Dim row As DataRow = dt.Select("CategoryName = 'Dairy Products'")(0)
' Change the value in the Description column.
row("Description") = "Milk and stuff"
' Perform the update.
da.Update(ds, "Categories")
' Close the database connection.
cn.Close( )

Real Time Site Analytics

Hi friends,
Lots of you asked about how to make real time site analytics,
Sorry I have no idea about that on ASP.Net but can help you with PHP !

The code for you !

Get page hits and store it into a text file, you can then show or hide analytics


$file="counter.txt";
// Reading file if exist
// Delet file to reset counter
$cpt = 1;
if(file_exists($file)) {
$inF = fopen($file,"r");
$cpt = intval(trim(fgets($inF, 4096))) + 1;
fclose($inF);
}
// Saving hits
$inF = fopen($file,"w");
fputs($inF,$cpt."\n");
fclose($inF);
?>

Add this to show hits on your site

And online visitors ?

Place it wherever you like !


$Fnm = "online.txt";

$IP=$REMOTE_ADDR;
$date0 = time()/60;
$vie = 5;

if (file_exists($Fnm)) {
$inF = fopen($Fnm,"r");
while (!feof($inF)) {
$ligne=fgets($inF, 4096);
$temp = explode("",$ligne);
if($temp[0]!=$IP) {
if($date0-intVal($temp[1])<=$vie) { $online++; $result .= $ligne . "\n"; } } } fclose($inF); } $result .= $IP . "" . $date0 . "\n"; $online++; // Et on sauve $inF = fopen($Fnm,"w"); fputs($inF,$result); fclose($inF); ?>

and then and online visitors will be showen on your sites !

Hope this interests lot of you game coders ;)

I forget that lots of you are lazy so I'll suggest this site (also if your server doesn't support PHP) : www.feedjit.com
I use both PHP and feedjit on www.barcodemaker.uni.cc
Hope you like it.
If you need pro and high startics why not try Google !
www.google.com/analytics