vb.net Tips & Tricks

Need a snippet of vb.net code to perform a particular programming task? Most coders (like the author of this Blog) don't keep every coding trick they've learned stored in their head - they figure out a solution once and refer back to previous programs when they need to use it again. Check here for (hopefully) useful chunks of code to reduce your programming efforts.

Is vb.net too limited for you?
Need a scripting environment that won't hold you back?

If so, move up to Windows PowerShell and check out some useful tips here: http://poshtips.com

Ping A System from vb.Net

Network ping is a quick way to check to see if a remote system is online (assuming the remote system does not have ping response blocked). There are basically two steps involved in this example: First, make sure that we are able to resolve the hostname to an IP address; if we can't do that, there's no point in attempting to ping it. Once we are able to resolve the hostname's IP address, we can move on to second step which is the actual ping operation. This is relatively simple in .Net Framework (2.0) using vb.Net.

Environment: VB.NET, Visual Studio 2005, .NET 2.0

STEP ONE:
Create a Windows Form application and place the following three controls on it.

(1) A TextBox control
- change the name to "txtHostName"
(2) A Button conrol
- change the name to "btnPingHost"
(3) A second TextBox Control
- change the name to "txtPingResult"
- set the "Multiline" property to "True"
- make the control big enough to show the ping output,
approximately 400(width) by 200(height)


STEP TWO:
Paste the following code into the "codebehind" for this form.



Imports System.Net.NetworkInformation
Imports system.net
Imports System.Threading
Imports System.Text

Public Class Form1

Private Sub btnPingHost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPingHost.Click
If HostIsResolvable(txtHostName.Text) Then
PingSystem(txtHostName.Text)
End If
End Sub

Sub PingSystem(ByVal HostName As String)
'Ping the system and display results to the txtPingResult control

'Clear any previous ping results
txtPingResult.Text = ""

Dim pingsender As New Ping
Dim options As New PingOptions

'Modify the default fragmentation behavior
options.DontFragment = True

'Create a buffer of 32 bytes of data to be transmitted.
Dim data As String = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
Dim buffer As Byte() = Encoding.ASCII.GetBytes(data)
Dim timeout As Integer = 120

Try
'Attempt ping
Dim reply As PingReply = pingsender.Send(HostName, timeout, buffer, options)
'Ping the target system 4 times to check for consistent results
For i As Integer = 1 To 4
If (reply.Status = IPStatus.Success) Then
txtPingResult.Text += String.Format("Reply from:{1}: Bytes={2} time{3} TTL={4}{0}", _
vbCrLf, reply.Address.ToString, reply.Buffer.Length, GetMs(reply.RoundtripTime), reply.Options.Ttl)
Else
txtPingResult.Text += String.Format("Ping Failed:{1}{0}", vbCrLf, reply.Status.ToString)
End If
Me.Refresh()
'Pause for 1 second before pinging again
System.Threading.Thread.Sleep(1000)
Next
Catch ex As Exception
txtPingResult.Text += String.Format("Ping Failed on host:{1}{0}Error:{2}{0}Detail:{3}{0}", vbCrLf, HostName, ex.Message, ex.InnerException)
End Try
txtPingResult.Text += "-- done --"
End Sub

Function HostIsResolvable(ByVal HostName As String) As Boolean
'Attempt to lookup hostname in DNS
'If successful, simply return TRUE
'If not successful, Return FALSE and display message to txPingResult control
Try
'performs the DNS lookup
Dim HostEntry As IPHostEntry = Dns.GetHostEntry(HostName)
Dim IpList As IPAddress() = HostEntry.AddressList
HostIsResolvable = True
Catch ex As System.Exception
txtPingResult.Text = ex.Message
HostIsResolvable = False
End Try

End Function

Function GetMs(ByVal ResponseTime As Integer) As String
'accept and integer value and return a friendly string
' reflecting number of milliseconds
If ResponseTime = 0 Then
Return "<1ms">
Else
Return String.Format("={0}ms", ResponseTime.ToString)
End If
End Function


Digital Clock/Calendar

I found that the built-in clock on my Windows Mobile phone was a bit small and difficult to read with my tired old eyes, so I whipped up this quick application to remedy the situation. It will display the current time, date, and day of week. You can use this on a Windows Mobile application or a regular Windows form application. To make it all work, you will need three labels and a timer control added to your form.

Drag three label controls onto your form and name them as follows:
lblClock
lblDate
lblDay

Next, drag a timer control to the form (I just kept the default "Timer1" name)
Timer1

Now you just need update the label size, font, color, etc to your liking and you're ready to insert the code.

Here's the whole program, start to finish. Pretty simple, but it gets the job done.

Environment: VB.NET, Visual Studio 2005, .NET 2.0




Public Class Form1

Public hr, mn, se As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
hr = 0
mn = 0
se = 0
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Dim ts As Date = Now
lblClock.Text = String.Format("{0:D2}:{1:D2}:{2:D2} {3}", ts.Hour Mod 12, ts.Minute, ts.Second, GetXM(ts))
lblDate.Text = String.Format("{0:D2}/{1:D2}/{2:D4}", ts.Month, ts.Day, ts.Year)
lblDay.Text = ts.DayOfWeek.ToString
End Sub

Private Function GetXM(ByVal ts As Date) As String
If ts.Hour >= 12 Then
Return "PM"
Else
Return "AM"
End If
End Function
End Class


Track Elapsed Time in VB.NET

Here's a very simple but effective solution for capturing elapsed time within a vb.net program.

The following sample assumes you are working within a Windows Form context. This is the "code behind" processing for some event that has been initiated within your form for which you want to capture Elapsed Time. A label "lblElapsedTime" has been created on the form and will be used to display the elapsed time value as the program runs.

Environment: VB.NET, Visual Studio 2005, .NET 2.0




'Two Variable declarations are needed: StartTime and ElapsedTime

dim StartTime as DateTime
dim ElapsedTime as TimeSpan

'Set the StartTime at the begin of the processing
' for which you want to capture ElapsedTime
StartTime = Now

'Begin your processing (let's assume it is some sort of looping logic)
'replace the following "For" loop with whatever
' looping construct suits your needs

For each x as integer in y

'Insert some processing here (or call to another routine)
' that will consume some time
'your code here
'Capture the Elapsed Time here as follows
ElapsedTime = Now().Subtract(StartTime)
'Now we will report the output to a Windows Form label
'display format is Hours:Minutes:Seconds
lblElapsedTime.Text = String.Format("Elapsed Time : {0:00}:{1:00}:{2:00}",_
CInt(ElapsedTime.TotalHours), _
CInt(ElapsedTime.TotalMinutes) Mod 60, _
CInt(ElapsedTime.TotalSeconds) Mod 60)
'Force the Windows Form to refresh and display the elapsed time
Me.Refresh()
Next