It has been while since I post last article. Actually I was planning to post this a little bit earlier, but... you know those excuses :-D
So what this is all about. I had to create project which has to operate with Active Directory and that was quite a new stuff for me. I though it won't be difficult and as usual I was wrong :-D Well, to be clear it isn't as difficult as it is confusing :) So this article isn't for describing some hard codding stuffs, but it should be good starter for anyone who has no experience in this and wants to find a quick and straight way to start developing. (Let's face it, most of the demands involve just simple operation in the active directory) So enough jibber-jabber...
For the start you should know there are two libraries to work with AD. System.DirectoryServices and System.DirectoryServices.AccountManagement, In my opinion DirectoryServices is the most powerful, but difficult to use. AccountManagement is quite easier but it won't let you to do "everything" you want to. Here is large article about them and it contains a lot of information and examples: http://ianatkinson.net/computing/adcsharp.htm#examples2 and there is even more on the Internet ;-). But I will stick just with the introduction these classes to make this post simple as much as it is possible.
Now you may wondering what this post is about. Well I am gonna show you sample code of both libraries, then describe how to extend AccountManagement to let you do more cool stuffs and at the end I will show you some workarounds I had to use when I was codding project.
System.DirectoryServices
For start do not forget use this using System.DirectoryServices; using statement.
And here is the code
//User's sAMAccountName
string user = "User's
sAMAccountName";
try
{
//Connect to the AD
DirectoryEntry de = new DirectoryEntry("LDAP://serverIP_or_adress", @"userName", "password");
//Create a new instance of DirectorySearcher
class to find required user
DirectorySearcher deSearch = new DirectorySearcher();
//Set the start of searching
deSearch.SearchRoot = de;
//Set filter
deSearch.Filter = "(&(objectClass=user)
(sAMAccountName=" + user + "))";
//Save result to the instance of SearchResult
class
SearchResult result =
deSearch.FindOne();
//Check the result
if (result != null)
{
//Save new to the instnce of DirectoryEntry so
you can operate with user.
DirectoryEntry foundedUser = new DirectoryEntry(result.Path);
//Create
a writer and open the file
TextWriter tw = new StreamWriter("ADUserDefaultProperties.txt");
//Loop through all users properties
foreach (var
property in result.Properties.PropertyNames)
{
try
{
if (result.Properties[property.ToString()] != null &&
result.Properties[property.ToString()].Count > 0)
{
tw.WriteLine(property.ToString() + ":
" + foundedUser.Properties[property.ToString()].Value.ToString());
}
else
{
tw.WriteLine(property.ToString() + ":
" + "Couldn't reach the
property!");
}
}
catch (NullReferenceException
nullEx)
{
tw.WriteLine(property.ToString() + ":
" + "Exception / Couldn't reach
the property!");
}
}
// close the stream
tw.Close();
}
}
foundedUser.Rename("cn="
+ name + " "
+ surname);
foundedUser.CommitChanges();
There is more you can do with System.DirectoryServices, but it is not theme of this post...
System.DirectoryServices.AccountManagement
Again do not forget to add: using System.DirectoryServices.AccountManagement;
This code is actually from site I mentioned above:
// enter AD settings
PrincipalContext AD = new
PrincipalContext(ContextType.Domain,
"leeds-art.ac.uk");
// create search user and add
criteria
Console.Write("Enter
logon name: ");
UserPrincipal u = new
UserPrincipal(AD);
u.SamAccountName = Console.ReadLine();
// search for user
PrincipalSearcher search = new
PrincipalSearcher(u);
UserPrincipal result = (UserPrincipal)search.FindOne();
//Do not forget to dispose search
object
search.Dispose();
// show some details
Console.WriteLine("Display
Name : " + result.DisplayName);
Console.WriteLine("Phone
Number : " + result.VoiceTelephoneNumber);
I just would like to point out another great extended class you can find there. It is extending AvanceFilters class. If you will extend this class you can define your own criteria for searching in AD. Isn't that great? And it simple like this:
public class UserPrincipalsExSearchFilter : AdvancedFilters
{
public UserPrincipalsExSearchFilter(Principal p) : base(p)
{ }
public void
EmployeeID(int value, MatchType
mt)
{
this.AdvancedFilterSet("employeeID",
value.ToString(), typeof(string), mt);
}
}
Ok that's all for introduction. I know I haven't mentioned how to create user, delete user etc., but those things you can easily "google it". Once you know where to start and that there are two main classes to work with AD(and if you can distinguish their purposes) the rest of the work should be a peace of cake. At least for the start...
At the end I would like to mention two "problems" I had.
1. Once I wasn't able to update property in AD using System.DirectoryServices.AccountManagement. You can always combine both classes if you want to. So if you already have UserPrincipal of some user, you don't need to search him again using DirectoryServices. You can do it like this:
DirectoryEntry de = (DirectoryEntry)userPrincipalOfNewUser.GetUnderlyingObject();
de.Rename("cn=" + userPrincipalOfNewUser.Surname +
" " +
userPrincipalOfNewUser.GivenName);
de.CommitChanges();
This can be quite helpful I guess...
2. I was using those classes in WCF service and I could't connect to the AD server or do any changes. My problem was with impersonation. So simple wrap your code like this:
using (HostingEnvironment.Impersonate())
{
//Put your code here
}
It helped me ;)
Ok that's all...I hope this will help you to start with DirectoryServices and AccountManagement classes.
Happy codding..
No comments:
Post a Comment