C # Action AD and Exchange Server summary (i)
The purpose of this blog is to summarize the operations on AD and Exchange server, including creating new ad users, setting up passwords, create mailboxes for ad users, and so on, based on a personal project experience.
This article is completely original, reprint please explain the source, hope for everyone useful.
Document Directory:
- test environment and requirements brief
- For AD operations
- Introduction of DLL and method description
- New OU or security Group
- New ad User
- Add a user to a group or remove a user from a group
- User Information Update
- Enable/disable user Account
- For Exchange Server Operations
- Create a new mailbox for an ad user
- Configuring Clients and servers
- Summarize and generalize
First, test environment and demand brief
1. Test environment
Server: Windows Server 2008R2
Exchange:exchange Server SP1
Development tools: Visual Studio 2010
One Exchange Server + one AD Server + one server hosting the test program
2. Demand Brief
- Create a corresponding OU based on the information provided
- Create a new ad user based on the user information provided
- Modify AD users based on the information provided
- For AD users
Second, ad operation
1. Introduction of DLL and method description
MS provides remote operation of ad DLL:System.DirectoryServices (with the addition of references);
Where we use the LDAP protocol to access the AD,LDAP translates to a Lightweight Directory Access protocol.
There are some issues to be aware of when using:
- If used in the Web application, when the amount of data back to produce a time-out problem, it is recommended to take other means such as MS MQ processing information, avoid the problem of time-out.
- The use of LDAP is a security risk, after all, transmission of user credentials over the network is not very secure, preferably run in the enterprise intranet.
DirectoryServices actually provides a lot of other operations, such as the operation of IIS, the operation of local users, interested can be understood under.
2. New OU or security Group
Create a new console application first
To add a service reference:
Create a new public method in the project that ADHelper.cs uses to provide AD operations
public class Adhelper {///<summary>////</summary>// <returns> </returns> public Static DirectoryEntry Getdirectoryentry () { DirectoryEntry de = new DirectoryEntry (); De. Path = "Ldap://ad server address/ou=companya,dc=contoso,dc=com"; De. Username = @ "contoso\ Administrator account"; De. Password = "Administrator password"; Return de; } <summary>//// with one parameter to create the connection overload///</summary>// <param name= "Domainreference" > </param> //<returns></returns> public static DirectoryEntry Getdirectoryentry (string Domainreference) { DirectoryEntry entry = new DirectoryEntry (domainreference, "Administrator account", "Administrator Password", Authenticationtypes.secure); return entry; } }
Adhelper Code Explanation:
- Create a new DirectoryEntry class, which is the entry class for the Active Directory
- Specifies the path to connect to, explaining in detail the composition of path in a later instance of the new OU
- To connect to the ad's administrator account, this administrator account must have permission to operate the ad
- The administrator's password is also to connect to the ad
- The overloaded getdirectoryentry is used to refer to the entry of this path according to the input path, and later
Create a new ADManage.cs action class that defines the specific action method:
<summary>//new OU///</summary>// <param name= "path" ></param> public void Createou (string name) { if (! Objectexists (name, "OU")) { DirectoryEntry DSE = Adhelper.getdirectoryentry (); Directoryentries ous = Dse. Children; DirectoryEntry NewOU = OUs. ADD ("ou=" + Name, "organizationalunit"); Newou.commitchanges (); NewOU. Close (); Dse. Close (); } else { Console.WriteLine ("Ou already exists"); } }
New OU code Explanation:
- The Objectexists method determines whether the new OU already exists, and the code below will enclose
- Using Adhelper to generate a directory entry, this example is in a Test CompanyA ou
- The Children property gets all the subkeys and adds the OU using the Add method
- Commit changes, send back to server
<summary>// new security Group/// </summary>/ <param name= "path" ></param > Public void CreateGroup (string name) { if (! Objectexists (name, "Group")) { DirectoryEntry DSE = Adhelper.getdirectoryentry (); Directoryentries Groups = DSE. Children; DirectoryEntry newgroup = Groups.add ("cn=" + Name, "group"); Newgroup.commitchanges (); NewGroup. Close (); Dse. Close (); } else { Console.WriteLine ("User group already exists"); } }
<summary>///To determine the presence///</summary>/<param name= "ObjectName" ></param> <param name= "Catalog" ></param>///<returns></returns> public bool Objectexis TS (string objectName, String catalog) {DirectoryEntry de = Adhelper.getdirectoryentry (); DirectorySearcher desearch = new DirectorySearcher (); Desearch.searchroot = de; Switch (catalog) {case "User": Desearch.filter = "(& (Objectclass=user) (cn=" + ObjectName + "))"; Break Case "Group": Desearch.filter = "(& (Objectclass=group) (cn=" + ObjectName + "))"; Break Case "OU": Desearch.filter = "(& (Objectclass=organizationalunit) (ou=" + ObjectName + "))"; Break Default:break; } searchresultcollection results = Desearch.findall (); if (results. Count = = 0) {RETurn false; } else {return true; } }
How to do it after we've written it, we'll test it.
Write the test code in program:
static void Main (string[] args) {admanage manage=new admanage (); Test Create OU Console.WriteLine ("Create OU Start ..."); try {manage. Createou ("NewOU01"); Console.WriteLine ("Create OU Finish ..."); Console.ReadLine (); } catch (Exception ex) {Console.WriteLine ("Create OU Error ..."); Console.WriteLine (ex); Console.ReadLine (); }//test Create Group Console.WriteLine ("Create Group Start ..."); try {manage. CreateGroup ("NewGroup01"); Console.WriteLine ("Create Group Finish ..."); Console.ReadLine (); } catch (Exception ex) {Console.WriteLine ("Create Group Error ..."); Console.WriteLine (ex); Console.ReadLine (); } }
Run code
View results in Domain control:
Add:
How do I create a new OU under a multi-tier OU?
OUs are similar to folders, you can have OUs of the same name in different directories, and you want to create OUs under multi-tier OUs, first confirm the path
Suppose there is a ou,path for:
CompanyA
Branchb
Departmentc
The Path property in the Getdirectoryentry instance should be modified to:
"Ldap://ad server address/ou=departmentc,ou=branchb,ou=companya,dc=contoso,dc=com" so that the newly created OU will be in the DEPARTMENTC directory.
3. New ad User
There are some differences between new user and new OU or group, look at the code first:
<summary>///new user///</summary>/<param name= "name" ></param> <param name= "Login" ></param> public void CreateUser (string name, string login) { if (objectexists (login, "user")) {Console.WriteLine ("Users already exist"); Console.ReadLine (); Return } DirectoryEntry de = Adhelper.getdirectoryentry (); Directoryentries users = de. Children; DirectoryEntry NewUser = Users. ADD ("cn=" + login, "user"); SetProperty (NewUser, "givenname", name); SetProperty (NewUser, "sAMAccountName", login); SetProperty (NewUser, "userPrincipalName", Login + "@contoso. com"); Newuser.commitchanges (); SetPassword (NewUser. Path); Newuser.commitchanges (); NewUser. Close (); De. Close (); }//<summary> property settings///</summary>//<param name= "de" ></param>//<param name= "Pro Pertyname "></param>//<param name=" PropertyValue "></param> public static void SetProp Erty (DirectoryEntry de, String propertyname, String propertyvalue) {if (PropertyValue! = null) {if (DE. Properties.contains (PropertyName)) {de. Properties[propertyname][0] = PropertyValue; } else {de. Properties[propertyname]. ADD (PropertyValue); }}}///<summary>//Password set///</summary>//<param name= " Path "></param> public void SetPassword (string path) {DirectoryEntry user = new Director Yentry (); User. Path = path; User. AuthenticationType = authenticationtypes.secure; Object ret = user. Invoke ("SetPassword", new object[] {"password01!"}); User.commitchanges (); User. Close (); }
New User code Explanation:
- Use Objectexists to determine if the user exists, and if present, prompts the user to exist
- New entry class instance, Add method new user
- SetProperty set the new user's properties (display name, pre-windows 2000 login, login name), and commit the changes
- SetPassword set user initial password, commit changes, close connection
Write the test code:
static void Main (string[] args) { admanage manage=new admanage (); Console.WriteLine ("Create User Start ..."); Try { manage. CreateUser ("Employee John", "Employee01"); Console.WriteLine ("Create User Finish ..."); Console.ReadLine (); } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { Console.WriteLine ("Create User Error ..."); Console.WriteLine (ex); Console.ReadLine (); } }
Test results:
Note: The new account is inactive at this point, and the following sections describe how to enable/disable
4. Add users to groups or remove users from groups
Add/Remove users to the group using the DirectorySearcher, to find the group, see Code:
<summary>///Add users to groups///</summary>//<param name= "de" ></param> <param name= "UserDN" ></param>///<param name= "GroupName" ></param> public void AddUserToGroup (DirectoryEntry de, String UserDN, String GroupName) {DirectorySearcher desearch = new Di Rectorysearcher (); Desearch.searchroot = de; Desearch.filter = "(& (Objectclass=group) (cn=" + GroupName + "))"; SearchResult Groupresult = Desearch.findone (); if (Groupresult! = null) {DirectoryEntry user = Adhelper.getdirectoryentry ("ldap://ad server/" + US ERDN); if (user! = null) {DirectoryEntry direntry = Groupresult.getdirectoryentry (); if (direntry.properties["member"]. Contains (UserDN)) {Console.WriteLine ("The user already exists in the user group, will be removed"); direntry.properties["Member"]. Remove (USERDN); Console.WriteLine ("The user has been removed from the group"); } else {direntry.properties["member"]. ADD (USERDN); Console.WriteLine ("added successfully, user added to group"); } direntry.commitchanges (); Direntry.close (); } else {Console.WriteLine ("User does not exist"); } user. Close (); } else {Console.WriteLine ("User group does not exist"); } return; }
Code Explanation:
- Creates a new DirectorySearcher instance, assigns a value to the filter, finds the security group based on the passed-in Parameter de directory (note: This group needs to be included in DirectoryEntry)
- Determine if the user exists based on the parameter UserDN (UserDN is the user's identity name, such as "cn=employee01,ou=companya,dc=rzh,dc=com")
- direntry.properties["Member"]. Contains (USERDN) determines whether the user exists in the group
- If the user is not present in the group, the user is added to the group. If the user exists in the group, the user is removed from the group
Test it, just test the Add, remove the action, test it yourself:
Class program { static void Main (string[] args) { admanage manage=new admanage (); Console.WriteLine ("Add user to Group Start ..."); Try { manage. AddUserToGroup (Adhelper.getdirectoryentry (), "cn=employee01,ou=companya,dc=contoso,dc=com", "NewGroup01"); Console.WriteLine ("Add user to Group Finish ..."); Console.ReadLine (); } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { Console.WriteLine ("Add user to Group Error ... "); Console.WriteLine (ex); Console.ReadLine ();}}}
Test results:
5, User Information update
User Information update is also relatively simple, directly on the sample code + test code, if in doubt, feel free to contact:
public void ModifyUser (DirectoryEntry de,string username,string Company) { DirectorySearcher desearch = new DirectorySearcher (); Desearch.searchroot = de; Desearch.filter = "(& (Objectclass=user) (cn=" + UserName + "))"; SearchResult result = Desearch.findone (); if (result = null) { DirectoryEntry dey = adhelper.getdirectoryentry (result. Path); SetProperty (Dey, "Company" and company); Dey.commitchanges (); Dey. Close (); } De. Close (); }
static void Main (string[] args) { admanage manage=new admanage (); Console.WriteLine ("Modify User info Start ..."); Try { manage. ModifyUser (Adhelper.getdirectoryentry (), "Employee01", "CompanyA"); Console.WriteLine ("Modify User info Finish ..."); Console.ReadLine (); } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { Console.WriteLine ("Modify User info Error ... "); Console.WriteLine (ex); Console.ReadLine (); } }
6. enable/disable User Account
Enable/disable user account to use the new attribute userAccountControl, can be the account password is expired, the account is available, etc. to set.
Here are the values that are used when setting userAccountControl
userAccountControl
The specific code is as follows:
<summary>//Enable account///</summary>// <param name= "de" ></param> public void Enableaccount (DirectoryEntry de) { //Set account password but not period int exp = (int) de. properties["userAccountControl"]. Value; De. properties["userAccountControl"]. Value = Exp | 0x10000; De.commitchanges (); Enable Account int val = (int) de. properties["userAccountControl"]. Value; De. properties["userAccountControl"]. Value = val & ~0x0002; De.commitchanges (); }
<summary>///Deactivate account///</summary>// <param name= "de" ></param> public void Disableaccount (DirectoryEntry de) { //Enable account int val = (int) de. properties["userAccountControl"]. Value; De. properties["userAccountControl"]. Value = Val | 0x0002; De.commitchanges (); }
The contents of the ad section have already been written, so take a look at the next article for Exchange Server operations.
If you have any questions, please discuss with me in time.
C # Action AD and Exchange Server summary (i)