TechShri from Shriniwas Wani

Custom Search

23 June, 2006

LDAP Class

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
///
/// Summary description for LDAPAuthentication
///

public class LDAPAuthentication
{
#region Private Members
///
/// Data Table for storing user info
///

private DataTable _UserInfoTable;
///
/// Ldap Path
///

private string _LDAPPath;
///
/// User Id for accessing LDAP
///

private string _LDAPUid;
///
/// Password Id for accessing LDAP
///

private string _LDAPPwd;
///
/// To specify maximum number of records to be ruterned, 0 for default
///

private int _MaxNumberOfRecords;
///
/// Gets the set of properties retrieved during the search. The default is an empty StringCollection, which retrieves all properties
///

private StringCollection _PropertiesToLoad;
///
/// A SortOption that specifies a SortDirection value and a DirectoryEntry.Name on which to sort
///

private SortOption _Sort;
///
/// filter attribute
///

private string _filterAttribute;
#endregion
#region Public Properties
///
/// Get / Set Data Table for storing user info
///

public DataTable UserInfoTable
{
get { return _UserInfoTable; }
set { _UserInfoTable = value; }
}
///
/// Get / Set Ldap Path
///

public string LDAPPath
{
get { return _LDAPPath; }
set { _LDAPPath = value; }
}
///
/// Get / Set User Id for accessing LDAP
///

public string LDAPUid
{
get { return _LDAPUid; }
set { _LDAPUid = value; }
}
///
/// Get / Set Password Id for accessing LDAP
///

public string LDAPPwd
{
get { return _LDAPPwd; }
set { _LDAPPwd = value; }
}
///
/// Get / Set To specify maximum number of records to be ruterned, 0 for default
///

public int MaxNumberOfRecords
{
get { return _MaxNumberOfRecords; }
set { _MaxNumberOfRecords = value; }
}
public string FilterAttribute
{
get { return _filterAttribute ; }
set { _filterAttribute = value ; }
}
///
/// Get / Set Gets the set of properties retrieved during the search. The default is an empty StringCollection, which retrieves all properties
///

public StringCollection PropertiesToLoad
{
get { return _PropertiesToLoad; }
set { _PropertiesToLoad = value; }
}
///
/// Get / Set A SortOption that specifies a SortDirection value and a DirectoryEntry.Name on which to sort
///

public SortOption Sort
{
get { return _Sort; }
set { _Sort = value; }
}
#endregion
public LDAPAuthentication()
{
_LDAPPath = "LDAP://cyb-ms.com/DC=cyb-ms,DC=com" ;
}

public LDAPAuthentication(string LdapPath, string Uid, string Pwd)
{
_LDAPPath = LdapPath;
_LDAPUid = Uid;
_LDAPPwd = Pwd;
_Sort = new SortOption("sn", System.DirectoryServices.SortDirection.Ascending);
_PropertiesToLoad = new StringCollection();
_PropertiesToLoad.Add("samaccountname");
_PropertiesToLoad.Add("mail");
_PropertiesToLoad.Add("givenname");
_PropertiesToLoad.Add("sn");
_MaxNumberOfRecords = 0;
_UserInfoTable = new DataTable("UserInfo");
_UserInfoTable.Columns.Add("UserID");
_UserInfoTable.Columns.Add("FirstName");
_UserInfoTable.Columns.Add("LastName");
}
public bool IsAuthenticated(string username)
{
FilterAttribute = string.Empty;
DirectoryEntry entry = new DirectoryEntry("");
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject; //TODO: NO USE OF THIS LINE, can remove
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
LDAPPath = result.Path;
FilterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
return false;
}
return true;
}

public string GetGroups()
{
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("samaccountname");
DataColumn dc2 = new DataColumn("givenname");
DataColumn dc3 = new DataColumn("sn");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
LDAPPath = ConfigurationManager.AppSettings["ldapPath"]; //"LDAP://cyb-ms.com/DC=cyb-ms,DC=com";
string domain = ConfigurationManager.AppSettings["domain"];
//string username = ConfigurationManager.AppSettings["username"];
//string pwd = ConfigurationManager.AppSettings["pwd"];
//string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry("");
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(&(objectClass=person)(((cn=*" + FilterAttribute + "*))( sn=*" + FilterAttribute + "*)))";
search.CacheResults = false;

//search.Filter = "(SAMAccountName=" + FilterAttribute + ")";
// search.PropertiesToLoad.Add("cn");
// search.PropertiesToLoad.Add("memberOf");
search.PropertiesToLoad.Add("SAMAccountName");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
SearchResultCollection resCollection = search.FindAll();
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}


public DataTable GetAllUsers(string strSearch)
{
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("samaccountname");
DataColumn dc2 = new DataColumn("givenname");
DataColumn dc3 = new DataColumn("sn");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
LDAPPath = ConfigurationManager.AppSettings["ldapPath"]; //"LDAP://cyb-ms.com/DC=cyb-ms,DC=com";
string domain = ConfigurationManager.AppSettings["domain"];
string username = ConfigurationManager.AppSettings["username"];
string pwd = ConfigurationManager.AppSettings["pwd"];
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(LDAPPath, domainAndUsername, pwd, AuthenticationTypes.ReadonlyServer);
DirectorySearcher search = new DirectorySearcher(entry);
//search.Filter = "(cn=" + FilterAttribute + ")";
//search.Filter = String.Format("((&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", strFirstName, strLastName);
//search.Filter = "sn=wa*" ;//, strLastName);
search.Filter = "(&(objectClass=person)(((cn=*" + strSearch + "*))( sn=*" + strSearch + "*)))";
//search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResultCollection resultCollection = search.FindAll();
if (resultCollection != null)
{
foreach (SearchResult result in resultCollection)
{
//StringCollection sc = AllProps(result.Properties);
if (result.Properties.Contains("samaccountname") result.Properties.Contains("givenname") result.Properties.Contains("sn"))
{
DataRow dr = dt.NewRow();
dr[0] = (result.Properties.Contains("samaccountname")) ? (string)result.Properties["samaccountname"][0].ToString().Trim() : string.Empty;
//string Email = (string)result.Properties["mail"][0].ToString().Trim();
dr[1] = (result.Properties.Contains("givenname")) ? ((string)result.Properties["givenname"][0].ToString().Trim()) : string.Empty;
dr[2] = (result.Properties.Contains("sn")) ? ((string)result.Properties["sn"][0].ToString().Trim()) : string.Empty;
dt.Rows.Add(dr);
// this.UserInfoTable.Rows.Add(UserID, FirstName, LastName);
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return dt; //groupNames.ToString();
}

}