Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
NET
Erika Ehrli Cabral June 2005 Some time ago I was working in a project where I had to design and develop a service to synchronize a human resources database with an Active Directory (AD). To accomplish my goal, I created a service that used .NET Directory Services, and after some months, the project succeeded. I had to invest a ton of extra hours to the project because I had a hard time finding sample .NET code and documentation related to specific tasks needed to work with AD User Accounts. Microsoft Technet offers a script repository to work with AD User Accounts; however, I needed to work with .NET and I could not find samples for all the tasks I needed to program. I promised to myself that one day I would publish the code samples I found and created to help other developers who are working with Directory Services. So, I wish you a happy AD.NET programming and I hope my work saves you some time. The code samples I provide are written in C#. Disclaimer: This code and information is provided as-is without warranty of any kind, either expressed of implied. Microsoft is not responsible for, shall have no liability for and disclaims all warranties whatsoever, expressed or implied, related to the provided code or information, including without limitation any warranties related to performance, security, stability, or non-infringement of title of material provided by dotnettreats.com.
How to...
1. Create a connection to Active Directory 2. Create a secure connection to Active Directory 3. Validate if a user exists 4. Set user's properties 5. Set user's country 6. Set user's password 7. Enable a user account 8. Add a user to a group 9. Generate a mailbox for a user in Microsoft Exchange Server 10. Create a user account 11. Disable a user account 12. Update user account 13. Validate if a string has a correct email pattern 14. Extract a user alias from an email account 15. Format dates to AD date format (AAAAMMDDMMSSSS.0Z) 16. Search users
/// </summary> public static void SetCultureAndIdentity(){ AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal; WindowsIdentity identity = (WindowsIdentity)principal.Identity; System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); }
} }
usr.AuthenticationType = AuthenticationTypes.Secure; object[] password = new object[] {SetSecurePassword()}; object ret = usr.Invoke("SetPassword", password ); usr.CommitChanges(); usr.Close(); } The usr.Invoke method can be called once within the same AppDomain, otherwise your program will crash. If you place a call to the usr.Invoke method inside a for construct, the first run will be succesful, but the second one will crash the compiler. I created a workaround that helped me to solve this problem. I made a separate console application (SetPassword.exe) and I called and started the process programatically from the SetPassword method. 1. Download the SetPassword project. 2. Copy the SetPassword.exe file in your application. 3. Call and start SetPassword.exe from you application. /// </summary> /// Method that calls and starts SetPassword.exe /// <param name="path"></param> /// <param name="password"></param> public void SetPassword(string path, string password){ StringBuilder args = new StringBuilder(); args.Append(path); args.Append(" "); args.Append(password); ProcessStartInfo startInfo = new ProcessStartInfo("SetPassword.exe",ar gs.ToString()); startInfo.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(startInfo); }
/// <param name="email"></param> /// <param name="group"></param> public void CreateNewUser(string employeeID, string name, string login, string email, st ring group){ Catalog catalog = new Catalog(); DirectoryEntry de = ADHelper.GetDirectoryEntry(); /// 1. Create user account DirectoryEntries users = de.Children; DirectoryEntry newuser = users.Add("CN=" + login, "user"); /// 2. Set properties SetProperty(newuser,"employeeID", employeeID); SetProperty(newuser,"givenname", name); SetProperty(newuser,"SAMAccountName", login); SetProperty(newuser,"userPrincipalName", login); SetProperty(newuser,"mail", email); newuser.CommitChanges(); /// 3. Set password SetPassword(newuser.Path); newuser.CommitChanges(); /// 4. Enable account EnableAccount(newuser); /// 5. Add user account to groups AddUserToGroup(de,newuser,group); /// 6. Create a mailbox in Microsoft Exchange GenerateMailBox(login); newuser.Close(); de.Close(); }
ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + Employee ID + "))"; ds.SearchScope = SearchScope.Subtree; SearchResult results = ds.FindOne(); if(results != null){ DirectoryEntry dey = GetDirectoryEntry(results.Path); int val = (int)dey.Properties["userAccountControl"].Value; dey.Properties["userAccountControl"].Value = val | 0x0002; dey.Properties["msExchHideFromAddressLists"].Value = "TRUE"; dey.CommitChanges(); dey.Close(); } de.Close(); }