Tuesday, June 29, 2010

This code just rocks.

Usually I post examples of code that sucks.  Today I am posting an example of code that just rocks.  Why does it rock because it solves a problem in a very elegant way.  I have had to write code to do the same thing several times but mine never looks or works as this example. The code comes from ravenDB’s server. It handles the case where you need to run in elevated privileges but the program wasn’t started at such a state.


private static void AdminRequired(Action actionThatMayRequiresAdminPrivileges, string cmdLine)
{
    var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false)
    {
        if (RunAgainAsAdmin(cmdLine))
            return;
    }
    actionThatMayRequiresAdminPrivileges();
}

private static bool RunAgainAsAdmin(string cmdLine)
{
    try
    {
        var process = Process.Start(new ProcessStartInfo
        {
            Arguments = cmdLine,
            FileName = Assembly.GetExecutingAssembly().Location,
            Verb = "runas",
        });
        if (process != null)
            process.WaitForExit();
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

1 comment:

Mel Green said...

Very cool!

Handling the switch to Administrator and automatically continuing the same function all in one executable is awesomely simple. I don't know why I hadn't thought of that before! There's a few places I could have used that.

Thanks for sharing! :D