Custom Search

Thursday, October 11, 2007

Execute Non Query

A quick way of using sql executeNonQuery Method of sqlCommand

' ----------------------------------------

' Required Imports :
'
' System.Data
' System.Data.SqlClient
' ----------------------------------------

Dim rowCount As Integer
Dim previousConnectionState As ConnectionState
previousConnectionState = conn.State

Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
rowCount = cmd.ExecuteNonQuery()

Finally
If previousConnectionState = ConnectionState.Closed Then
conn.Close()
End If
End Try

Database Err Handling

' ----------------------------------------
' Required Imports :
'
' System.Data
' System
' ----------------------------------------

Try
' Add your data task here.
Catch concurrencyEx As DBConcurrencyException
Throw concurrencyEx
Catch constraintEx As ConstraintException
Throw constraintEx
Catch deletedRowEx As DeletedRowInaccessibleException
Throw deletedRowEx
Catch duplicateNameEx As DuplicateNameException
Throw duplicateNameEx
Catch inRowChangingEx As InRowChangingEventException
Throw inRowChangingEx
Catch invalidConstraintEx As InvalidConstraintException
Throw invalidConstraintEx
Catch invalidExpressionEx As InvalidExpressionException
Throw invalidExpressionEx
Catch missingPrimaryEx As MissingPrimaryKeyException
Throw missingPrimaryEx
Catch noNullEx As NoNullAllowedException
Throw noNullEx
Catch readOnlyEx As ReadOnlyException
Throw readOnlyEx
Catch rowNotInTableEx As RowNotInTableException
Throw rowNotInTableEx
Catch strongTypingEx As StrongTypingException
Throw strongTypingEx
Catch typedDataSetEx As TypedDataSetGeneratorException
Throw typedDataSetEx
Catch versionNotFoundEx As VersionNotFoundException
Throw versionNotFoundEx
Catch dataEx As DataException
Throw dataEx
Catch ex As Exception
Throw ex
Finally
' Dispose of any resources you used in the Try block.
End Try

Friday, October 5, 2007

Migration VS 2002 / 2003 to VS2005

Migration VS 2002 / 2003 to VS2005

Many people still confusing of migrating VS2002 / 2003 to VS2005.
Let's help people by putting your idea on migration.
Let's start with me first

Things you need to consider when you are migration from VS2002 / 2003 to VS2005
1. Third party component
Check if your third party components do support in VS 2005.
Check the support document what you need to change and what you need to have.

Ribbon Component

Ribbon Component is one of the most searching component.
Most Ribbon components supprt in VS 2005 and VS2002 / 2003. In order to run a proper
Ribbon Component you need to have MS Office 2007


Report
Report is you need to the most when you are developing application.
If you are using Crystal Report V9.xx with VS2002 / 2003. You need to upgrade it to
higher version.
Crystal Report V9 doesnt support Framework V2.
VS 2005 is using framework v2.


2. Database
You might want to change on your code. VS 2005 has a new features called ADONet Async. This a great features for speeding up your application and waiting time.
AdoNet Async is doing multiple jobs at the same time without waiting for the first task to finish.

Thursday, October 4, 2007

MS SQL Backup Script

MS SQL Backup Script


There are many ways to backup sql script. There are many post, articles talking about backup sql.

Here is one of the quick way to backup your MS SQL Database.

1. Clear Log
TO reduce rubbish on your drive. You do not need rubbish log.
2. Backup database after clear database log.

You may put this script into your scheduler. Just change a little of the script. :)

--CLEAR LOG
DBCC SHRINKDATABASE (N'IT_Medan', 0,TRUNCATEONLY)

-- BACKUP DABATABASE
BACKUP DATABASE [IT_Medan_DB] TO DISK = N'C:\Backup\IT_Medan.bk' WITH INIT , NOUNLOAD , NAME = N'IT_Medanbackup', NOSKIP , STATS = 10, NOFORMAT

Simple Console Application

Imports system
Imports microsoft.visualbasic ' For msgbox

Namespace N1
Class Ovrl
Shared Sub main()
myfunc("Mansih")
myfunc(22)
End Sub

'Accepts Integer
Overloads Shared Function myfunc(ByVal i As Integer) As String
msgbox("Overloaded Function Accepting Integer")
End Function

'Accepts String
Overloads Shared Function myfunc(ByVal s As String) As String
msgbox("Overloaded Function Accepting String")
End Function
End Class
End Namespace

This Example Demonstrated Function Overloading, It is also possible to overload a Constructor and its also one of my favourite feature.

Imports system
Imports microsoft.visualbasic ' For msgbox


Namespace N1
Class OvrConst
Shared Sub main()
Dim o As New OvrConst()
Dim x As New OvrConst("Constructor 2")
End Sub

'cosntructor 1 without parameter
Public Overloads Sub New()
msgbox("Constructor 1")
End Sub


'cosntructor 2 with a String parameter
Public Overloads Sub New(ByVal s As String)
msgbox(s)
End Sub

End Class
End Namespace

Reading XML FIle

After calling read method, you can go though the document node by node and get the data.

Source Code:
Imports System
Imports System.Xml
Module Module1

Sub Main()
' Open an XML file
Dim reader As XmlTextReader = New XmlTextReader("C:\\it_medan.xml")

While reader.Read()
Console.WriteLine(reader.Name)
End While

End Sub

End Module

Object Serialization

Option Strict Off
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Public Module SerializationSample
'Class Node to hold the Linklist Item. Must be marked as
'serializable
Public Class Node
Public Value As Integer
Public NextNode As Node = Nothing
'Constructor
Public Sub New(ByVal NewValue As Integer)
MyBase.New()
Me.Value = NewValue
End Sub
End Class
'Linked List Class. MUst be marked with
'serializable attribute
Public Class LinkedList
Private m_head As Node = Nothing
Private m_tail As Node = Nothing
'Adding to Linklist
Public Function Add(ByVal iValue As Integer) As Boolean
Dim curNode As Node = m_head
While Not (curNode Is Nothing)
If (curNode.Value = iValue) Then Return False
curNode = curNode.NextNode
End While
Dim newNode As Node = New Node(iValue)
If (m_tail Is Nothing) Then
m_tail = newNode
m_head = m_tail
Else
m_tail.NextNode = newNode
m_tail = newNode
End If
Return True
End Function
'Remove from link list
Public Function Remove(ByVal iValue As Integer) _
As Boolean
Dim prevNode As Node = Nothing
Dim curNode As Node = m_head

While Not (curNode Is Nothing)
If (curNode.Value = iValue) Then
If (prevNode Is Nothing) Then
If (m_head Is m_tail) Then
m_tail = Nothing
m_head = m_tail
Else
m_head = m_head.NextNode
End If
Else
prevNode.NextNode = curNode.NextNode
Exit While
End If
Return True
End If
prevNode = curNode
curNode = curNode.NextNode
End While
Return False
End Function
'Find a specific node in linklist
Public Function FindNode(ByVal iValue As Integer) As Node
Dim curNode As Node = m_head
While Not (curNode Is Nothing)
If curNode.Value = iValue Then Return curNode
curNode = curNode.NextNode
End While
Return Nothing
End Function
'Swap the Node position in linked list
Public Function SwapPositions(ByVal iValue1 As Integer, _
ByVal iValue2 As Integer) As Boolean
Dim curNode As Node = m_head
Dim Node1 As Node = Nothing
Dim Node2 As Node = Nothing
Dim prevNode As Node = Nothing
Dim prevNode1 As Node = Nothing
Dim prevNode2 As Node = Nothing

If iValue1 = iValue2 Then
Return False
End If

While Not (curNode Is Nothing)
If (curNode.Value = iValue1) Then
prevNode1 = prevNode
Node1 = curNode
ElseIf (curNode.Value = iValue2) Then
prevNode2 = prevNode
Node2 = curNode
End If

If (Not (Node1 Is Nothing)) And (Not (Node2 Is Nothing)) Then
Exit While
End If

prevNode = curNode
curNode = curNode.NextNode
End While

If Node1 Is Nothing Or Node2 Is Nothing Then _
Return False

If (prevNode1 Is Nothing) Then
m_head = Node2
Else
prevNode1.NextNode = Node2
End If
If (prevNode2 Is Nothing) Then
m_head = Node1
Else
prevNode2.NextNode = Node1
End If
Dim tmp As Node = Node1.NextNode
Node1.NextNode = Node2.NextNode
Node2.NextNode = tmp

Return True
End Function
'Display
Public Sub Draw()
Dim curNode As Node = m_head
Debug.Write("List: ")
While Not (curNode Is Nothing)
Debug.Write(curNode.Value & " ")
curNode = curNode.NextNode
End While
Debug.WriteLine("")
End Sub
End Class
'Serialization implementation.
Public Class Ser
ReadOnly iMinValue As Integer = 1
ReadOnly iMaxValue As Integer = 9
Public Sub Scope1()
Dim list As LinkedList = New LinkedList()
Dim i As Integer
Debug.WriteLine("Entering Scope 1")
Debug.WriteLine("Creating and filling List ..")
For i = iMinValue To iMaxValue - 1
list.Add(i)
Next
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 1\n")
End Sub
Public Sub Scope2()
Debug.WriteLine("Entering Scope 2")
Dim list As LinkedList = LoadListFromDisk()
Debug.WriteLine("Swapping Entries")
Debug.WriteLine("Swapping 1 and 2")
list.SwapPositions(1, 2)
Debug.WriteLine("Swapping 3 and 4")
list.SwapPositions(3, 4)
Debug.WriteLine("Swapping 5 and 6")
list.SwapPositions(5, 6)
Debug.WriteLine("Swapping 7 and 8")
list.SwapPositions(7, 8)
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 2\n")
End Sub
Public Sub Scope3()
Debug.WriteLine("Entering Scope 3")
Dim list As LinkedList = LoadListFromDisk()
Debug.WriteLine("Swapping Random Entries")
Dim rnd As Random = New Random()
Dim num1, num2, i As Integer
For i = 0 To 15
While (True)
num1 = rnd.Next(iMinValue, iMaxValue + 1)
num2 = rnd.Next(iMinValue, iMaxValue + 1)
If num1 <> num2 Then
Exit While
End If
End While
Debug.WriteLine("Swapping " & num1 _
& " and " & num2)
list.SwapPositions(num1, num2)
Next
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 3\n")
End Sub

Public Sub Scope4()
Debug.WriteLine("Entering Scope 4")
Dim list As LinkedList = LoadListFromDisk()
Debug.WriteLine("Removing Entries")
Debug.WriteLine("Removing 1")
list.Remove(1)
Debug.WriteLine("Removing 2")
list.Remove(2)
Debug.WriteLine("Removing 3")
list.Remove(3)
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 4\n")
End Sub
Private Function LoadListFromDisk() As LinkedList
Debug.WriteLine _
("Deserializing LinkedList from file ..")
Dim s As Stream = New FileStream("linkedlist.bin", FileMode.Open)
Dim b As BinaryFormatter = New BinaryFormatter()
'This casting requires option strict option of vb to
' be off
'While compliing the code use the
' switch /optionstrict-
Dim list As LinkedList = b.Deserialize(s)

s.Close()
list.Draw()
Return list
End Function
Private Sub SaveListToDisk(ByRef list As LinkedList)
list.Draw()



Debug.WriteLine _
("Serializing LinkedList to file ..")

Dim s As Stream = New FileStream("linkedlist.bin", FileMode.Create)



Dim b As BinaryFormatter = New BinaryFormatter()
b.Serialize(s, list)
s.Close()
End Sub

End Class
Sub Main()
Dim SerSample As Ser = New Ser()
With SerSample
.Scope1()
.Scope2()
.Scope3()
.Scope4()
End With
End Sub

End Module

Using Delegate

' Delegate Definition
Public Delegate Sub mySingleCast(ByVal value As String)
Class myEcho
Public Sub Shout(ByVal Value As String)
MsgBox(Value)
End Sub
End Class
Class proVerb
Public Sub Verb(ByVal Value As String)
MsgBox(Value)
End Sub
End Class
Private Sub btnDelegate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnDelegate.Click
' Declaration Section
Dim objMyEcho As New myEcho()
Dim objproVerb As New proVerb()
Dim dlgt As mySingleCast

' Assign the Function Pointer to delegate
dlgt = New mySingleCast(AddressOf objMyEcho.Shout)

' Call the Invoke Method of Delegate
dlgt.Invoke("Enjoy .Net Programming")

' Assign the Function Pointer of another class to delegate
dlgt = New mySingleCast(AddressOf objproVerb.Verb)

' Calling Invoke Method of Delegate
dlgt.Invoke("God is Great")

Using Threading

Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Threading


Class MyThread
Shared Sub main()
Try
'Declare a Thread and Assign it to a Methord Hi
Dim t As New thread(AddressOf hi)
'Declare Another Thread and assign it to Bye
Dim b As New thread(AddressOf bye)

'Set the priority level for each thread
t.Priority = ThreadPriority.Normal
b.Priority = ThreadPriority.Lowest

'Start the thread execution
t.start()
b.start()
Catch e As exception
msgbox(e.tostring)
End Try
End Sub

Shared Sub hi()
'Infinite Loop CTRL + C to Exit
Do While True
console.writeline("hi")
Loop
End Sub

Shared Sub bye()
'Infinite Loop CTRL + C to Exit
Do While True
console.writeline("bye")
Loop
End Sub
End Class

Saving Images into database

FieldName Type
Pic OLE Object
FileSize Text

The following code establishes a database connection and inserts a file in the "Pic" field.

Save the file as SaveImage.vb

Imports System
Imports System.IO
Imports System.Data

Public Class SaveImage
Shared Sub main()
'Delaclare a file stream object
Dim o As System.IO.FileStream
'Declare a stream reader object
Dim r As StreamReader
Dim jpgFile As String
Console.Write("Enter a Valid .JPG file path")
jpgFile = Console.ReadLine
If Dir(jpgFile) = "" Then
Console.Write("Invalid File Path")
Exit Sub
End If
'Open the file
o = New FileStream(jpgFile, FileMode.Open, FileAccess.Read, FileShare.Read)
'Read the output in a stream reader
r = New StreamReader(o)
Try
'Declare an Byte array to save the content of the file to be saved
Dim FileByteArray(o.Length - 1) As Byte
o.Read(FileByteArray, 0, o.Length)
'Open the DataBase Connection, Please map the datasource name to match the 'Database path
Dim Con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=DbImages.mdb")
Dim Sql As String = "INSERT INTO DbImages (Pic,FileSize) VALUES (?,?)"
'Declare a OleDbCommand Object
Dim CmdObj As New System.Data.OleDb.OleDbCommand(Sql, Con)
'Add the parameters
CmdObj.Parameters.Add("@Pic", System.Data.OleDb.OleDbType.Binary, o.Length).Value = FileByteArray
CmdObj.Parameters.Add("@FileSize", System.Data.OleDb.OleDbType.VarChar, 100).Value = o.Length
Con.Open()
CmdObj.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Console.Write(ex.ToString)
End Try
End Sub
End Class

Compile the file as
vbc SaveImage.vb /r:system.data.dll /r:system.dll
A file will be inserted in the Database each time we execute SaveImage.exe.

Menghitung Umur

Fungsi Menghitung Waktu


» Publisher: Mustakin Caca | Post: 2/14/2006 | Click: 588


Print Page Favorites

Function cari_umur(TanggalAwal As Date, TanggalAkhir As Date) As String
On
Error GoTo salah
Dim tahun As Long, bln As Integer, bulan As Integer, thn As Long
Dim Counter As Integer, hari As Integer

hari = Format(CDate(TanggalAwal), "d")
bln = Format(CDate(TanggalAwal), "m")
thn = Format(CDate(TanggalAwal), "yyyy")

Do Until (hari = Format(CDate(TanggalAkhir), "d")
And _
bln = Format(CDate(TanggalAkhir), "mm")
And _
thn = Format(CDate(TanggalAkhir), "yyyy"))
hari = hari + 1


If hari = Format(CDate(TanggalAwal), "d") Then
bulan = bulan + 1 'jumlah bulan
Counter = 0 'jumlah hari
If bulan = 12 Then
bulan = 0
tahun = tahun + 1 'jumlah tahun
End If
Else
Counter = Counter + 1
End If

If CDate(hari & "/" & bln & "/" & thn) = CDate(Trim(TanggalAkhir)) Then Exit Do
If bln = 1 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 2 And hari = 29 And thn Mod 4 = 0 Then
bln = bln + 1: hari = 0
ElseIf bln = 2 And hari = 28 And thn Mod 4 > 0 Then
bln = bln + 1: hari = 0
ElseIf bln = 3 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 4 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 5 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 6 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 7 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 8 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 9 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 10 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 11 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 12 And hari = 31 Then
bln = 1: thn = thn + 1: hari = 0
End If
Loop

cari_umur = Counter & " hari " & bulan & " bulan " & tahun & " tahun"
Exit Function
salah:
If Err.Number = 13 Then
MsgBox "format tanggal salah"
End If
End Function

Private Sub Command3_Click()
'Mulai tanggal - s/d tanggal
MsgBox cari_umur(CDate(Text1), CDate(Text2))
End Sub

Tuesday, October 2, 2007

Get Latest MSDN Magazine and code

Great link http://www.ftponline.com/vsm/
You will find latest MSDN magazine and MSDN code here.

Connect to website

' ----------------------------------------
' Required Imports :
'
' Microsoft.VisualBasic
' System
' ----------------------------------------

Dim baseUri As New Uri("http://www.it-medan.blogspot.com/")
Dim relativeUri As New Uri("images/index.htm?id=null")

' Compose absolute Uri using the base and the relative Uri.
Dim absoluteUri As New Uri(baseUri, relativeUri)

Dim absolute As String = absoluteUri.AbsolutePath()

Using Comparer

' ----------------------------------------
' Required Imports :
'
' System.Collections.Generic
' ----------------------------------------

Public Class IntegerComparer
Inherits Comparer(Of Integer)

Public Overrides Function Compare(ByVal param1 As Integer, ByVal param2 As Integer) As Integer
If param1 < param2 Then
' result = <0 if param1 < param2
Return -1
ElseIf param1 > param2 Then
' result = >0 if param1 > param2
Return 1
Else
' result = 0 if param1 = param2
Return 0
End If
End Function
End Class

Sunday, September 30, 2007

Retrieving environment details in VB.Net

' 1) Place a button in the form
' 2) Place a TextBox in the Form and name it as txtInfo
' 3) Set the Multi-line property of the TextBox(txtInfo) to True
' 4) Import the System.Environment namespace
' 5) Write the following code in the CommandButton click Event

Dim s As String
Dim o As System.Environment

s = "Current Directory=System.Environment.CurrentDirectory()->"
s = s & o.CurrentDirectory() & vbCrLf

s = s & "CommandLine=System.Environment.CommandLine()->"
s = s & o.CommandLine() & vbCrLf

s = s & "Environment Variable=System.Environment.GetEnvironmentVariable(variable)->"
s = s & o.GetEnvironmentVariable("PATH") & vbCrLf

s = s & "MachineName=System.Environment.MachineName->"
s = s & o.MachineName & vbCrLf

s = s & "SystemDirectory=System.Environment.SystemDirectory->"
s = s & o.SystemDirectory & vbCrLf

s = s & "UserName=System.Environment.UserName->"
s = s & o.UserName & vbCrLf

s = s & "UserDomainName=System.Environment.UserDomainName->"
s = s & o.UserDomainName & vbCrLf

s = s & "OSVersion=System.Environment.OSVersion->"
s = s & o.OSVersion.ToString & vbCrLf

txtInfo.Text = s

' The namespace System.Environment provides methods to access various information like System Name, Domain Name , Username, OSVersion etc. These methods returns a string as a parameter. Values are retrieved and stored in the local variable s. To avoid using a length qualifier System.Environment with each call, a varaible is declared of type System.Environment and the same is substituted there.

' When the button is pressed, all the above information are retrieved and posted in the Textbox txtInfo.

' Happy programming with VB.NET.

Passing by Value and by Reference in Vb.Net

Imports System
Imports Microsoft.visualbasic

Class TestRef

Sub Change(ByRef i As String)
i = "Changed"
End Sub

Sub DontChange(ByVal i As String)
i = "Some Text"
End Sub

End Class

Class PassValue

Shared Sub main()
Dim objT As New TestRef()
Dim sChange As String = "DotNetExtreme"
Dim sDontChange As String = "DotNetExtreme"

'Value of sChange will change
MsgBox("Before = " & sChange)
objT.Change(sChange)
MsgBox("After = " & sChange)

'Value of sDontChange will not change
MsgBox("Before = " & sDontChange)
objT.DontChange(sDontChange)
MsgBox("After = " & sDontChange)

End Sub
End Class

' Compile the file from the command prompt as VBC Passval.vb

Using exception handling in VB.Net

Imports System
Imports Microsoft.VisualBasic ' For MsgBox
Class MyExceptionClass
Shared Sub main()
Dim s(3) As String
Try
'Try to cause an Exception
MsgBox(s(5))

'Catch the raised Exception
Catch e As Exception
MsgBox (e.Message)

'This block will be executed in any case
Finally
MsgBox ("Finally Fired")
End Try
End Sub
End Class

' Lets see how we can have multiple Catch Statements to catch a specific type of error and act upon it.

' Remember:
' We can have multiple Catch statements but be very specific in declaring the sequence of Catch blocks because if a Catch block handling generic exception is preceding the Catch block handling the specific type of exception, the exception will be handled by the generic Catch block hence defeating the purpose.

' This example illustrates the use of multiple Catch Blocks

Imports System
Imports Microsoft.VisualBasic ' For MsgBox

Class MyExceptionClass
Shared Sub main()
Dim s(3) As String
Try
'Try to cause an Exception
MsgBox(s(5))

'This is a Specific Exception handling catch block
'Only IndexOutOfRange Exception will he caught here
Catch e As IndexOutOfRangeException
msgbox("Do something Special")

'This is a generic Exception handling Catch block
'Be sure to place it after your Sepecific Catch block
Catch e As Exception
msgbox(e.Message)

'This block will be executed in any case
Finally
msgbox("Finally Fired")
End Try
End Sub
End Class

Get IP for a host name in VB.Net

' Get the IP addresses for a given domain name

Private Function GetAllIPAddresses(ByVal domainName As String) _
As System.Collections.Specialized.StringCollection

Dim results As New System.Collections.Specialized.StringCollection
Dim hostInfo As System.Net.IPHostEntry = System.Net.Dns.GetHostByName(domainName)

For Each ip As System.Net.IPAddress In hostInfo.AddressList
results.Add(ip.ToString)
Next

Return results
End Function

Writing data from datasource to XML file

' write dataset contents to an xml file
ds.WriteXml("C:\\out.xml")

' Before that same old steps. Create a connection object, create dataadapter and call fill method of data adapter to fill a dataset.

Dim cmdString As String = "Select ContactID, FirstName, LastName from Contacts"
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\contactmanagement.mdb"
Dim myConnection As OleDbConnection = New OleDbConnection(connString)
' Open connection
myConnection.Open()
'create data adapter and dataset objects
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmdString, myConnection)
Dim ds As DataSet = New DataSet()

' fill dataset
da.Fill(ds, "Contacts")



' Source Code:

Imports System
Imports System.Data
Imports System.Data.OleDb
Module Module1
Sub Main()
'construct the command object and open a connection to the Contacts table
Dim cmdString As String = "Select ContactID, FirstName, LastName from Contacts"
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\contactmanagement.mdb"
Dim myConnection As OleDbConnection = New OleDbConnection(connString)
' Open connection
myConnection.Open()
'create data adapter and dataset objects
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmdString, myConnection)
Dim ds As DataSet = New DataSet()

' fill dataset
da.Fill(ds, "Contacts")

' write dataset contents to an xml file
ds.WriteXml("C:\\out.xml")

End Sub
End Module

Reading XML Files in VB.Net

' After calling read method, you can go though the document node by node and get the data.

' Source Code:
Imports System
Imports System.Xml
Module Module1

Sub Main()
' Open an XML file
Dim reader As XmlTextReader = New XmlTextReader("C:\\out.xml")

While reader.Read()
Console.WriteLine(reader.Name)
End While

End Sub

End Module

Getting a Database Table in VB.Net

' Listing 1: Getting a Database Schema
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim str As String = "Provider=Microsoft.jet.oledb.4.0;Data Source=c:\\northwind.mdb"
Dim conn As New OleDb.OleDbConnection()
conn.ConnectionString = str
' Open a connection
conn.Open()

'Call GetOleDbSchemaTable
Dim schemaTable As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})

' Attach data row to the grid and close the connection
DataGrid1.DataSource = schemaTable
conn.Close()

End Sub

Now if you want only database table names, you can extract the data table returned by the GetOleDbSchemaTable. The code listed in Listing 2 shows how to do so.

Listing 2. Extracting a DataTable to get only table names.
Dim str As String = "Provider=Microsoft.jet.oledb.4.0;Data Source=c:\\northwind.mdb"
Dim conn As New OleDb.OleDbConnection()
conn.ConnectionString = str
' Open a connection
conn.Open()
Dim ca As Object

'Call GetOleDbSchemaTable
Dim schemaTable As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, _New Object() {Nothing, Nothing, Nothing, "TABLE"})

Dim tableList As New DataTable("Table")
Dim rowvals(0) As Object
Dim newdc As New DataColumn("Col")
tableList.Columns.Add(newdc)
Dim rowcoll As DataRowCollection = tableList.Rows
Dim counter As Integer

For counter = 0 To schemaTable.Rows.Count - 1
Dim rd As DataRow = schemaTable.Rows(counter)
If rd("TABLE_TYPE").ToString = "TABLE" Then
rowvals(0) = rd("TABLE_NAME").ToString
rowcoll.Add(rowvals)
End If
Next

' Attach data row to the grid and close the connection
DataGrid1.DataSource = tableList
conn.Close()

How to use Delegates in VB.Net

'Author : Pramod Kumar Singh
'Purpose : To show HOW Delegates WORKS in VB7
'Applicatio : Console
'Date : 5th Jan 2001
'History :

Module Module1
'Define a Delegate
Delegate Sub CompareFunc(ByVal x As Integer, _
ByVal y As Integer, ByRef b As Boolean)
'Define a Event that will be used in AddHandler

Public Event a As CompareFunc
'Bubble Sort Algorithm which calles Delegates to perform work
Function BubbleSort(ByVal SortHigher As CompareFunc, _
ByVal IntArray() As Integer) As Integer()
Dim I, J, Value, Temp As Integer
Dim b As Boolean
For I = 0 To Ubound(IntArray)
Value = IntArray(I)
For J = I + 1 To UBound(IntArray)
Try
SortHigher.Invoke(IntArray(J), Value, b)
If b = True Then
Temp = IntArray(J)
IntArray(J) = Value
IntArray(I) = Temp
Value = Temp
End If
Catch
'Add error handling here, or just proceed
End Try
Next J
Next I
End Function

'Actual Event handling , called by Delgates
Sub Fire(ByVal x As Integer, ByVal y As Integer, ByRef b As Boolean)
If y > x Then
b = True
Else
b = False
End If
End Sub

'Entry point
Sub Main()
Dim IntArray() As Integer = {12, 1, 96, 56, 70}
Dim iArrayCount As Integer
Dim iCounter As Integer
' Add a delegate Handler
AddHandler a, (AddressOf Fire)
'Define Array for Sorting
iArrayCount = IntArray.Length
Console.WriteLine("Integer array to be sorted")
For iCounter = 0 To iArrayCount - 1
Console.WriteLine(" Value at{0} is {1} ", _
iCounter, IntArray(iCounter))
Next
'Call the method which is going to raise events
BubbleSort(Module1.aEvent, IntArray)
iArrayCount = IntArray.Length
Console.WriteLine("Integer array after Bubble Sort with Delegate")
'Display the Data to user on Console
For iCounter = 0 To iArrayCount - 1
Console.WriteLine(" Value at{0} is {1}", _
iCounter, IntArray(iCounter))
Next

End Sub
End Module

Converting Image Formats in VB.Net

' This code snippet uses System.Drawing namespace to convert the image formats. This simple but effective VB.NET and C# application accepts an image file as input and converts it to a variety of file formats viz. GIF, JPG, TIFF etc. For Simplicity this application converts an supplied Image file into .GIF format. With a simple modification this application can be extended to a full fledge "Image Converter", I would keep the options open for you all :)
' Author: Manish Mehta

Imports System
Imports System.Drawing

Class ConvertImageFormats
Shared Sub main()
Dim strFileToConvert As String

Console.Write("Image File to Convert :")
strFileToConvert = Console.ReadLine()

' Initialize the bitmap object by supplying the image file path
Dim b As New Bitmap(strFileToConvert)

'Convert the file in GIF format, also check out other
' formats like JPG, TIFF
b.Save(strFileToConvert + ".gif", System.Drawing.Imaging.ImageFormat.Gif)
Console.Write("Sucessfully Converted to " & strFileToConvert & ".gif")
End Sub
End Class

' Check out the relevent C# code to convert the image formats.
' Bitmap b;

mybmp Bitmap = new Bitmap("FileName");
b.Save("FileName", System.Drawing.Imaging.ImageFormat.Gif);

How to you use Friend and Class in VB.Net

imports system

class singleton
public shared s as singleton
public shared flag as boolean
public i as String

private sub new
' private constructor disallowing other to create object directly
end sub

friend shared function getSingletonObject as singleton
if flag = false then
s = new singleton
flag = true
return s
else
return s
end if
end function
end class

class test
shared sub main
dim o as singleton
dim y as singleton
o = singleton.getSingletonObject
o.i = "Singleton"
y = singleton.getSingletonObject
console.writeline(y.i)
end sub
end class

Get Your IP Address in VB.Net

Option Strict Off
imports system
Imports System.Net.DNS


Public Class GetIP
shared Function GetIPAddress() As String
Dim oAddr As System.Net.IPAddress
Dim sAddr As String

With system.Net.DNS.GetHostByName(system.Net.DNS.GetHostName())
oAddr = New System.Net.IPAddress(.AddressList(0).Address)
sAddr = oAddr.ToString
End With
GetIPAddress = sAddr
End Function

shared Sub main
Dim shostname As String

'Set string equal to value of System DNS Object value for GetHostName
'This should be the localhost computer name
shostname = system.Net.DNS.GetHostName
console.writeline ("Your Machine Name = " & shostname )

'Call Get IPAddress
console.writeline ("Your IP = " & GetIPAddress )
End Sub
End Class

Using File System Watcher in Vb.Net

Imports System
Imports System.IO

Class FileWatch

Shared Sub main()
Dim file_watch As New FileSystemWatcher()

' Path to monitor
file_watch.Path = "c:\"

' Uncomment to watch files
' file_watch.Target = IO.WatcherTarget.File

file_watch.IncludeSubdirectories = True

' Additional filtering
file_watch.Filter = "*.*"
file_watch.EnableRaisingEvents = true

'Add the event handler for creation of new files only
AddHandler file_watch.created, New FileSystemEventHandler(AddressOf OnFileEvent)

' file_watch.Enabled = True

' Dont Exit
console.readline()
End Sub

' Event that will be raised when a new file is created
Shared Sub OnFileEvent(ByVal source As Object, ByVal e As FileSystemEventArgs)
console.writeline("New File Created in C: ")
End Sub

End Class