Archive for the ‘Visual Basic’ Category.
February 17, 2011, 1:37 pm
A co-worker found this nice little nugget in one of our sports web site applications:
Dim isAssHeadCoach As Boolean = Session("IsAssHeadCoach")
I hope it is meant to check for an assistant or associate head coach.
November 3, 2010, 9:52 am
Have you ever had a situation where all of those nested try/catch blocks just get in your way when trying to chase down a problem? I just hate that.
Luckily, in Visual Studio 2008 (and other versions, I am sure), there is a handy dandy way to disable all of the try/catch blocks when you run the application in debug mode from the IDE. Just go to the Debug menu, select Exceptions, click the box under the Thrown column for Common Language Runtime Exceptions (or others if that is what you are looking for), and click OK. Now when the code has a problem, you see it right away instead of trying to work backwards through nested try/catch blocks in different classes and modules.
Just don’t forget to put it back to the way it was when you are done. I am not a huge fan of try/catch blocks, but their normal use definitely has its place.
October 27, 2010, 12:47 pm
This VB code was brought to my attention. It is meant to look at a string variable (prefixText) and decide if the string is numeric or not, and return a data set (ds) by using a different method based on the result of the numeric test. (As always, this code is in a heavily used production environment.)
If Left(prefixText, 1) = "0" Or Left(prefixText, 1) = "1" Or Left(prefixText, 1) = "2" Or Left(prefixText, 1) = "3" Or Left(prefixText, 1) = "4" Or Left(prefixText, 1) = "5" Or Left(prefixText, 1) = "6" Or Left(prefixText, 1) = "8" Or Left(prefixText, 1) = "9" Then
ds = New Users(_ConnStr).getUsersListByNumber(prefixText)
Else
ds = New Users(_ConnStr).getUsersListByLastName(prefixText)
End If
I have some great ideas on how to improve this code. The first thing I would have done was to use OrElse instead of Or, it would speed things up tremendously. And I would also have added in the test for the “7″ character.
June 5, 2010, 6:48 pm
A co-w0rker and I attended the Central Ohio Day of .NET on June 5, 2010. There was quite a bit of good content at the conference, which is a real tribute to the organizers, volunteers, and presenters.
The highlights of my day were sitting in on Matt Casto’s regular expressions talk, Phil Japikse’s M-V-VM primer, discussing the etymology of the MongoDB project with Sam Corder (I still say it was named such after the character in Blazing Saddles), Michael Eaton’s talk on WPF, and Parag Joshi’s demonstration of XNA/Windows Phone 7 game development.
March 16, 2010, 8:02 pm
In order to send stuff to the printer in VB.NET, it is not quite as simple as dealing with the Printer object as in VB6. There are a couple of extra steps involved. Here is what I found, along with some helper methods that you might find useful.
On the form you want to print from, pull up the Toolbox and add a PrintDocument, a PrintDialog, and a Button, set the Document property of the PrintDialog to point to the PrintDocument you just created, and in the button’s Click event, insert the following code:
Private Sub butPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butPrint.Click
If PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDocument1.DefaultPageSettings.Landscape = True
PrintDocument1.Print()
End If
End Sub
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
PrintTestPage(e.Graphics, PrintDocument1)
End Sub
The Print method call in the button click event then fires the PrintDocument PrintPage event. Notice that I have set the default page settings to landscape. Don’t forget to wire the PrintDialog Document property to your PrintDocument, otherwise if you change the printer to print to in the print dialog, the document will still go to the default printer.
The PrintTestPage method is just something simple that I put together to make sure that the coordinates and justifications are all working fine. Here is that code:
Sub PrintTestPage(ByVal g As System.Drawing.Graphics, ByVal doc As PrintDocument)
Dim x, y As Integer
For x = 0 To 100 Step 10
For y = 0 To 100 Step 10
PrintAtLocationWithColor(g, doc, x.ToString + ", " + y.ToString, x, y, _
If(x = 0, "L", If(x = 100, "R", "C")), If(y = 0, "T", If(y = 100, "B", "C")), _
"Arial", 8, True, Brushes.Red)
Next
Next
PrintRectangle(g, doc, 0, 0, 100, 100)
PrintRectangle(g, doc, 10, 10, 80, 80)
PrintRectangle(g, doc, 20, 20, 60, 60)
PrintRectangle(g, doc, 30, 30, 40, 40)
PrintRectangle(g, doc, 40, 40, 20, 20)
End Sub
The two methods called here, PrintAtLocationWithColor and PrintRectangle, are shown here:
Sub PrintAtLocationWithColor(ByVal pg As Graphics, ByVal pd As PrintDocument, ByVal s As String, _
ByVal xPosition As Single, ByVal yPosition As Single, _
ByVal justification As String, ByVal verticalJustification As String, _
ByVal fontFace As String, ByVal fontSize As Single, _
ByVal fontBold As Boolean, ByVal theColor As Brush)
Dim w, h As Single
Dim x, y As Single
Dim f As Font
Dim sty As FontStyle
sty = FontStyle.Regular
If fontBold Then sty = sty + FontStyle.Bold
If fontSize < 1 Then fontSize = 8.0
f = New Font(fontFace, fontSize, sty)
If pd.DefaultPageSettings.Landscape Then
x = xPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Height)
y = yPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Width)
Else
x = xPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Width)
y = yPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Height)
End If
w = pg.MeasureString(s, f).Width
h = pg.MeasureString(s, f).Height
If Left(UCase(justification), 1) = "C" Then
x = x - w / 2
End If
If Left(UCase(justification), 1) = "R" Then
x = x - w
End If
If Left(UCase(verticalJustification), 1) = "C" Then
y = y - h / 2
End If
If Left(UCase(verticalJustification), 1) = "B" Then
y = y - h
End If
pg.DrawString(s, f, theColor, x, y)
End Sub
Sub PrintRectangle(ByVal pg As Graphics, ByVal pd As PrintDocument, ByVal xPosition As Single, ByVal yPosition As Single, _
ByVal width As Single, ByVal height As Single)
Dim w, h As Single
Dim x, y As Single
If pd.DefaultPageSettings.Landscape Then
x = xPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Height)
y = yPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Width)
w = width / 100 * (pd.DefaultPageSettings.PrintableArea.Height)
h = height / 100 * (pd.DefaultPageSettings.PrintableArea.Width)
Else
x = xPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Width)
y = yPosition / 100 * (pd.DefaultPageSettings.PrintableArea.Height)
w = width / 100 * (pd.DefaultPageSettings.PrintableArea.Width)
h = height / 100 * (pd.DefaultPageSettings.PrintableArea.Height)
End If
pg.DrawRectangle(Pens.Black, x, y, w, h)
End Sub
All of the positioning and size parameters of these methods are percentages across and down the page, which I find much easier to deal with than absolute or printer specific positioning. This makes it dead simple to scale the reports to any page size I want to use.
February 23, 2010, 10:43 pm
In converting some legacy VB6 code to VB.NET, I noticed that there was a lot of use of the Format function in the code to convert numbers to strings. This makes sense as Format was pretty much the only game in town in VB6.
However, in .NET, they introduced a handy-dandy .ToString() method that, on the surface, seems to do much the same thing as the Format function. I have been able to use them pretty much interchangeably with the desired results coming out every time.
I started to wonder which way was faster. Since I am a big proponent of empirical knowledge instead of just trying to get the theoretical story behind the two ways to do this, I rolled together this quick VB.NET console application:
Imports System.Text
Module Module1
Sub Main()
Dim i As Integer
Dim r As Random = New Random()
Dim t As Double
System.Console.WriteLine("10,000,000 Formats")
Dim sb1 As New stringbuilder
t = Timer
For i = 1 To 10000000
sb1.Append(Format(r.NextDouble * 100.0, "###0.00 "))
Next
System.Console.WriteLine("Seconds elapsed: " + (Timer - t).ToString("#######0.00"))
System.Console.WriteLine("Length of string builder: " + sb1.Length.ToString())
System.Console.WriteLine()
System.Console.WriteLine("10,000,000 ToStrings")
Dim sb2 As New StringBuilder
t = Timer
For i = 1 To 10000000
sb2.Append((r.NextDouble * 100.0).ToString("###0.00 "))
Next
System.Console.WriteLine("Seconds elapsed: " + (Timer - t).ToString("#######0.00"))
System.Console.WriteLine("Length of string builder: " + sb2.Length.ToString())
System.Console.WriteLine()
System.Console.WriteLine("Press any key to end the program ")
System.Console.ReadKey()
End Sub
End Module
And here are the results:

As you can see, the ToString method is about 15% faster when doing 10 million calls with random numbers.
Oh, and by the way, Happy Pancake Day.
January 27, 2010, 1:56 pm
In converting my VB6 code over to VB.NET, I was looking for an easy way to take the different between two DateTime items and display in hours and minutes. The TimeSpan gives a nice structure to dive into the difference and see exactly the interval, but I was hoping to find a way to output this in the same way that you can use the ToShortTimeString method of DateTime.
As it turns out, I found a posting by Jay Barlow that mentions converting the time different to a date time, and then using a custom format string to do the work so that I wouldn’t have to. Here is my new VB.NET code, where rec is a class that includes the start and end date and duration is a string that holds the information to be displayed:
If rec.endDate IsNot Nothing Then
Dim ts As TimeSpan = CDate(rec.endDate).Subtract(rec.startDate)
Dim dt As DateTime = DateTime.MinValue.Add(ts)
duration = "Event duration: " + dt.ToString("H:mm")
End If
Oh, and one more thing. Am I the only one in the world that thinks that iPad is the worst product name in history? Sure, it is so close to iPod so as to create brand recognition and draw comparisons, but I would just wonder what kind of names were shot down, and if any of them did not begin with the letter i.
By the way, Happy (Belated) Australia Day.
January 8, 2010, 10:18 pm
The few dozen remaining WinForms developers left on this planet may have noticed that, for some reason, a group box with radio buttons in it as designed in the Visual Studio 2008 environment will have the first radio button of the first group box automatically selected when the form comes up, even though all of the radio buttons have their Checked property set to false in the design environment. It never used to do this in VB6, as when you ran the application, the group of radio buttons would have no members selected.
The problem manifests itself when you are trying to perform additional tasks in the CheckedChanged event of the radio buttons when the user selects one of the radio buttons, since the first radio button is being automatically selected.
I asked this question on Stack Overflow, and got a couple of replies. The one that I finally used to solve the problem was to set the Checked property of the radio buttons to false in the form’s Shown event, which I had never used before. By doing this, the first radio button was no longer automatically showing up checked.
One other thing that I had to do in addition was to cast the sender into a RadioButton and look at the Checked property of the clicked radio button in the CheckedChanged event, as that event is fired for radio buttons both being turned on and also turned off.
Oh, and happy National English Toffee Day!
December 28, 2009, 7:57 pm
One of the things that I really liked (and used quite a bit) in the VB6 IDE was the ability to use the design surface to create a form with a bunch of controls with the same name as a control array. You would create the controls on the design page, give it the same name as another control, and the Index property would automatically be incremented. This would then let me use a loop to manipulate and examine these controls.
This functionality is missing in VB.NET, as I discovered when I tried to do my first .NET Compact Framework application way back when Visual Studio 2003 was shiny and new, and has continued to be missing from the feature set in VS2005 and VS2008.
Microsoft is not much help on this front. Their solution is to create the forms in code, as described in this article:
Not so helpful link
But I like using the design surface to create forms. A co-worker suggested we try to do a test in C# and tamper with the designer.cs file to create an array of controls in there, which worked OK. The big problems there were that the controls showed up on the design surface, but they could not be clicked and modified. Also, when we added a control to the form and saved it, all of the customizations we made to the designer file disappeared. (Oops.)
So instead, what I am now doing is creating my forms in the designer as before, with each control of the set having a different name with a number after it (such as cboName0, cboName1, etc.), referring to the index of the control in the array. At the top of the form’s class I have the arrays defined:
Dim cboName(10) as ComboBox
Dim lblNumber(10) as Label
Then, in the form load event, I am calling this subroutine:
Sub SetUpControlArrays()
For Each cb In Me.Controls.OfType(Of ComboBox)()
If cb.Name.Contains("cboName") Then
cboName(CInt(cb.Name.Replace("cboName", ""))) = cb
End If
Next
For Each lbl In Me.Controls.OfType(Of Label)()
If lbl.Name.Contains("lblNumber") Then
lblNumber(CInt(lbl.Name.Replace("lblNumber", ""))) = lbl
End If
Next
End Sub
Now I have the ability to address the controls in the same way that I used to do in VB6. The fact that I lived with this missing feature for about 6 years and just now figuring out a decent way around the problem pretty much guarantees that VS2010 will put the control arrays back in.
EDIT: At the request of a Strong Bad fan who shall remain nameless, I changed up the code above to be a bit more friendly. The previous code only extracted the rightmost 1 character from the name of the control on the design surface, which would not work if you had a control name such as cboName10.
November 24, 2009, 8:37 pm
I wanted to have my .NET based Palm OS conduit DLL be able to report the version of the HotSync Manager that the user has installed on their computer. Initially, I was going to try to read the version of the executable, but then I would first have to find the path to the executable, and hope that this would be a reliable enough method.
As it turns out, after I did a little investigation, I found out that it is not necessary to try and figure out where the HotSync Manager is installed by reading the appropriate registry key to get the HotSync Manager location and then trying to get the version number of the assembly at that path. Because the user is in the conduit code, the HotSync Manager (HOTSYNC.EXE) is already in the running processes list. It just so happens that in the System.Diagnostics namespace there is a handy dandy method that gets all of the running processes, along with a goodly amount of information about each process, including the version number.
So here is my VB.NET code that searches for the HotSync Manager process and returns the version number as a string.
Function GetHotSyncVersion() As String
Dim versionString As String = "Unknown"
Dim procList As List(Of Process) = Process.GetProcesses().ToList
Dim hotSyncProcess As Process = Nothing
For Each p In procList
If p.ProcessName.ToUpper = "HOTSYNC" Then
hotSyncProcess = p
End If
Next
If hotSyncProcess IsNot Nothing Then
versionString = hotSyncProcess.MainModule.FileVersionInfo.FileVersion
End If
Return versionString
End Function
Sorry I missed the CIDUG meeting tonight.