Use the NET class and LDAP to query Active Directory

Source: Internet
Author: User


Introduction
This article describes how to use it. . NET Framework manages resources in Windows Active Directory Service. Microsoft provides the Active Directory Service Interface (ADSI), which can be used with many vendors, including IIS (Internet Information Service), LDAP (Lightweight Directory Access Protocol ), winNT and Novell NetWare Directory Service (NDS ),
Because my purpose is to demonstrate the use of NET DirectoryService Classes, I restrict the demo project to query computers with some common resources. Users and printers are located in the domain of the user's machine, it also shows the efficiency, the difficulty of Active Directory Service, and the ability of Active Directory to retrieve objects.

I also use LDAP in this demonstration, because I want to know this protocol, because it is a platform-independent protocol, which will be useful.

There are different ways to query the Active Directory Service in the C # Program
Use ADSI to communicate with each other through COM. In this case, on the Visual Studio C # project "add reference...", select the active DS type library from the list on the "COM" tab. Add the ActiveDs statement to the beginning of the file or use a fully qualified class name to access the ADSI function.
Use the Active Directory Service OLEDB provider (ADsDSOObject ). This method serves as a useful supplement to the Active Directory of the linked Server in SQL Server. In an article on the scope of this course, I will discuss how to query Active Directory using the ADS OLEDB provider in different articles.
. The class provided by the System. DirectoryServices namespace under. NET. To access the references for adding System. DirectoryServices. dll to these classes. This article demonstrates this method.
. NET System. DirectoryServices namespace
The System. DirectoryServices namespace provides two important classes: DirectoryEntry's DirectorySearcher work and Active Directory. Resources of the DirectoryEntry class are in Active Directory, And the DirectorySearcher class is used to query Active Directory. The class in the namespace. . NET Security and collection classes support the master class mentioned above.
Add your System. DirectoryServices to your reference. In the Add reference dialog box, select System. DirectoryServices. dll.

Filtering string in LDAP format
The DirectorySearcher class uses a search root Directory, which is a server that starts searching and LDAP filter strings (similar to SQL IN THE where clause) to query Active Directory resources. The format of the LDAP filter string is similar to LISP. The conditions enclosed in brackets and the first two conditions of the operator. For example, the declaration of (& (A) (B) means that A and B still remember the brackets. It should be interpreted as another example (| (& (A) (B) (C) (A and B) or (C ).

OLAP condition statements are composed of Active Directory attributes, such as name, objectCategory, objectClass, printerName, and ListedName. For example, the condition for querying the printer list is that (objectCategory = printQueue) objectCategory is an attribute, while printQueue is a printer Resource Allocated to the Active Directory with a pre-value. Query LDAP queries of all printer start characters 'G' (& (PrintQueue of objectCategory attribute) (= G *)) the values observed in the above filter are not enclosed by quotation marks ('or.

Use Code
This project describes how to query the Active Directory Service and obtain different objects. Query and use LDAP. . NET class only uses the QueryObjectsByNETClasses () and GetFilterString () methods.

The following code creates a DirectorySearcher object in the QueryObjectsByNETClasses () method, and sets the attribute search based on the user's preferences. Different descriptions are comments in the code. Only the PropertiesToLoad attribute "name" added to the DirectorySearcher class saves time, because we only care about the name and objectClass of the object returned in the search list.

 

DirectorySearcher ds = new DirectorySearcher ();
Ds. SearchRoot = new DirectoryEntry ("");
// Start searching from local domain
Ds. Filter = GetFilterString ();
// Get the LDAP filter string based on selections on the form
Ds. PropertyNamesOnly = true;
// This will get names of only those
// Properties to which a value is set
Ds. PropertiesToLoad. Add ("name ");

// (PageSize) Maximum number of objects
// The server will return per page
// In a paged search. Default is 0, I. e. no paged search
If (ObjsPerPage. Text. Length> 0)
Ds. PageSize = Int32.Parse (ObjsPerPage. Text );

// (ServerPageTimeLimit) the amount of time the server
// Shocould observe to search a page of results
// Default is-1, I. e. search indefinitely
If (PageTimeLimit. Text. Length> 0)
Ds. ServerPageTimeLimit = new TimeSpan (long) (Decimal. Parse (
PageTimeLimit. Text) * TimeSpan. TicksPerSecond ));

// (SizeLimit) maximum number of objects the server
// Returns in a search
// Default is 0-interpreted as server
// Set default limit of 1000 entries
If (ObjsToFetch. Text. Length> 0)
Ds. SizeLimit = Int32.Parse (ObjsToFetch. Text );

// (ServerTimeLimit) amount of time that the server
// Shocould observe in a search
// Default is-1 interpreted as server default limit of 120 seconds
If (TotalTimeLimit. Text. Length> 0)
Ds. ServerTimeLimit = new TimeSpan (long) (Decimal. Parse (
TotalTimeLimit. Text) * TimeSpan. TicksPerSecond ));

// (SearchScope) option to search one level or complete subtree
// Default is Subtree, so set this option only if oneLevel is selected
If (searchOptionCB. SelectedIndex = 1)
Ds. SearchScope = SearchScope. OneLevel;

// (CacheResults) property by default is true
Ds. CacheResults = CacheResultsCB. Checked;

Ds. ReferralChasing = ReferralChasingOption. None;

If (SortResultsCB. Checked)
Ds. Sort = new SortOption ("name", SortDirection. Ascending );
The FormFilter () and GetFilterString () functions are used to form an LDAP query string (see the following description about the format of these strings in the LDAP filter string format section ). We will focus on the pre-placed & | operation list. If you have any questions, refer to the Active Directory architecture of MSDN to form a complete set of attributes for different objects.

 

// Form a filter string for the search in LDAP format
Private string FormFilter (string objectCategory, string filter)
{
String result;
Result = String. Format ("(& (objectCategory = {0}) (name = {1 }))",
ObjectCategory, filter );
Return result;
}

// This function forms the filter string based on the selected
// Objects on the form
Private string GetFilterString ()
{
// Form the filter string for directory search
String filter = "";
If (UsersCB. Checked)
Filter + = FormFilter ("user", UsersFilter. Text );
If (ComputersCB. Checked)
Filter + = FormFilter ("computer", ComputersFilter. Text );
If (PrintersCB. Checked)
Filter + = FormFilter ("printQueue", PrintersFilter. Text );

// Add all the above filter strings
Return "(|" + filter + ")";
}
 

Key points and precautions
The attributes of the object class using the objectCategory attribute, rather than when possible. Two things related to this issue are mentioned in the Active Directory document:
The attributes of objectClass can have multiple values. This may be a problem, especially if you retriving the object class. You can have multiple values!
ObjectCategory is an index attribute in Active Directory. Therefore, you can use the objectCategory attribute to speed up the query.
The second point is more important, because all the examples show the objectClass used by MSDN, and using objectCategoryProperty will speed up the query!

If the list query is too large, it may time out. So don't be surprised if your query does not return the complete list. Note that you cannot set a value. The default value of ServerTimeLimit is greater than 120 seconds! Therefore, if all the objects and directories you are looking for are too large, it is best to query the number of times and incrementally change your LDAP filter string (for example, A *, B *..) combined results.
Try to use the DirectorySearcher with PropertiesToLoad and PropertyNamesOnly performance. If you know what properties you are, try to search. If PropertyNamesOnly is set to true, the query will get the names set for these attribute values. The point name and surname attribute can be loaded to PropertiesToLoad to reduce the read time. By default, PropertiesToLoad is set to all the properties obtained in an empty StringCollection, and PropertyNamesOnly is set to false to retrieve the names of all properties, even if no value is set. For example. In my demo, I will load the "name" attribute and set PropertyNamesOnly to true. Please note that even if no property of the specified objectClass and objectCategory attributes is automatically loaded, an object is taken out.
By default, all results obtained in Active Directory are cached. Set the DirectorySearcher of the CacheResults property to false to refresh the object and cache it on the local computer.
 

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.