(Print this page)

The My namespace
Published date: Monday, June 11, 2007
On: Moer and Éric Moreau's web site

One of the great new feature in Visual Basic 2005 is the My namespace.

The My namespace doesn’t bring anything new to the language. It simply offers a clearer path to methods and properties already existing in the .Net Framework. You can see it as a shortcut to quickly access features that are sometime hard to find.

This is the first article of a series of 2. Next month, I will show you how to extend this namespace with your own methods.

Is there a bug around My?

I never heard that there is a bug with the My namespace. What many people complain is that the classes exposed by the My namespace varies according to the project type you are currently in.

Here is a table showing you the classes available depending on the project type you are building:

 
Class
Windows
Application
Console
Applications
Class
Library
Web
Applications
My.Application X X X  
My.Computer X X X X
My.Forms X      
My.Log X     X
My.Request       X
My.Response       X
My.Settings X X X  
My.User X X X X
My.WebServices X X X  

I am sure you now want to see some action.

Figure 1:The demo application

Make some noise

You sometimes want to have your application make some noise. If you want some standard noise, you can use something like this:

My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)
Can you guess what sound it will make? If you prefer to play a .wav file, you can use this syntax:
My.Computer.Audio.Play(txtPath.Text)
This will play your file once. If you look at the Intellisense, you will find that 4 overloads exist on this method. Instead of giving a path to your file, you could pass a stream or an array of bytes containing your wav file (useful if you store your sounds in a resource file). There is also a second parameter that let you play the file in loop. In this case, you will want to stop the sound at some point and you will need to use the stop method:
My.Computer.Audio.Stop()

Getting some info about just everything

You won’t be able to query the weather forecast with the My namespace but the information about your computer, and your application, your user. Here is an example of some interesting properties to know:

With ListBox1.Items
    .Clear()
    .Add("Computer Name : " + My.Computer.Name)
    .Add("Computer.Screen.WorkingArea : " + My.Computer.Screen.WorkingArea.ToString)
    .Add("Computer.Info.OSFullName : " + My.Computer.Info.OSFullName)
    .Add("Computer.Info.TotalPhysicalMemory : " + My.Computer.Info.TotalPhysicalMemory.ToString)
    .Add("Computer.Info.TotalVirtualMemory : " + My.Computer.Info.TotalVirtualMemory.ToString)
    .Add("Computer.Info.AvailablePhysicalMemory : " + My.Computer.Info.AvailablePhysicalMemory.ToString)
    .Add("Computer.FileSystem.CurrentDirectory : " + My.Computer.FileSystem.CurrentDirectory)
    .Add("Application.Info.Title : " + My.Application.Info.Title)
    .Add("Application.Info.Version : " + My.Application.Info.Version.ToString)
    .Add("User.Name : " + My.User.Name)
End With

Working with folders and files

Would you believe me if I tell you that I can list the content of a folder into a listbox control using a single line of code? This line is:

ListBox1.DataSource = My.Computer.FileSystem.GetFiles("c:\Temp")
If you want to read the content of a text file, you can also do it with a single line of code:
txtTextFile.Text = My.Computer.FileSystem.ReadAllText("C:\WINNT\win.ini")
Another nice feature is to be able to copy files or folders using the standard Windows dialog (including the cancel button). Notice that there are a couple of overloads on this method. I only show the one I prefer here. This feature can be implemented using a single line but you will normally use the 5 lines syntax if you allow the cancellation of the copy like this:
Try
    My.Computer.FileSystem.CopyDirectory( _
        "c:\temp", _
        "c:\temp2", _
        FileIO.UIOption.AllDialogs, _
        FileIO.UICancelOption.ThrowException)
Catch ex As OperationCanceledException
    'user canceled the operation
End Try

Resources file

Using the My namespace, the resources file is now strongly type which ease access to the resources by providing Intellisense and compile-time checking.

If you have a string resource named String1 in your application, you can access it simply by using:

My.Resources.String1

Detecting network connectivity

It is really easy to know if the computer is attached to a network or not:

If My.Computer.Network.IsAvailable Then
    lblNetworkStatus.Text = "the network is available"
Else
    lblNetworkStatus.Text = "the network is NOT available"
End If
You can also detect when the status is changing. It is a bit more complex and … it is not always working!

Figure 2: Project Properties

To try if you can get it working, you need to open your project properties and click the “View application events” from the Application tab. Clicking this button will open a code screen from which you need to select (MyApplication Events) from the top-left combo and NetworkAvailabilityChanged the from the top-right combo to create the event handler. You can then write code to warn user that the status has changed:

My.Forms.Form1.NetworkStatusChanged()
I found that if you have more then one network connection (which is frequent on laptop because of both wired and wireless connections), you may not be able to get it working.

My.Settings

My article published in March 2007 showed how to use the My.Settings class. Just like the resources file, the settings are now strongly typed. Refer to that article for more information.

What if you are doing C#?

The My namespace is natively limited to VB developers. If you are a C# developer, everything is not lost. There are some alternatives. The most useful is probably the That class created by Juval Lowy that you can get for free by searching for “My for C# 2.0” from http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11. Another workaround is explained at http://www.codeproject.com/useritems/MyNamespace.asp.

Conclusion

I know that all the features shown here are existing elsewhere in the .Net Framework but the My namespace makes it so easy to use because it is well organized.

Don’t forget to read my next article which will show you how to customize the My namespace with your own content.

I hope you appreciated the topic and see you next month.


(Print this page)