Jumping on the Environment Trend

28 ביוני 2008

תגיות:
אין תגובות

Recently everyone has been obsessed with the environment (at least the politicians…) and even I have started recycling and print double sided… But did you know that the .Net framework had tuned to the recent trends as well?

Save the trees!

So today we're going to talk about the System.Environment class and introduce some time-saving methods provided by it.

Useful information

The Environment class holds some valuable information about the application's environment (surprise surprise!). It exposes properties such as MachineName, OSVersion, UserDomainName, UserName, CurrentDirectory and the very helpful StackTrace property.
When you're debugging, this can be a lifesaver. You can log all the calls to a single method and find out who's calling it and when, just write out the Environment.StackTrace value.
For example, the following code:

class Program

{

    static void Main(string[] args)

    {

        Go();

    }

 

    public static void Go()

    {

        Console.WriteLine(Environment.StackTrace);

    }

}

 

Results in:

at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at TheEnvironmentTrend.Program.Go() in c:\Demo\Program.cs:line 18
at TheEnvironmentTrend.Program.Main(String[] args) in c:\Demo\Program.cs:line 13
Press any key to continue . . .

 

Special folders

Sometimes you need the path to some OS special folders. Getting them yourself might be a bit tricky, so instead, the Environment class comes to our aid:

public string GetTheUsersDesktopPath()

{

    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

 

    return path;

}

 

The GetFolderPath method returns the path to the given special folder. The SpecialFolder enum includes ApplicationData, InternetCache, History, MyDocuments, MyPictures and more.

Environment variables

Let's say your application stores data in the AppData folder. You can't assume that the AppData folder exists on the user's C drive, so you need to get the AppData path first. You could do it using the GetSpecialFolder method, but there is a better way:

public string GetMyAppDataPath()

{

    string path = Environment.ExpandEnvironmentVariables(@"%appdata%\MyApplication\Something");

 

    return path;

}

 

The ExpandEnvironmentVariables method is a huge time saver. You can set there any environment variable you want and they will be translated to their real values (like: logonserver, computername, homedrive and more. Try Start->Run->cmd, type "set" and run. You'll see your environment variables there). This doesn't have to be used just for paths, you can use it for various purposes. For instance, consider the following string: "You are %username%, you have installed windows on %windir% and you have a %NUMBER_OF_PROCESSORS% processor computer". This would be a great welcome message! (hmmmm)

The method Al-Gore would've liked

Environment.FailFast
Except from the fact that this is what we've been doing during the last centuries, this can be helpful in your code sometimes. For example, when you have an exception and you know that your application won't rise again from it, you can shut down the application, with no finally blocks called. Pay attention that calling this method will brutally shut down your application, so use it wisely.
For example, the following code:

public void ByeBye()

{

    try

    {

        Console.WriteLine("Doing something important");

 

        throw new Exception("Oh no!");

    }

    catch

    {

        // Our environment is at the no-return point!

        Environment.FailFast("No real explanation for the kids");

    }

    finally

    {

        Console.WriteLine("We're gonna save it now!");
        FixTheEnvironment();

}

}

Will result in:

Doing something important
Press any key to continue . . .

= deadTree

The finally block wasn't called…

Keep the environment safe!
Shay


Share this post : del.icio.us it! digg it! dotnetkicks it! technorati!

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים