LinqPad – Get Disk Information

Getting hardware information can sometimes be hard when writing in .NET, the Framework keeps many of the deails away from the developer.  One day I needed to know if a drive letter existed and what type of drive it was.  I found many ways to do this but the one I liked the best is extremely simple from a code perspective:

Assemblies:
System.Management
System.Management.Instrumentation

var drive = "C";
var disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
disk.Get();
disk.Dump();

LinqPad – Enum to String

Converting an enum item to s string in C# is pretty simple, but we had a situation where the enum was not what we wanted to display to the user on the web.  Looking around I found several examples of how to get the displayed version to be more user-friendly.  Here is an example:

public enum SysModeType
{
 Student,
 Admin,
 Preceptor,
 Undefined
}

We wanted to show “Administrator” on the web site but internally we were using “Admin”. We could do a search and replace for all Admin entries but there were other implications to the enum question in my mind. What if I wanted to display “Student Teacher” or “Intern/Unpaid” or any other combination of things that are not compatible with C# syntax.  I came up with several solutions and then went once step forward to test the performance of each.  The link is what worked and what didn’t.  I leave it to you to decide which one works for you.

LinqPad File: Utility – Enum to string.linq

LinqPad – Active Directory User Groups

The other day I needed to know the Active Directory groups a user had assigned.  Not being an operations person, I couldn’t go and use the tools on the server.  I decided there must be an easy way to get this done.  After a bit of searching, I came up with this LinqPad script using some assemblies Microsoft provided.

Assemblies:
System.DirectoryServices
System.DirectoryServices.ActiveDirectory
System.DirectoryServices.AccountManagement
System.DirectoryServices.Protocols

string username = 'hlord'; 
string domain = 'MyDomain'; 

var domainGroups = new List<string>(); 
var domainContext = new PrincipalContext(ContextType.Domain, domain); 
var user = UserPrincipal.FindByIdentity(domainContext, username); 
var authGroups = user.GetAuthorizationGroups();
authGroups.All(g => {
		if (!string.IsNullOrEmpty(g.Name) && !domainGroups.Contains(g.Name))
			domainGroups.Add(g.Name);
		return true;
	});

domainGroups.Sort();
domainGroups.Dump();

LinqPad File: LDAP – User Groups.linq