新版AD操作处理类
关于ASP.NET如何获取AD中的详细用户信息等方法的实现。其中主要依托CLR:DirectoryServices.
此类如果对外转载请注意作者版权:杨云    2006

/********************************************************************************
**
**  File  Name:  AdHandler.cs
**  Creator:  杨云
**  Create  date:  
**  Lastest  Modifier:  
**  Lastest  Modify  date:  
**  Description:  
**  
**  Version  number:  1.0.0.0
*********************************************************************************/
using  System;
using  System.Data;
using  System.Collections;
using  System.Configuration;
using  System.DirectoryServices;
using  System.Text.RegularExpressions;

namespace  Tool
{
public  class  ActiveDirectoryCenter
{  
protected  Hashtable  m_deptHeadGroup;
protected  Hashtable  m_areaMapping;
protected  string  m_domainUser;
protected  string  m_password;
protected  string  m_path;
protected  string  m_groupPath;

public  ActiveDirectoryCenter()
{
Initialize();
}

protected  void  Initialize()
{
m_deptHeadGroup  =  
(Hashtable)ConfigurationSettings.GetConfig("deptHeadGroupSetting");
m_areaMapping  =  (Hashtable)ConfigurationSettings.GetConfig("areaMapping");

IDictionary  identity  =  
(IDictionary)ConfigurationSettings.GetConfig("identity");
m_domainUser  =  identity["userId"].ToString();
m_password  =  identity["password"].ToString();
m_path  =  identity["path"].ToString();
m_groupPath  =  identity["groupPath"].ToString();  
}

#region  GetUser
///  <summary>
///  Get  user's  information  by  user's  id
///  </summary>
///  <param  name="userID">User's  id</param>
///  <returns>Datatable  containning  
'Area','Domain','UserID','DisplayName','Department','EmailAddress','MemberOf'</returns>
public  DataTable  GetUser(string  userID)  
{
DataTable  result  =  new  DataTable();
result.Columns.AddRange(new  DataColumn[]{
new  DataColumn("Area",typeof(String)),
new  DataColumn("Domain",typeof(String)),
new  DataColumn("UserID",typeof(String)),
new  DataColumn("FullName",typeof(String)),
new  DataColumn("DeptShortName",typeof(String)),
new  DataColumn("EmailAddress",typeof(String)),
new  DataColumn("MemberOf",typeof(String)),
new  DataColumn("UserName",typeof(String)),
new  DataColumn("Rank",typeof  (String))
});

string  
propDistinguishedname="",propArea="",propDomain="",propUserID="",propDisplayName="",propDepartment="",propEmailAddress="",propMemberof="",  propFullName="";


//获得基本信息  
string  filter  =  
string.Format("(&(objectCategory=person)(mailnickname={0}))",userID);
string[]  propertiesToLoad  =  new  
string[]{"distinguishedname","mailnickname","displayName","mail"};

SearchResult  r  =  SearchOne(filter,  propertiesToLoad);
if(r  ==  null)
{
return  result;
}
propDistinguishedname  =    Getvalue(r,"distinguishedname");
propUserID  =  Getvalue(r,"mailnickname");  
propDomain  =  ParseDomain(propDistinguishedname);
propDisplayName  =  Getvalue(r,"displayName");  
propDepartment  =  ParseDepartment(propDisplayName);
propArea  =  ParseArea(propDisplayName,  propDomain);  
propEmailAddress  =  Getvalue(r,"mail");
propFullName  =  ParseFullName(propDisplayName);

//搜索Group
filter  =  string.Format(  
"(&(objectClass=group)(member={0}))",propDistinguishedname);//group对象

SearchResultCollection  rs  =  SearchBatch(filter,  new  
string[]{"displayname"});
foreach(SearchResult  entry  in  rs)
{
string  t  =  Getvalue(entry,"displayname");
if  (t!="")
{
propMemberof  +=  t  +  ",";  
}
}  
if(propMemberof  !=  string.Empty)
{
propMemberof  =  propMemberof.Substring(0,propMemberof.Length-1);  
}  

result.Rows.Add(new  
string[]{propArea,propDomain,propUserID,propFullName,propDepartment,propEmailAddress,propMemberof,propDisplayName});
return  result;
}
#endregion

#region  GetUserGroup
///  <summary>
///  Get  the  user  or  group  by  the  domain  and  keyword  of  display  name
///  </summary>
///  <param  name="keyword">Keyword  of  display  name</param>
///  <returns>Datatable  containning  'DisplayName','Domain'  and  
'UserID'</returns>
public  DataTable  GetUserGroup(string  keyword)
{
DataTable  result  =  new  DataTable();
result.Columns.AddRange(new  DataColumn[]{
new  DataColumn("DisplayName",typeof(String)),
new  DataColumn("Domain",typeof(String)),
new  DataColumn("UserID",typeof(String)),
new  DataColumn("userAccountControl",typeof(String))  
});

string  propDisplayName  =  "";
string  propDomain  =  "";
string  propUserID  =  "";
string  userAccountControl  =  "";
string  filter  =  string.Format(  
"(&(|(objectCategory=person)(objectClass=group))(displayname=*{0}*))",keyword);//user对象  

SearchResultCollection  rsGroup  =  SearchBatch(filter,
new  string[]{"displayname",  "distinguishedname",  "mailnickname",  
"userAccountControl"});
foreach(SearchResult  entry  in  rsGroup)
{  
propDisplayName  =  Getvalue(entry,"displayname");
propDomain  =  ParseDomain(Getvalue(entry,"distinguishedname"));
propUserID  =  Getvalue(entry,"mailnickname");
userAccountControl  =  Getvalue(entry,"userAccountControl");
if(userAccountControl.Trim()  !=  "66050")
{
result.Rows.Add(new  
string[]{propDisplayName,propDomain,propUserID,userAccountControl});
}
}

return  result;
}
#endregion

#region  GetDeptHeadGroup
///  <summary>
///  Get  the  department's  head  group  by  area
///  </summary>
///  <param  name="area">The  area  like  cn  or  cn.cd</param>
///  <returns>The  group's  display  name</returns>
public  string  GetDeptHeadGroup(string  area)
{
if(!m_deptHeadGroup.Contains(area.ToLower()))
{
throw  new  Exception("The  area  dose  not  exist!");
}
return  m_deptHeadGroup[area.ToLower()].ToString();
}
#endregion

#region  GetGroupMember

///  <summary>
///  传入一个Group的名字,获取里面的所有Member
///  </summary>
///  <param  name="strGroupName">group的name,形如:"**  microsoft(cn.sh)";</param>
///  <param  name="bIncludeSubGroup">是否包含其子group的member</param>
///  <returns>Datatable  containning  'DisplayName','EmailAddress'  and  
'UserID'</returns>
public  DataTable  GetGroupMember(string  strGroupName,bool  bIncludeSubGroup)
{  
DataTable  resultTable  =  new  DataTable();
resultTable.Columns.AddRange(new  DataColumn[]{
new  DataColumn("DisplayName",typeof(String)),
new  DataColumn("EmailAddress",typeof(String)),
new  DataColumn("UserID",typeof(String)),
});
string  strPrex  =  m_groupPath;
string  strPath  =m_path;
string  strUser  =  m_domainUser;
string  strPassword  =  m_password;

string  filter  =  string.Format(  
"(&(objectClass=group)(|(displayname={0})(name={0})))",strGroupName);//搜索name或displayname为指定值的group对象  
SearchResult  result  =  this.SearchOne(filter,  null);  
if(result  ==  null)
{
return  resultTable;
}
Stack  stack  =  new  Stack();  //因为要搜索子Group,这里引入stack来支持遍历  
stack.Push(result.Properties["adspath"][0].ToString());

Hashtable  htResult  =  new  Hashtable();
while(stack.Count  !=  0)
{
using(DirectoryEntry  cur  =  new  DirectoryEntry())
{
cur.Path  =  (string)stack.Pop();  
cur.Username  =  strUser;
cur.Password  =  strPassword;
foreach(string  strProp  in  cur.Properties["member"])//搜索member属性
{
using(DirectoryEntry  member  =  new  DirectoryEntry())
{
member.Path  =  strPrex  +  strProp.ToString();
member.Username  =  strUser;
member.Password  =  strPassword;
if(member.SchemaClassName.ToLower().Equals("user"))//user对象
{
if(!htResult.ContainsKey(member.Guid))//一个user可以在多个group下,因此可能重复,这里检查是否重复
{
htResult.Add(member.Guid,  
member.Properties["displayName"][0].ToString());//建议还要保存member.Path,这样可以很方便重构对应的DirectoryEntry来获得其他数据
string  propDisplayName  =  Getvalue(member,"displayname");
string  propEmailAddress  =  Getvalue(member,"mail");
string  propUserID  =  Getvalue(member,"mailnickname");
resultTable.Rows.Add(new  
string[]{propDisplayName,propEmailAddress,propUserID});
}
}
else  if(member.SchemaClassName.ToLower().Equals("group")  &&  
bIncludeSubGroup)//group对象
{
stack.Push(member.Path);
}
}
}
}  
}  
return  resultTable;
}

#endregion

#region  Protected  Method

protected  SearchResult  SearchOne(string  filter,  string[]  propertiesToLoad)
{
DirectorySearcher  searcher  =  null;
try
{
searcher  =  GetSearcher(filter,  propertiesToLoad);
return  searcher.FindOne();
}
finally
{
if(searcher  !=  null)
{
if(searcher.SearchRoot  !=  null)
{
searcher.SearchRoot.Dispose();
}
searcher.Dispose();
}
}
}

protected  SearchResultCollection  SearchBatch(string  filter,  string[]  
propertiesToLoad)
{
DirectorySearcher  searcher  =  null;
try
{
searcher  =  GetSearcher(filter,  propertiesToLoad);
return  searcher.FindAll();
}
finally
{
if(searcher  !=  null)
{
if(searcher.SearchRoot  !=  null)
{
searcher.SearchRoot.Dispose();
}
searcher.Dispose();
}
}
}

protected  DirectorySearcher  GetSearcher(string  filter,  string[]  
propertiesToLoad)
{  
DirectorySearcher  searcher  =  new  DirectorySearcher();  
searcher.SearchRoot  =  new  DirectoryEntry(m_path,  m_domainUser,  
m_password);;
searcher.SearchScope  =  SearchScope.Subtree;
searcher.Filter  =  filter;
if(propertiesToLoad  !=  null)
{
searcher.PropertiesToLoad.AddRange(propertiesToLoad);
}

return  searcher;
}

protected  string  ParseDomain(string  distinguishedname)
{
if(distinguishedname  ==  null  ||  distinguishedname.Trim().Length  ==  
0)return  "";

Regex  reg  =  new  Regex  (  @"(DC|dc)\s*=\s*(?<DC>[^,]+)");
Match  m  =  reg.Match(distinguishedname);

return  m.Groups["DC"].value;  
}

protected  string  ParseDepartment(string  displayname)
{
if(displayname  ==  null  ||  displayname.Trim().Length  ==  0)
{
return  "";
}

Regex  reg  =  new  Regex(@"\(\s*(?<Department>[^.]+.[^.]+).[^.]+\)");
Match  m  =reg.Match(displayname);

return  m.Groups["Department"].value;
}

protected  string  ParseFullName(string  displayname)
{
if(displayname  ==  null  ||  displayname.Trim().Length  ==  0)
{
return  "";
}
Regex  reg  =  new  Regex(@"([a-zA-Z]*)\.[a-zA-Z]*\.([a-zA-Z]*)");
Match  m  =reg.Match(displayname);

return  m.Groups[1].value  +  "  "  +  m.Groups[2].value;
}

protected  string  ParseArea(string  displayname,  string  domain)
{
if(displayname  ==  null  ||  displayname.Trim().Length  ==  0)
{
return  "";
}
string[]  arrayStr  =  displayname.Split(new  char[]{'.'});
if(arrayStr[3]  !=  null  &&  
m_areaMapping.Contains(arrayStr[3].Trim().ToLower()))
{
return  m_areaMapping[arrayStr[3].Trim().ToLower()].ToString();
}  
return  m_areaMapping[domain].ToString();
}

protected  string  Getvalue(DirectoryEntry  entry,string  strProp)
{
string  strvalue  ;
if(entry.Properties[strProp]  ==  null  ||  entry.Properties[strProp].Count  
==  0)
{
strvalue  =  "";
}
else
{
strvalue  =  entry.Properties[strProp][0].ToString();
}

return  strvalue;
}

protected  string  Getvalue(SearchResult  result,string  strProp)
{
string  strvalue;
if(result.Properties[strProp]  !=  null  &&    
result.Properties[strProp].Count  !=  0)
{
strvalue  =    result.Properties[strProp][0].ToString();
}
else
{
strvalue  =  "";
}

return  strvalue;
}  
#endregion

}
}

posted on 2008-11-14 11:04  yxbsmx  阅读(318)  评论(0编辑  收藏  举报