patterncsharpMinor
Loading Active Directory users by username and by SID
Viewed 0 times
directorysidactiveusernameloadingandusers
Problem
I have many different methods like ones below, but is there way I could improve them and remove duplicate code ?
public static ADUser Load(string userName)
{
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, IdentityType.SamAccountName, userName))
{
if (user != null)
{
return Utilities.LoadUser(user);
}
}
return null;
}
public static ADUser LoadBySid(string sid)
{
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, IdentityType.Sid, sid))
{
if (user != null)
{
return Utilities.LoadUser(user);
}
}
return null;
}Solution
I have limited knowledge in C#, but could you not extract something like this?
private static ADUser InternalLoad( IdentityType type, string identity ) {
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, type, identity))
{
if (user != null)
{
return Utilities.LoadUser(user);
}
}
return null;
}Code Snippets
private static ADUser InternalLoad( IdentityType type, string identity ) {
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, type, identity))
{
if (user != null)
{
return Utilities.LoadUser(user);
}
}
return null;
}Context
StackExchange Code Review Q#105023, answer score: 6
Revisions (0)
No revisions yet.