ONDotNet.com    
 Published on ONDotNet.com (http://www.ondotnet.com/)
 See this if you're having trouble printing code examples


Rapid Application Development with VB.NET 2.0

by Jesse Liberty
08/02/2004

For a couple of years now, I've been touting the Microsoft-endorsed sentiment that it really doesn't matter if you program in C# or in VB.NET, since both are just syntactic sugar layered on top of MSIL (Microsoft Intermediate Language, the true language of .NET). That appears to be changing a bit with Whidbey.

Microsoft seems to be targeting Visual Basic 2.0 a bit more towards Rapid Application Development (RAD), and thus the designers of VB2 have added a few features to make developing applications quicker and easier. A key feature in this approach is the My object. The My object exposes six top-level objects for fast access to various aspects of your application, environment and resources. These are:

Each of these objects provides extensive properties for access to otherwise difficult-to-find or difficult-to-manipulate aspects of your running application and its environment. To see the My object at work, and to demonstrate how quickly it allows you to put together an application, I've created a small test app, shown in Figure 1.


Figure 1.

Notice that the application indicates whether or not you are currently connected to the network (this is updated by an event if you disconnect or reconnect), whether or not you are an administrator on this machine, which special keys are depressed, and what is currently on the clipboard. The Look Again button reexamines the keys and the clipboard (there is no event handling for when keys are depressed in this implementation). There are also buttons to get or set a specific registry entry, and there is a list box with information about the computer and the current user. Finally, there is a list of .wav files from the Windows\Media directory, and a button that allows you to play each of these sounds (double-clicking on an entry will play it, as well).

Programming Visual Basic .NET

Related Reading

Programming Visual Basic .NET
By Jesse Liberty

Creating this application took about an hour. It would have gone faster, but I was learning more about the My object as I went. By any standard, that is fairly rapid application development.

You can download the code for this application, but it is quite easy to create it for yourself. (Note: the code was created with the Beta 1 version of Visual Studio .NET 2005.)

To create this application yourself, begin by creating a new VB Windows Application. Drag the list boxes, check boxes, and so forth onto the form as shown in Figure 1. For convenience, name them as shown in Figure 2.


Figure 2.

Loading the Form

When the form loads, you'll set the current working directory to C:\Windows\Media and you'll set the data source for lbClips to the list of files in that directory that end in .wav. You accomplish all of this with two lines of code added to the FrmMy_Load event handler:


Private Sub FrmMy_Load(ByVal sender As Object, _
                       ByVal e As System.EventArgs) _
                       Handles Me.Load

The first line of code will set the current directory, using My.Computer.FileSystem.CurrentDirectory.

My.Computer.FileSystem.CurrentDirectory = "C:\Windows\Media"

Let's examine this line a bit more closely. The My object exposes the Computer object, which provides properties for manipulating the components of the computer, including the clock, keyboard, file system, and audio. We'll come back to this object a lot. My.Computer has a property, FileSystem, that returns the My.Computer.FileSystem object, which in turn has properties and methods for working with drives and files. One such property, CurrentDirectory, sets or gets the current directory for the application.

The second line of code in the FrmMy_Load method sets the data source for the list box to the list of files in the current directory.

lbClips.DataSource = _
    My.Computer.FileSystem.GetFiles( _
      My.Computer.FileSystem.CurrentDirectory, _
      False, _
      "*.wav")

Here, the My.Computer.FileSystem.GetFiles method is being called. It takes three arguments (in this overloaded version): a directory, a Boolean indicating whether to recurse into the subdirectories, and a string indicating the wildcards to use in retrieving the files.

Hey! Presto! the list box is loaded with all of the .wav files from the Windows/Media directory.

The load event handler then calls five other methods as follows:

Each of these methods is made absurdly simple by the My object.


Public Sub IsNetworked()
    Me.cbNetworked.Checked = My.Computer.Network.IsAvailable
End Sub

The Network object, available as a property of My.Computer, has a property named IsAvailable that returns true if the computer is currently connected to the network. That Boolean value is used to set the Checked property of the cbNetworked check box. Later in this article, I'll show you how to update that check box by responding to the NetworkAvailabilityChanged event.

The IsAdministrator method is equally straightforward.


Private Sub IsAdministrator()
    Me.cbAdministrator.Checked = _
      My.User.IsInRole("Administrators")
End Sub

The My.User object contains a great deal of information about the current user. The IsInRole method is a quick and easy way to determine what permissions to provide the user.

The CheckKeys method sets each of the key-related check boxes by using the Boolean parameters of the Keyboard object retrieved through My.Computer:

Private Sub CheckKeys()
  Me.cbAltKey.Checked = My.Computer.Keyboard.AltKeyDown
  Me.cbCapsLock.Checked = My.Computer.Keyboard.CapsLock
  Me.cbCtrlKey.Checked = My.Computer.Keyboard.CtrlKeyDown
  Me.cbNumLock.Checked = My.Computer.Keyboard.NumLock
  Me.cbScrollLock.Checked = My.Computer.Keyboard.ScrollLock
  Me.cbShiftKey.Checked = My.Computer.Keyboard.ShiftKeyDown
End Sub

The FillFromClipboard method calls GetText on the Clipboard object, also available from the My.Computer object. The Clipboard object can be used to place items onto the clipboard as well, including images and other non-text objects:

Private Sub FillFromClipBoard()
    Me.txtClipBoard.Text = My.Computer.Clipboard.GetText()
End Sub
Finally, the FillComputerInfo method uses the My.Computer.Info object to obtain information about memory, the operating system, and the current user, and this information is added to the lbComputerInfo list box:
Private Sub FillComptuerInfo()
  Me.lbComputerInfo.Items.Add( "Total memory: " +  _
    My.Computer.Info.TotalPhysicalMemory.ToString())
  Me.lbComputerInfo.Items.Add("Physical memory: " + _
    My.Computer.Info.AvailablePhysicalMemory.ToString())
  Me.lbComputerInfo.Items.Add("Virtual memory: " + _
    My.Computer.Info.AvailableVirtualMemory.ToString())
  Me.lbComputerInfo.Items.Add("Machine Name: " + _
    My.Computer.Info.MachineName.ToString())
  Me.lbComputerInfo.Items.Add("User: " + _
    My.Computer.Info.UserName.ToString())
  Me.lbComputerInfo.Items.Add("O.S.: " + _
    My.Computer.Info.OSFullName.ToString())
End Sub

The Look Again button event handler just calls CheckKeys and FillFromClipBoard to reset the check boxes and the text based on changes since the form was loaded.

Implementing the Interactions

In the upper-right-hand corer, you see a text box and two buttons: Set and Get. These are used to write a string to a key in the registry, and to read that string from the registry, respectively. The Get button's handler calls the GetValue method of the Registry object obtained through My.Computer. This method takes three arguments: the key, the value name, and the default value to return if the key is empty.

Private Sub btnGetRegistry_Click(ByVal sender As System.Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles btnGetRegistry.Click
  Me.txtRegistry.Text = My.Computer.Registry.GetValue( _
    "HKEY_CURRENT_USER\MyObjectKey", _
    "MyObjectValue", _
    "No Registry value stored").ToString()
End Sub
Setting the Registry uses the SetValue method on the same object, and the three arguments this time are the key, the name of the value, and the actual text to store.

My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyObjectKey", _
                              "MyObjectValue", _
                              Me.txtRegistry.Text)
Me.txtRegistry.Text = String.Empty

The second line of code clears the text box when the text is written to the registry.

An event handler is created for both the Click event on the Play button and for a double-click event on the lbClips list box.


Private Sub Play_Event(ByVal sender As System.Object, _
                       ByVal e As System.EventArgs) _
                       Handles btnPlay.Click, lbClips.DoubleClick

The job of this event holder is to find the currently selected .wav file and to play it. This is done using the Play method of the Audio object obtained from My.Computer.

My.Computer.Audio.Play(lbClips.SelectedItem)

Using MyEvents.vb

Finally (and this is about the only tricky bit in this entire example), you want the ConnectedToNetwork check box to be updated if you unplug your network cable. To accomplish this, you need to implement a handler for the NetworkAvailabilityChanged event. To do so, return to the solution explorer and click the Show All Files button. It turns out that your application includes a hidden file, named MyEvents.vb, as shown in Figure 3.


Figure 3.

Open that file and click on the drop-down menu to show the events. Click on the NetworkAvailabilityChanged event and the outline of the event handler is created for you, as shown in Figure 4.


Figure 4.

Within that handler, just add a call to FrmMy.IsNetworked() so that when the network availability changes (and the event is fired) you can update your check box.

Summary

The My object has made creating this application almost absurdly easy. Each of the My object objects has many more properties and methods than are shown here, but they are easy to explore through Intellisense and the MSDN documentation, now that you know they exist and have seen how they are used.

VB 2 has taken a dramatic lead in Rapid Application Development with the My object. This raises the question of why this facility is not available in C#. Unless there is a clear performance penalty in using the My object (I've not tested that yet) there is no reason to turn our C# noses up at anything that makes programming easier; after all, the more that is provided by the framework, the more we can concentrate on designing and building the application.

The example code for this article is available for download.

Jesse Liberty is a senior program manager for Microsoft Silverlight where he is responsible for the creation of tutorials, videos and other content to facilitate the learning and use of Silverlight. Jesse is well known in the industry in part because of his many bestselling books, including O'Reilly Media's Programming .NET 3.5, Programming C# 3.0, Learning ASP.NET with AJAX and the soon to be published Programming Silverlight.


Return to ONDotnet.com

Copyright © 2009 O'Reilly Media, Inc.