Wednesday, January 25, 2006

VB.NET "My" Namespace for C#

When attending the free workshops by Microsoft on the new features of the .NET framework 2.0, I was really impressed with the new "My" namespace. But, I was kinda disappointed to find out that was a VB.NET-only language feature....being a C# developer, I was frustrated.

However, I've found out that you can use most of the functionalities of that namespace in C# if you import the Microsoft.VisualBasic library into your C# project. (HEART ATTACK! BREATHE!!!!) Ok, for you C# purists, this may be a little nerve-racking, but if you don't like this solution read on for more suggestions.

Once you've added the reference to your C# project, just include the following using statement in your class:

using Microsoft.VisualBasic.Devices;

Then you can use the "MyServices" namespace as follows.



class TestMyServices
{
// Play a sound w/ the audio class
Audio myAudio = new Audio();
Console.WriteLine("Playing sound...");
myAudio.Play(@"c:\WINDOWS\Media\chime.wav");
// or use Computer object to call Audio class
Computer myComputer = new Computer();
myComputer.Audio.Play(@"c:\WINDOWS\Media\ding.wav");
// display time info w/ the clock class
Clock myClock = new Clock();
Console.WriteLine("Current Time: {0}", myClock.LocalTime);
Console.WriteLine("Current day of week: {0}", myClock.LocalTime.DayOfWeek);
// display machine info with computer class
Console.WriteLine("Computer Name: {0}", myComputer.Name);
if (myComputer.Network.IsAvailable)
Console.WriteLine("Computer is connected to Network");
else
Console.WriteLine("No network available");
}

You can gain access to most of the same features of VB's My namespace, except a few (e.g. FileSystemProxy). Here is some of the stuff you can access w/ MyServices:
Audio, Clipboard, Clock, FileSystem, Info, Keyboard, Mouse, Name, Network, Ports, Registry, Screen.

For those classes not available for C# from MyServices, you can most likely use a static method implementation, e.g.:

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(@"c:\origDir", @"c:\copyOfDir");
You can find more on this topic in the Visual Studio 2005 Help by searching for "How to: Use the My Namespace (C# Programming Guide)"

Thanks to Kubben at the CodeProject for the great tip.

Happy coding!

1 comment:

Interveiw Questions said...

Try to avoid using My everywhere in your code.