En ocasiones es útil hacer consultas al directorio activo ya sea para buscar usuarios u otros objetos que estén en el directorio activo.
En seguida el código.
using System;
using System.Collections.Generic; using System.Collections; using System.DirectoryServices; using System.Data; using System.Text; namespace F.Net.ActiveDirectory { public struct ADColumns { #region Active Directory Columns public const string accountExpires = "accountExpires"; public const string altSecurityIdentities = "altSecurityIdentities"; public const string badPasswordTime = "badPasswordTime"; public const string badPwdCount = "badPwdCount"; public const string c = "c"; public const string cn = "cn"; public const string co = "co"; public const string codePage = "codePage"; public const string company = "company"; public const string countryCode = "countryCode"; public const string department = "department"; public const string description = "description"; public const string directReports = "directReports"; public const string displayName = "displayName"; public const string dsCodePropagationData = "dsCodePropagationData"; public const string facsimileTelephoneNumber = "facsimileTelephoneNumber"; public const string garbageCollPeriod = "garbageCollPeriod"; public const string givenName = "givenName"; public const string homeDirectory = "homeDirectory"; public const string homeDrive = "homeDrive"; public const string homeMDB = "homeMDB"; public const string homePhone = "homePhone"; public const string initials = "initials"; public const string instanceType = "instanceType"; public const string ipPhone = "ipPhone"; public const string lastLogoff = "lastLogoff"; public const string lastLogon = "lastLogon"; public const string legacyExchangeDN = "legacyExchangeDN"; public const string lmPwdHistory = "lmPwdHistory"; public const string logonCount = "logonCount"; public const string mail = "mail"; public const string managedObjects = "managedObjects"; public const string manager = "manager"; public const string maxPwdAge = "maxPwdAge"; public const string maxStorage = "maxStorage"; public const string memberOf = "memberOf"; public const string mobile = "mobile"; public const string name = "name"; public const string notes = "notes"; public const string ntPwdHistory = "ntPwdHistory"; public const string objectGUID = "objectGUID"; public const string objectSid = "objectSid"; public const string otherFacsimileTelephoneNumber = "otherFacsimileTelephoneNumber"; public const string otherIpPhone = "otherIpPhone"; public const string otherMailbox = "otherMailbox"; public const string otherMobile = "otherMobile"; public const string otherPager = "otherPager"; public const string otherTelephone = "otherTelephone"; public const string pager = "pager"; public const string PasswordExpirationDate = "PasswordExpirationDate"; public const string physicalDeliveryOfficeName = "physicalDeliveryOfficeName"; public const string postalAddress = "postalAddress"; public const string postalCode = "postalCode"; public const string postOfficeBox = "postOfficeBox"; public const string primaryGroupID = "primaryGroupID"; public const string profilePath = "profilePath"; public const string pwdLastSet = "pwdLastSet"; public const string sAMAccountName = "sAMAccountName"; public const string sAMAccountType = "sAMAccountType"; public const string scriptPath = "scriptPath"; public const string sIDHistory = "sIDHistory"; public const string sn = "sn"; public const string st = "st"; public const string street = "street"; public const string streetAddress = "streetAddress"; public const string telephineNumber = "telephineNumber"; public const string title = "title"; public const string unicodePwd = "unicodePwd"; public const string url = "url"; public const string userAccountControl = "userAccountControl"; public const string userCertificate = "userCertificate"; public const string userPrincipalName = "userPrincipalName"; public const string userSharedFolder = "userSharedFolder"; public const string userWorkstations = "userWorkstations"; public const string wWWHomePage = "wWWHomePage"; #endregion } public class Query { #region Private Members private string objectTypeSearch = "objectClass"; private bool _GetAllColumns = false; private DirectorySearcher ds ; private string strFilter; private string objCat; private ArrayList filters; private ArrayList columns; private ArrayList _ResultColumns; private string domain; #endregion #region Public Properties public string ObjectTypeSearch{ set{this.objectTypeSearch = value;} get{return this.objectTypeSearch;} } /// <summary> /// /// </summary> public bool GetAllColumns{ set{this._GetAllColumns = value;} get{return this._GetAllColumns ;} } /// <summary> /// /// </summary> public string Domain{ set{this.domain=value;} get{return this.domain;} } /// <summary> /// /// </summary> public string ObjectCategory { set{this.objCat=value;} get{return this.objCat;} } /// <summary> /// /// </summary> public string Filter { set {this.strFilter=value;} get {return this.strFilter;} } /// <summary> /// /// </summary> public bool CacheResults { set{this.ds.CacheResults = value;} get{return this.ds.CacheResults;} } /// <summary> /// /// </summary> public int PageSize { set{this.ds.PageSize=value;} get{return this.ds.PageSize;} } /// <summary> /// /// </summary> public int SizeLimit { set{this.ds.SizeLimit=value; } get{return this.ds.SizeLimit;} } /// <summary> /// /// </summary> public System.TimeSpan ServerTimeLimit { set{this.ds.ServerTimeLimit =value;} get{return this.ds.ServerTimeLimit;} } /// <summary> /// /// </summary> public System.TimeSpan ServerPageTimeLimit { set{this.ds.ServerPageTimeLimit=value; } get{return this.ds.ServerPageTimeLimit;} } /// <summary> /// /// </summary> public System.DirectoryServices.SearchScope SearchScope { set{this.ds.SearchScope = value;} get{return this.ds.SearchScope;} } /// <summary> /// /// </summary> public System.DirectoryServices.ReferralChasingOption ReferralChasing { set{this.ds.ReferralChasing=value;} get{return this.ds.ReferralChasing;} } public ArrayList ResultColumns{ get{return this._ResultColumns;} } #endregion #region Constructors & Initializers /// <summary> /// /// </summary> private void init() { this.filters=new ArrayList(); this.columns=new ArrayList(); this._ResultColumns=new ArrayList(); this.objectTypeSearch = "objectClass"; this.objCat="user"; this.domain=""; ds = new DirectorySearcher(); } /// <summary> /// /// </summary> public Query() { this.init(); } /// <summary> /// /// </summary> /// <param name="ObjectCategory"></param> public Query(string ObjectCategory) { this.init(); this.objCat=ObjectCategory; } #endregion #region Filter List Methods /// <summary> /// /// </summary> /// <param name="filter"></param> public void AddFilter(string filter) { this.filters.Add(filter); } /// <summary> /// /// </summary> /// <param name="filter"></param> public void RemoveFilter(string filter) { this.filters.Remove(filter); } /// <summary> /// /// </summary> /// <param name="index"></param> public void RemoveFilterAt(int index) { if (index<this.filters.Count) this.filters.RemoveAt(index); } /// <summary> /// /// </summary> /// <returns></returns> public int CountFilters() { return this.columns.Count; } #endregion #region Column List Methods /// <summary> /// /// </summary> /// <param name="column"></param> public void AddResultColumn(string column) { this.columns.Add(column); } /// <summary> /// /// </summary> /// <param name="column"></param> public void RemoveColumn(string column) { this.columns.Remove(column); } /// <summary> /// /// </summary> /// <param name="index"></param> public void RemoveColumnAt(int index) { if (index<this.columns.Count) this.columns.RemoveAt(index); } /// <summary> /// /// </summary> /// <returns></returns> public int CountColumns() { return this.columns.Count; } /// <summary> /// /// </summary> /// <param name="de"></param> /// <returns></returns> public Hashtable EnumerateColumns(DirectoryEntry de) { Hashtable ht=new Hashtable(); System.Collections.IDictionaryEnumerator en=de.Properties.GetEnumerator(); while (!en.Current.Equals(null)) { ht.Add(en.Key,en.Value ); en.MoveNext(); } return ht; } #endregion #region Updating Methods /// <summary> /// /// </summary> /// <param name="de"></param> /// <param name="PropertyName"></param> /// <param name="Value"></param> public void UpdateProperty(DirectoryEntry de, string PropertyName, string Value ){ try { de.Properties[PropertyName].Value = Value; de.CommitChanges (); } catch{ throw; } } #endregion #region Filter Expression Building & Search Methods /// <summary> /// /// </summary> /// <returns></returns> public string GetFilterExpression() { if (filters.Count > 0 ) { strFilter = "(&(" + objectTypeSearch + "=" + objCat + ")"+(filters.Count>1?"(":"")+(filters.Count>1?"|":""); foreach(string expre in filters) { strFilter += "(" + expre + ")"; } strFilter += ")"+(filters.Count>1?")":""); } return strFilter; } /// <summary> /// /// </summary> /// <param name="de"></param> /// <returns></returns> public string[] ADEntryToArray(DirectoryEntry de) { string[] ret; int i; if (_GetAllColumns) { ret=new string[de.Properties.PropertyNames.Count]; i=0; foreach (string column in de.Properties.PropertyNames){ try { ret[i] = de.Properties[column].Value.ToString() ; i++; } catch { ret[i] = ""; } } } else { ret=new string[columns.Count]; i=0; foreach (string column in columns) { try { ret[i] = de.Properties[column].Value.ToString() ; i++; } catch { ret[i] = ""; } } } return ret; } /// <summary> /// /// </summary> /// <param name="de"></param> /// <param name="dt"></param> /// <returns></returns> public void ConfigureTable(DirectoryEntry de, ref DataTable dt) { _ResultColumns.Clear(); if (_GetAllColumns) { foreach (string column in de.Properties.PropertyNames) { try { dt.Columns.Add(column); _ResultColumns.Add(column); } catch { throw; } } } else { foreach (string column in columns) { try { dt.Columns.Add(column); _ResultColumns.Add(column); } catch { throw; } } } } /// <summary> /// /// </summary> /// <returns></returns> public DataTable Search() { try { int i=0; DataTable dt=new DataTable(); if (columns.Count==0) { columns.Add("cn"); columns.Add("sAMAccountName"); columns.Add("mail"); } ds.SearchRoot = new DirectoryEntry(domain); // start searching from local domain ds.Filter = this.GetFilterExpression(); // get the LDAP filter string based on selections on the form ds.PropertyNamesOnly = false; // this will get names of only those properties to which a value is set //ds.PropertiesToLoad.Add("name"); SearchResultCollection src = ds.FindAll(); domain = ds.SearchRoot.Path ; i=0; foreach (SearchResult sr in src) { if (i==0){ ConfigureTable(sr.GetDirectoryEntry(),ref dt); } dt.Rows.Add(ADEntryToArray(sr.GetDirectoryEntry())); i++; } return dt; } catch(Exception ex) { throw ex; } } public ArrayList ReturnAsStringList(string columnSeparator) { ArrayList ret=new ArrayList(); string strItem; DataTable dt=Search(); foreach(DataRow row in dt.Rows ) { strItem=""; foreach(string item in row.ItemArray) strItem+=item+columnSeparator; if (strItem.Length>1) { ret.Add( strItem.Substring(0,strItem.Length-1)); } else ret.Add (""); } return ret; } /// <summary> /// /// </summary> /// <param name="columnSeparator"></param> /// <returns></returns> public ArrayList ReturnAsMatrix(string columnSeparator) { ArrayList ret=new ArrayList(); DataTable dt=Search(); foreach(DataRow row in dt.Rows ) { ret.Add(row.ItemArray.Clone()); } return ret; } #endregion } }