Here’s a fun little piece of code I scraped together today for an ongoing issue we’ve been having. Seems for years nobody can figure out how to locate whether a user(jodom for example) exists in our Active Directory and how to add them to a group via C#. A few people have tried but always given up and used a web service built by a consultant that no one knows what happened to the source code. The service is a pain because it dies silently whether the user exists or not and whether it succeeds or not.(really dude)

The code isn’t that difficult as you can see and I’m almost certain my peers came up with something similar on previous attempts. I’m almost certain their failure was the result of not being able to obtain appropriate DN because nobody even our network engineers had heard of LDP Tool for Querying Active Directory(LDAP) which will assist you in building LDAP queries in C#. There’s obviously a disconnect there in the developer community because I must of ran through a dozen HELP threads on various .NET boards concerning this topic.

So….code is below and should work fine to add/remove a user to a group that the userName/password provided has Management rights to. It first uses the DirectorySearcher to find the DN of the account and then uses that DN for the Add/Delete. There might be a simpler(mo better) way to do it but this hammer works so swing it.

string NTId = "jsmith";
bool IsAdding = true;
string userName = "UserWithManagementRightsToGroup";
string password = "Password";
var exists = this.ObjectContext.SomeEntitys.Where(p => p.EmployeeID == NTId);
DirectorySearcher userSearcher = new DirectorySearcher();
userSearcher.Filter = "(&(objectclass=user)(objectCategory=person)" + "(sAMAccountName=" + NTId + "))";
if (userSearcher != null)
{
userSearcher.PropertiesToLoad.Add("distinguishedName");
SearchResult searchResult = null;
using (SearchResultCollection src = userSearcher.FindAll())
{
if (src.Count > 0)
{
searchResult = src[0];
string DN = searchResult.Properties["distinguishedName"][0].ToString();
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://domain.com/" +
"CN=My_Users,OU=Security Groups,DC=domain,DC=com",
userName, password);
 
if (IsAdding == true && !entry.Properties["member"].Contains(DN))
entry.Properties["member"].Add(DN);
else if (IsAdding == false && entry.Properties["member"].Contains(DN))
entry.Properties["member"].Remove(DN);
else if (IsAdding == true && entry.Properties["member"].Contains(DN))
OnError(new DomainServiceErrorInfo(new CustomError("Attempted to add user that is already in group. : " + NTId)));
else if (IsAdding == false && !entry.Properties["member"].Contains(DN))
OnError(new DomainServiceErrorInfo(new CustomError("Could not remove because user was not in group. : " + NTId)));
 
entry.CommitChanges();
entry.Close();
}
catch (Exception uhoh)
{
}
}
}
}
Trackback

no comment untill now

Add your comment now

You must be logged in to post a comment.