Custom Search

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