Archive for the ‘Visual Basic’ Category.

2010 Central Ohio Day of .NET

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.

VB.NET Printing For Dummies

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.

.NET Kombat (Format vs. ToString)

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.

Easy way to format the time difference between two dates

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.

VB.NET radio button groups act differently than VB6 radio button groups

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!

Control arrays in VB.NET

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.

How to get the version number of a running process

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.

NetCFSvcUtil.exe error in Windows 7

I have been using Windows 7 for a while now, and always had to keep my Windows XP dev machine handy to help out with my Windows Mobile software development.

It turns out that the NetCFSvcUtil application included in the .NET CF Power Toys did not get along with Windows 7 (neither the RC or the RTM bits), as it gave a cryptic error message of “An error occurred in the tool”.

So just for giggles, I decided to see if there were any updates, and lo and behold, I found a blog post from Habib Heydarian with an updated application:

NetCFSvcUtil.exe and Windows 7

Now I can happily generate the client code on my Windows 7 machine.

Monty Hall meets Monte Carlo

In honor of CBS canceling The Guiding Light after 72 years, and replacing it with a new incantation of Let’s Make A Deal, I decided to apply a little brute force computing to The Monty Hall problem.

Here is the VB.NET code to run the simulations. I decided to only apply a few different Monty Hall behaviors and a few different player behaviors, but it should be enough to drive home the paradox.

Module Module1
 
    Sub Main()
 
        Dim i, j, ctr As Integer
        Dim doorSwitch As String = "?"
        Dim smartMonty As String = "?"
        Dim prizeDoor(3) As Boolean
        Dim rand As Random = New Random()
        Dim doorMontyOpens As Integer
        Dim doorYouOpen As Integer
        Dim carsWon As Integer = 0
 
        Console.WriteLine("The Monty Hall Problem")
        Console.Write("How many times to run the simulation? ")
        ctr = Val(Console.ReadLine())
        If ctr < 1 Then End
 
        Console.Write("Are you going to switch doors? [Y/N/M] ")
        While Not "YNM".Contains(doorSwitch)
            doorSwitch = Console.ReadKey.KeyChar.ToString.ToUpper
        End While
        Console.WriteLine()
 
        Console.Write("Does Monty know where the car is? [Y/N/M] ")
        While Not "YNM".Contains(smartMonty)
            smartMonty = Console.ReadKey.KeyChar.ToString.ToUpper
        End While
        Console.WriteLine()
 
        For i = 1 To ctr
 
            ' set up the prize doors
            For j = 1 To 3
                prizeDoor(j) = False
            Next
            prizeDoor(rand.Next(1, 4)) = True
 
            Console.Write(i.ToString() + " (")
            For j = 1 To 3
                Console.Write(If(prizeDoor(j), "$", j.ToString))
            Next
            Console.Write(") -- ")
 
            ' Monty shows you a door
            If smartMonty = "Y" Or (smartMonty = "M" And _
                                    rand.NextDouble > 0.5) Then
                doorMontyOpens = If(prizeDoor(2), 3, 2)
            Else
                doorMontyOpens = rand.Next(2, 4)
                If prizeDoor(doorMontyOpens) Then
                    carsWon = carsWon + 1
                    Console.WriteLine("Monty revealed the car!!!!!")
                    Continue For
                End If
            End If
            Console.Write("Monty reveals a goat behind door #" + _
                          doorMontyOpens.ToString + " -- ")
 
            ' pick a door to open
            If doorSwitch = "Y" Or (doorSwitch = "M" And _
                                  rand.NextDouble > 0.5) Then
                doorYouOpen = If(doorMontyOpens = 2, 3, 2)
                Console.Write("You switched to door #" + _
                              doorYouOpen.ToString + " -- ")
            Else
                doorYouOpen = 1
                Console.Write("You stayed with door #1 -- ")
            End If
 
            ' did we win?
            If prizeDoor(doorYouOpen) Then
                Console.WriteLine("You won the car!!!!!")
                carsWon = carsWon + 1
            Else
                Console.WriteLine("You won the goat.")
            End If
 
        Next
 
        Console.WriteLine(" ")
        Console.WriteLine("You won the car " + carsWon.ToString + _
                          " times out of " + ctr.ToString)
        Console.WriteLine("Winning percentage: " + (carsWon * _
                            100.0 / ctr).ToString("##0.0"))
        Console.WriteLine(" ")
        Console.WriteLine("Strike any key to end...")
        Console.ReadKey()
 
    End Sub
 
End Module

Now if CBS ever decides to cancel The Young And The Restless, we are going to have a real problem on our hands.

Retrosheet.org play-by-play baseball data

I have thought for a long time that Retrosheet.org was a pretty neat web site with the potential for a ton of baseball information.

They have loads of stats on their site, but it can be hard to get at sometimes.  As a result, I thought I might do some coding against their data just for fun. (I am doing this mainly because I am bored, because the Steelers are not on TV here in Ohio today, and because cable does not carry the NFL Sunday Ticket.)

The first task is to take their event data files and get them into a format that can be easily read and parsed. There are zip files on the Retrosheet web site to download entire seasons worth of event data, just go to retrosheet.org, hover over Data downloads, and select Play-by-play files.

However, once you look at these event files, you discover that they may need a little interpreting to get them into a nicer format for study. Luckily, Tom Tippett, David Nichols, and David W. Smith wrote a DOS application that does this, you just need to run this BEVENT.EXE file on each of the event files.

And of course, I couldn’t simply do that, I had to write a VB.NET console application to create a batch file do automate this.

Imports System.IO
 
Module Module1
 
    Sub Main()
 
        Console.WriteLine("BEvent Helper")
        Console.Write("Enter the directory of your event files: ")
        Dim d As String = Console.ReadLine()
 
        If d.Trim = "" Or Not Directory.Exists(d) Then GoTo App_end
        If Right(d, 1) <> "\" Then d = d + "\"
 
        Dim eventFilenames As List(Of String)
        eventFilenames = Directory.GetFiles(d, "*.ev?").ToList
 
        Dim s, cmd As String
        Dim sw As StreamWriter = New StreamWriter(d + "BEventHelper.bat")
        For Each f In eventFilenames
            s = Path.GetFileName(f)
            cmd = "bevent.exe -f 0-96 -y " + Left(s, 4) + " " + s + " > " + s + ".csv"
            sw.WriteLine(cmd)
        Next
        sw.WriteLine("pause")
        sw.Close()
 
App_end:
        Console.WriteLine("Press any key to end application...")
        Console.ReadKey()
 
    End Sub
 
End Module

So what you do is download a season zip file (such as the 2008 Major League season), unzip the files into a directory, download the bevent.zip file from the Software tools page, unzip it and place the BEVENT.EXE file into the directory with all the event files, run the console application and enter the directory name at the prompt, and when it is all said and done, you have a BEventHelper.bat file in the directory. Once this file is run, you will end up with CSV files that correspond to the event files.

In the next episode, I will begin to read in the data and crank out some preliminary statistics.

Disclaimer: The information used here was obtained free of charge from and is copyrighted by Retrosheet. Interested parties may contact Retrosheet at “www.retrosheet.org”.