Monday, April 22, 2013

Things that were once hard

I needed a quick utility to generate a script for setting the permissions on a massive (wide and deep) directory structure.  The analysis for this was not going well - I asked someone else to try it and they did not get the scope of the issue.  I needed to just get something running quickly so I wrote a quick .NET app to generate what I needed.  I was pleasantly surprised when went to actually grab the permissions for a given folder.

The last time I did something where I was scraping permissions off a folder I was in C++ and the Win32 API.  Yikes!  High impedence for something that I was just going to throw away.

The following is a snippet of code that wrote doing in .NET 4 (I don't think this code would be any different in .NET 2).
 class FolderPermissions  
{
public string Name { get; set; }
public IEnumerable<Acl> Acls { get; set; }
}
class Acl
{
public string Name { get; set; }
public FileSystemRights Permission { get; set; }
}
private static FolderPermissions GetFolderPermissions(string pFolderName)
{
AuthorizationRuleCollection perms;
perms = SafeCallToGetAccessRules(pFolderName);
var retAcls = new FolderPermissions { Name = pFolderName };
var acls = new List<Acl>();
foreach (FileSystemAccessRule perm in perms)
{
if ( perm.AccessControlType == AccessControlType.Deny)
continue;
var acl = new Acl() {Permission = perm.FileSystemRights, Name = perm.IdentityReference.ToString()};
acls.Add(acl);
}
retAcls.Acls = acls.ToArray();
return retAcls;
}

This snippet is where I am copying the permissions for a given folder into my own lightweight structure, so that I could do queries on the structure to help me create the script.

One thing in particular I remember about doing this in Win32 was once I got the SID for a particular identity, it was a pain to resolve that to a name.  Now it is just the IdentityReference.Value.

This is the type of value I like.  Now if I just had a scripting language to do this in so I did not have to compile it would be all set.  Of course there are bunch out there - just I am not as proficient in them as I am in C#.  Hmmm.