PrincipalContext in class constructor

  • Thread starter Thread starter musosdev
  • Start date Start date
M

musosdev

Hi

I'm trying to create a static class for my ActiveDirectory functions...
things like GetUsernameFromID, etc.

The code works, but every function has to declare its own PrincipalContext,
and what I'd really like it to have that as a static, as follows...

public class ActiveDirectory
{
static PrincipalContext dC;

public ActiveDirectory()
{
dC = new PrincipalContext(ContextType.Domain,
"thepoint.org.uk.local");
}
}

public static string GetCurrentUserFullName(string userSAM)
{
string currentUserFN = "(unknown)";
string currentUserSN = "";
UserPrincipal user = UserPrincipal.FindByIdentity(dC, userSAM);
currentUserFN = user.GivenName;
currentUserSN = user.Surname;

return currentUserFN + " " + currentUserSN;
}
}

(have removed try/catch blocks for brevity)

However, this throws the following error on the line "UserPrincipal user =
UserPrincipal.FindByIdentity(dC, userSAM);"

"Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: context"

I assume this related to the dC object not being set, even though it is
being set by the Contructor!? Any ideas on how to resolve this? I tried
making the constructor static, but that fails with "access modifiers are not
allowed on static constructors".

Any help is appreciated!

Cheers


Dan
 
Brilliant - thanks for the explanations and advice guys.

static ActiveDirectory() {} works perfectly... great stuff!
 
Back
Top