C # AD (Active Directory) domain information synchronization, organization unit, user and Other Information Query

Source: Internet
Author: User
Tags ldap samaccountname

Next, configure the Active Directory domain controller for Windows Server 2008 r2

Use C # to read information for the ad domain in combination with common requirements ^_^!

 

Directory

 

  • Sample Preparation
  • Knowledge
  • Example of reading Ad Domain Information
  • Directorysearcher. Filter attribute extension description
  • Description of user attribute extension (including graphic attribute comparison)
    • General
    • Address
    • Account
    • Phone number
    • Organization
  • Sample download

 

Sample Preparation
  • Open the ad Domain Controller configured in the previous article
  • Start Menu --> Administrative Tools --> Active Directory users and computers
  • Create organizational unit and user

  • The new level is as follows:

  

 

Knowledge

It is very easy to use C # To access Active Directory.

Lightweight Directory Access Protocol (LDAP)

Two Component classes in the system. directoryservices namespace

Directoryentry and directoryseacher

 

Example of reading Ad Domain Information

The example is written in winform in Framework 3.5.

Reads Organization Unit (OU) and user information based on common requirements, and synchronizes the hierarchical relationship between organization unit and user;

It focuses on user information, especially account, email, Sid, and other information;

  

  • Next we start to connect to the domain and read it out.Sample PreparationOrganization Unit and user

First, write the code and use LDAP to try to access the domain.

Format: LDAP: // domain

# Region # Whether to connect to the domain /// <summary> // function: whether to connect to the domain /// Author: Wilson // time: 2012-12-15 // http://msdn.microsoft.com/zh-cn/library/system.directoryservices.directoryentry.path (V = vs.90 ). aspx // </Summary> /// <Param name = "domainname"> domain name or IP address </param> /// <Param name = "username"> User Name </ param> /// <Param name = "userpwd"> password </param> /// <Param name = "entry"> domain </param> /// <returns> </returns> private bool isconnected (string domainname, string username, string userpwd, out directoryentry domain) {domain = new directoryentry (); try {domain. path = string. format ("LDAP: // {0}", domainname); domain. username = username; domain. password = userpwd; domain. authenticationtype = authenticationtypes. secure; domain. refreshcache (); Return true;} catch (exception ex) {logrecord. writelog ("[isconnected method] error message:" + ex. message); return false ;}# endregion

Call the isconnected method by using parameters. The result is as follows:

  

  • After connecting to the ad domain, find the root ou
# Region # Whether the domain has an organizational unit // <summary> // function: whether the domain has an organizational unit // Author: Wilson // time: /// </Summary> /// <Param name = "entry"> </param> /// <Param name = "ou"> </param> // /<returns> </returns> private bool isexistou (directoryentry entry, out directoryentry ou) {ou = new directoryentry (); try {ou = entry. children. find ("ou =" + txtrootou. text. trim (); Return (ou! = NULL);} catch (exception ex) {logrecord. writelog ("[isexistou method] error message:" + ex. Message); Return false ;}# endregion

Call the isexistou method by number. The result is as follows:

  

  • Next, read the organization unit and user information.

In this example, an entity class and an enumeration type are created for ou and user to identify the hierarchy and export information.

# Region # type // <summary> // type // </Summary> Public Enum typeenum: int {// <summary> // organization unit // </Summary> ou = 1, /// <summary> /// user /// </Summary> User = 2 }# endregion # region # ad Domain Information Entity /// <summary> /// ad Domain Information Entity // </Summary> public class admodel {public admodel (string ID, string name, int typeid, string parentid) {id = ID; name = Name; typeid = typeid; parentid = parentid;} Public String ID {Get; set ;} public string name {Get; set;} public int typeid {Get; set;} Public String parentid {Get; Set ;}# endregion

Read the following information

Private list <admodel> List = new list <admodel> ();

# Region # synchronize /// <summary> /// function: Synchronize /// created by: Wilson // Creation Time: /// </Summary> // <Param name = "entryou"> </param> Public void syncall (directoryentry entryou) {directorysearcher mysearcher = new directorysearcher (entryou, "(objectclass = organizationalunit)"); // query the Organization Unit directoryentry root = mysearcher. searchroot; // search for the root ou syncrootou (Root); stringbuilder sb = new stringbuilder (); sb. append ("\ r \ NID \ t account \ t Type \ t parent ID \ r \ n "); foreach (VAR item in list) {sb. appendformat ("{0} \ t {1} \ t {2} \ t {3} \ r \ n", item. ID, item. name, item. typeid, item. parentid);} logrecord. writelog (sb. tostring (); MessageBox. show ("synchronization successful", this. text, messageboxbuttons. OK, messageboxicon. information); application. exit () ;}# endregion # region ## synchronize root organization units /// <summary> /// function: Synchronize root organization units /// Creator: wilson // Creation Time: /// </Summary> // /<Param name = "entry"> </param> private void syncrootou (directoryentry entry) {If (entry. properties. contains ("ou") & entry. properties. contains ("objectguid") {string rootouname = entry. properties ["ou"] [0]. tostring (); byte [] bguid = entry. properties ["objectguid"] [0] As byte []; string id = bitconverter. tostring (bguid); list. add (New admodel (ID, rootouname, (INT) typeenum. ou, "0"); syncsubou (entry, ID) ;}# endregion # region ## synchronize subordinate organization units and subordinate users /// <summary> // function: synchronize subordinate organization units and subordinate users /// Creator: Wilson /// Creation Time: /// </Summary> /// <Param name = "entry"> </param> /// <Param name = "parentid"> </param> private void syncsubou (directoryentry entry, string parentid) {foreach (directoryentry subentry in entry. children) {string entryschemaclsname = subentry. schemaclassname; string [] arr = subentry. name. Split ('='); string categorystr = arr [0]; string namestr = arr [1]; string id = string. empty; If (subentry. properties. contains ("objectguid") // Sid {byte [] bguid = subentry. properties ["objectguid"] [0] As byte []; id = bitconverter. tostring (bguid);} bool isexist = List. exists (D => D. id = ID); Switch (entryschemaclsname) {Case "organizationalunit": If (! Isexist) {list. add (New admodel (ID, namestr, (INT) typeenum. ou, parentid);} syncsubou (subentry, ID); break; Case "user": String accountname = string. empty; If (subentry. properties. contains ("samaccountname") {accountname = subentry. properties ["samaccountname"] [0]. tostring () ;}if (! Isexist) {list. Add (New admodel (ID, accountname, (INT) typeenum. User, parentid) ;} break ;}}# endregion

Call the syncall method to output the list cyclically. The result is as follows. You can see the hierarchical relationship clearly.

// ID Account type parent ID // your acompany 1 0 // FB-44-91-AE-AC-73-2B-4D-9F-01-B1-E2-16-D3-CB-1B department01 1 RMB // your department03 1 FB-44-91-AE-AC-73-2B-4D-9F-01-B1-E2-16-D3-CB-1B // E3-AD-47-45-38-64-02-4D-B9-83-2C-50-67-50-4F-92 ZW 2 RMB // your zhongw 2 FB-44-91-AE-AC-73-2B-4D-9F-01-B1-E2-16-D3-CB-1B // department02 1 rows // 1c-13-fa-66-e4-51-65-49-8b-dc-22-60-32-34-8f-22 Wilson 2 BC-D0-34-85-67-2F-05-4D-B5-77-E3-F4-AD-51-45-02 // export porschev 2 rows

 

Directorysearcher. Filter attribute extension description

Directorysearcher mysearcher = new directorysearcher (entryou, "(objectclass = organizationalunit)"); // query the organizational unit

The second parameter is a filter. You can also enter other filtering conditions as required. The following lists several common

Filtering Conditions Value
User (& (Objectcategory = person) (objectclass = user ))
Computer (Objectcategory = computer)
Group (Objectcategory = Group)
Contact (Objectcategory = contact)
Shared Folder (Objectcategory = volume)
Printer (Objectcategory = printqueue)

For more advanced filtering, see http://msdn.microsoft.com/zh-cn/library/system.directoryservices.directorysearcher.filter (V = vs.80). aspx

 

 

Description of user attribute extension (including graphic attribute comparison)

In this example, only the user has read several attributes. If you have used the ad domain, you should know that there are many attributes that are commonly used.

The following uses the user details in the ad domain to compare the corresponding attribute names.

  • Common Tab

  

ID Tab Item Name Attribute name
Surname (l) Sn
Name (f) Givenname
Display name (s) Displayname
Description (d) Description
Office (c) Physicaldeliveryofficename
I) Initials
7. Telephone number (t) Telephonenumber
Bytes Email (m) Mail
Bytes Web page (W) Wwwhomepage
Bytes Phone number-others (o )... Othertelephone
Bytes Webpage-Other (r )... URL

  

  • Address Tab

  

ID Tab Item Name Attribute name
Country/region (o) CO
Province/Autonomous Region (V) St
City/County (c) L
Sub-district (s) Streetaddress
Mailbox (B) Postofficebox
Zip code (z) Postalcode

  

  • Account tab

  

ID Tab Item Name Attribute name
User Login Name (u) Userprincipalname
User Login Name (earlier than Windows 2000) (W) Samaccountname

  

  • Phone Tab

  

ID Tab Item Name Attribute name
Home Phone (m) Homephone
Pager (P) Pager
Mobile phone (B) Mobile
Fax (f) Facsimiletelephonenumber
IP Phone (I) Ipphone
Note Info
7. Home phone-others (o) Otherhomephone
Bytes Pager-others (t) Otherpager
Bytes Mobile phone-others (B) Othermobile
Bytes Fax-Others (E) Otherfacsimiletelephonenumber
Bytes IP Phone-others (r) Otheripphone

 

  • Organization Tab

  

ID Tab Item Name Attribute name
Company (c) Company
Department (d) Department
Title (j) Title
Manager-Name (N) Manager
Direct subordinate (E) Directreports

  

Some other attributes are not listed. You can output directoryentry. properties. propertynames cyclically.

For example, using objectsid is also an important attribute for a user and will be used when setting Windows sharing!

 

Sample download

Example download: http://files.cnblogs.com/zhongweiv/SynchronousAD.zip

The sample code is relatively simple and can be downloaded as needed. Let's take a look at it. ^_^!

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.