using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
namespace Alpha.Code
{
public static class SecurityExtensions
{
public static IOrderedEnumerable<IGrouping <string, NTAccount>>
GetGroupsUnderDomains(this WindowsIdentity identity)
{
var groups =
from grIdentity in identity.Groups
where grIdentity.IsValidTargetType(typeof(NTAccount))
select grIdentity.Translate(typeof(NTAccount)) as NTAccount into ntAccounts
let domainName = ntAccounts.GetDomainName()
let groupName = ntAccounts.GetAccountName()
orderby domainName
group ntAccounts by domainName into domainGroups
orderby domainGroups.Key
select domainGroups;
return groups;
}
public static string GetDomainName(this NTAccount account)
{
string[] split = account.Value.Split('\\');
return split.Length == 1 ? string.Empty : split[0];
}
public static string GetAccountName(this NTAccount account)
{
string[] split = account.Value.Split('\\');
return split[split.Length - 1];
}
}
}