由于Exchange与AD实现了无缝的集成,所以某些对Exchange的开发实际上也是对AD的开发,以下是我在开发过程中的ADHelper类,主要完成AD操作的某些基本功能
在博客堂的Think Different and Think More的blog的文章 http://blog.joycode.com/liuhuimiao/articles/20946.aspx 中有一个ADHelper类,另外在Rainbow中也有一个ADHelper类
using System.DirectoryServices;
using System.Net;
using System.Text;
using CDOEXM;
namespace ExchangeMailTest
{
/// <summary>
/// 实现AD操作的一些常用功能
/// </summary>
public class ADHelper
{
private const string LDAP_IDENTITY = "LDAP://";
#region CreateADAccount
public static DirectoryEntry CreateADAccount(string userName,string password,string organizeName)
{
return CreateADAccount(userName,password,organizeName,string.Empty);
}
public static DirectoryEntry CreateADAccount(string userName,string password,string organizeName,string adGroup)
{
return CreateADAccount(null,null,userName,password,organizeName,adGroup);
}
public static DirectoryEntry CreateADAccount(string adminName,string adminPassword,string userName,
string password,string organizeName,string adGroup)
{
DirectoryEntry entry = null;
if (adminName == null || adminPassword == null)
{
entry = new DirectoryEntry(GetOrganizeNamePath(organizeName));
}
else
{
entry = new DirectoryEntry(GetOrganizeNamePath(organizeName),adminName,
adminPassword,AuthenticationTypes.Secure);
}
//增加用户到AD域中
DirectoryEntry user = entry.Children.Add("CN=" + userName,"user");
user.Properties["sAMAccountName"].Add(userName);
user.CommitChanges();
//设置密码
user.Invoke("SetPassword",new object[]{password});
user.Properties["userAccountControl"].Value = 0x200;
user.CommitChanges();
return user;
}
#endregion
public static string GetDomainPath()
{
using (DirectoryEntry root = new DirectoryEntry())
{
return root.Path;
}
}
public static DirectoryEntry FindObject(string category,string name)
{
return FindObject(null,null,category,name);
}
public static DirectoryEntry FindObject(string adminName,string adminPassword,string category,string name)
{
DirectoryEntry de = null;
if (adminName == null || adminPassword == null)
{
de = new DirectoryEntry(GetDomainPath(),adminName,adminPassword,AuthenticationTypes.Secure);
}
else
{
de = new DirectoryEntry();
}
DirectorySearcher ds = new DirectorySearcher(de);
string queryFilter = string.Format("(&(objectCategory=" + category +")(sAMAccountName={0}))", name);
ds.Filter = queryFilter;
ds.Sort.PropertyName = "cn";
DirectoryEntry userEntry = null;
try
{
SearchResult sr = ds.FindOne();
userEntry = sr.GetDirectoryEntry();
}
finally
{
if (de != null)
{
de.Dispose();
}
if (ds != null)
{
ds.Dispose();
}
}
return userEntry;
}
#region 改变AD用户信息,删除AD帐户
public static void RenameUser(string adminUser,string adminPassword,string oldUserName,string newUserName)
{
DirectoryEntry userEntry = FindObject(adminUser,adminPassword,"user",oldUserName);
userEntry.Rename(newUserName);
userEntry.CommitChanges();
}
public static void SetUserPassword(string userName,string password)
{
SetUserPassword(null,null,userName,password);
}
public static void SetUserPassword(string adminName,string adminPassword,string userName,string password)
{
DirectoryEntry userEntry = FindObject(adminName,adminPassword,"user",userName);
userEntry.Invoke("SetPassword",new object[]{password});
userEntry.CommitChanges();
}
/// <summary>
/// 删除AD账户,使用当前上下文的安全信息,一般用于Windows程序
/// </summary>
/// <param name="userName">用户名称</param>
public static void DeleteADAccount(string userName)
{
DeleteADAccount(null,null,userName);
}
/// <summary>
/// 删除AD账户,使用指定的用户名和密码来模拟,一般用于ASP.NET程序
/// </summary>
/// <param name="adminUser"></param>
/// <param name="adminPassword"></param>
/// <param name="userName">用户名称</param>
public static void DeleteADAccount(string adminUser,string adminPassword,string userName)
{
DirectoryEntry user = FindObject(adminUser,adminPassword,"user",userName);
user.Children.Remove(user);
user.CommitChanges();
}
#endregion
#region 与OU及组有关的操作
/// <summary>
/// 创建OU,需要指定连接到AD的授权信息,一般用于ASPNET程序
/// </summary>
/// <param name="adminName"></param>
/// <param name="adminPassword"></param>
/// <param name="name"></param>
/// <param name="parentOrganizeUnit"></param>
public static DirectoryEntry CreateOrganizeUnit(string adminName,string adminPassword,string name,string parentOrganizeUnit)
{
DirectoryEntry parentEntry = null;
if (adminName == null || adminPassword == null)
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit));
}
else
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit),adminName,adminPassword,
AuthenticationTypes.Secure);
}
DirectoryEntry organizeEntry = parentEntry.Children.Add("OU=" + name,"organizationalUnit");
organizeEntry.CommitChanges();
//parentEntry.CommitChanges();
return organizeEntry;
}
/// <summary>
/// 创建OU,不需要指定连接到AD的授权信息,用于Windows程序
/// </summary>
/// <param name="name"></param>
/// <param name="parentOrganizeUnit"></param>
public static DirectoryEntry CreateOrganizeUnit(string name,string parentOrganizeUnit)
{
return CreateOrganizeUnit(null,null,name,parentOrganizeUnit);
}
/// <summary>
/// 将用户加入到用户组中
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="organizeName">组织名</param>
/// <param name="groupName">组名</param>
/// <exception cref="InvalidObjectException">用户名或用户组不存在</exception>
public static void AddUserToGroup(string userName,string groupName)
{
AddUserToGroup(null,null,userName,groupName);
}
/// <summary>
/// 将用户加入到用户组中
/// </summary>
/// <param name="adminName"></param>
/// <param name="adminPassword"></param>
/// <param name="userName">用户名</param>
/// <param name="groupName">组名</param>
/// <exception cref="InvalidObjectException">用户名或用户组不存在</exception>
public static void AddUserToGroup(string adminName,string adminPassword,string userName,string groupName)
{
DirectoryEntry rootUser = null;
if (adminName == null || adminPassword == null)
{
rootUser = new DirectoryEntry(GetUserPath(),adminName,adminPassword,AuthenticationTypes.Secure);
}
else
{
rootUser = new DirectoryEntry(GetUserPath());
}
DirectoryEntry group = null;
DirectoryEntry user = null;
try
{
group = rootUser.Children.Find("CN=" + groupName);
}
catch (Exception)
{
throw new InvalidObjectException("在域中不存在组“" + groupName + "”");
}
try
{
user = FindObject(adminName,adminPassword,"user",userName);
}
catch (Exception)
{
throw new InvalidObjectException("在域中不存在用户“" + userName + "”");
}
//加入用户到用户组中
group.Properties["member"].Add(user.Properties["distinguishedName"].Value);
group.CommitChanges();
}
#endregion
#region Method 与AD的DN解析有关
/// <summary>
/// 获取所有用户所在的安全组
/// </summary>
/// <returns></returns>
private static string GetUserPath()
{
return GetUserPath(null);
}
/// <summary>
/// 获取所有没有在AD组织中的用户DN名称
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
private static string GetUserPath(string userName)
{
StringBuilder sb = new StringBuilder();
sb.Append(LDAP_IDENTITY);
if (userName != null && userName.Length > 0)
{
sb.Append("CN=").Append(userName).Append(",");
}
sb.Append("CN=Users,").Append(GetDomainDN());
return sb.ToString();
}
/// <summary>
/// 根据用户所在的组织结构来构造用户在AD中的DN路径
/// </summary>
/// <param name="userName">用户名称</param>
/// <param name="organzieName">组织结构</param>
/// <returns></returns>
public static string GetUserPath(string userName,string organzieName)
{
StringBuilder sb = new StringBuilder();
sb.Append(LDAP_IDENTITY);
sb.Append("CN=").Append(userName).Append(",").Append(SplitOrganizeNameToDN(organzieName));
return sb.ToString();
}
/// <summary>
/// 获取域的后缀DN名,如域为ExchangeTest.com,则返回"DC=ExchangeTest,DC=Com"
/// </summary>
/// <returns></returns>
public static string GetDomainDN()
{
// return "DC=ExchangeTest,DC=Com";
//
DirectoryEntry domain = new DirectoryEntry();
return domain.Name;
}
public static string GetOrganizeNamePath(string organizeUnit)
{
StringBuilder sb = new StringBuilder();
sb.Append(LDAP_IDENTITY);
return sb.Append(SplitOrganizeNameToDN(organizeUnit)).ToString();
}
/// <summary>
/// 分离组织名称为标准AD的DN名称,各个组织级别以"/"或"\"分开。如"总部/物业公司/小区",并且当前域为
/// ExchangeTest.Com,则返回的AD的DN表示名为"OU=小区,OU=物业公司,OU=总
/// 部,DC=ExchangeTest,DC=Com"。
/// </summary>
/// <param name="organizeName">组织名称</param>
/// <returns>返回一个级别</returns>
public static string SplitOrganizeNameToDN(string organizeName)
{
StringBuilder sb = new StringBuilder();
if (organizeName != null && organizeName.Length > 0)
{
string[] allOu = organizeName.Split(new char[]{'/','\\'});
for (int i = allOu.Length - 1; i >= 0; i--)
{
string ou = allOu[i];
if (sb.Length > 0 )
{
sb.Append(",");
}
sb.Append("OU=").Append(ou);
}
}
//如果传入了组织名称,则添加,
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(GetDomainDN());
return sb.ToString();
}
#endregion
}
}
using System.Net;
using System.Text;
using CDOEXM;
namespace ExchangeMailTest
{
/// <summary>
/// 实现AD操作的一些常用功能
/// </summary>
public class ADHelper
{
private const string LDAP_IDENTITY = "LDAP://";
#region CreateADAccount
public static DirectoryEntry CreateADAccount(string userName,string password,string organizeName)
{
return CreateADAccount(userName,password,organizeName,string.Empty);
}
public static DirectoryEntry CreateADAccount(string userName,string password,string organizeName,string adGroup)
{
return CreateADAccount(null,null,userName,password,organizeName,adGroup);
}
public static DirectoryEntry CreateADAccount(string adminName,string adminPassword,string userName,
string password,string organizeName,string adGroup)
{
DirectoryEntry entry = null;
if (adminName == null || adminPassword == null)
{
entry = new DirectoryEntry(GetOrganizeNamePath(organizeName));
}
else
{
entry = new DirectoryEntry(GetOrganizeNamePath(organizeName),adminName,
adminPassword,AuthenticationTypes.Secure);
}
//增加用户到AD域中
DirectoryEntry user = entry.Children.Add("CN=" + userName,"user");
user.Properties["sAMAccountName"].Add(userName);
user.CommitChanges();
//设置密码
user.Invoke("SetPassword",new object[]{password});
user.Properties["userAccountControl"].Value = 0x200;
user.CommitChanges();
return user;
}
#endregion
public static string GetDomainPath()
{
using (DirectoryEntry root = new DirectoryEntry())
{
return root.Path;
}
}
public static DirectoryEntry FindObject(string category,string name)
{
return FindObject(null,null,category,name);
}
public static DirectoryEntry FindObject(string adminName,string adminPassword,string category,string name)
{
DirectoryEntry de = null;
if (adminName == null || adminPassword == null)
{
de = new DirectoryEntry(GetDomainPath(),adminName,adminPassword,AuthenticationTypes.Secure);
}
else
{
de = new DirectoryEntry();
}
DirectorySearcher ds = new DirectorySearcher(de);
string queryFilter = string.Format("(&(objectCategory=" + category +")(sAMAccountName={0}))", name);
ds.Filter = queryFilter;
ds.Sort.PropertyName = "cn";
DirectoryEntry userEntry = null;
try
{
SearchResult sr = ds.FindOne();
userEntry = sr.GetDirectoryEntry();
}
finally
{
if (de != null)
{
de.Dispose();
}
if (ds != null)
{
ds.Dispose();
}
}
return userEntry;
}
#region 改变AD用户信息,删除AD帐户
public static void RenameUser(string adminUser,string adminPassword,string oldUserName,string newUserName)
{
DirectoryEntry userEntry = FindObject(adminUser,adminPassword,"user",oldUserName);
userEntry.Rename(newUserName);
userEntry.CommitChanges();
}
public static void SetUserPassword(string userName,string password)
{
SetUserPassword(null,null,userName,password);
}
public static void SetUserPassword(string adminName,string adminPassword,string userName,string password)
{
DirectoryEntry userEntry = FindObject(adminName,adminPassword,"user",userName);
userEntry.Invoke("SetPassword",new object[]{password});
userEntry.CommitChanges();
}
/// <summary>
/// 删除AD账户,使用当前上下文的安全信息,一般用于Windows程序
/// </summary>
/// <param name="userName">用户名称</param>
public static void DeleteADAccount(string userName)
{
DeleteADAccount(null,null,userName);
}
/// <summary>
/// 删除AD账户,使用指定的用户名和密码来模拟,一般用于ASP.NET程序
/// </summary>
/// <param name="adminUser"></param>
/// <param name="adminPassword"></param>
/// <param name="userName">用户名称</param>
public static void DeleteADAccount(string adminUser,string adminPassword,string userName)
{
DirectoryEntry user = FindObject(adminUser,adminPassword,"user",userName);
user.Children.Remove(user);
user.CommitChanges();
}
#endregion
#region 与OU及组有关的操作
/// <summary>
/// 创建OU,需要指定连接到AD的授权信息,一般用于ASPNET程序
/// </summary>
/// <param name="adminName"></param>
/// <param name="adminPassword"></param>
/// <param name="name"></param>
/// <param name="parentOrganizeUnit"></param>
public static DirectoryEntry CreateOrganizeUnit(string adminName,string adminPassword,string name,string parentOrganizeUnit)
{
DirectoryEntry parentEntry = null;
if (adminName == null || adminPassword == null)
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit));
}
else
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit),adminName,adminPassword,
AuthenticationTypes.Secure);
}
DirectoryEntry organizeEntry = parentEntry.Children.Add("OU=" + name,"organizationalUnit");
organizeEntry.CommitChanges();
//parentEntry.CommitChanges();
return organizeEntry;
}
/// <summary>
/// 创建OU,不需要指定连接到AD的授权信息,用于Windows程序
/// </summary>
/// <param name="name"></param>
/// <param name="parentOrganizeUnit"></param>
public static DirectoryEntry CreateOrganizeUnit(string name,string parentOrganizeUnit)
{
return CreateOrganizeUnit(null,null,name,parentOrganizeUnit);
}
/// <summary>
/// 将用户加入到用户组中
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="organizeName">组织名</param>
/// <param name="groupName">组名</param>
/// <exception cref="InvalidObjectException">用户名或用户组不存在</exception>
public static void AddUserToGroup(string userName,string groupName)
{
AddUserToGroup(null,null,userName,groupName);
}
/// <summary>
/// 将用户加入到用户组中
/// </summary>
/// <param name="adminName"></param>
/// <param name="adminPassword"></param>
/// <param name="userName">用户名</param>
/// <param name="groupName">组名</param>
/// <exception cref="InvalidObjectException">用户名或用户组不存在</exception>
public static void AddUserToGroup(string adminName,string adminPassword,string userName,string groupName)
{
DirectoryEntry rootUser = null;
if (adminName == null || adminPassword == null)
{
rootUser = new DirectoryEntry(GetUserPath(),adminName,adminPassword,AuthenticationTypes.Secure);
}
else
{
rootUser = new DirectoryEntry(GetUserPath());
}
DirectoryEntry group = null;
DirectoryEntry user = null;
try
{
group = rootUser.Children.Find("CN=" + groupName);
}
catch (Exception)
{
throw new InvalidObjectException("在域中不存在组“" + groupName + "”");
}
try
{
user = FindObject(adminName,adminPassword,"user",userName);
}
catch (Exception)
{
throw new InvalidObjectException("在域中不存在用户“" + userName + "”");
}
//加入用户到用户组中
group.Properties["member"].Add(user.Properties["distinguishedName"].Value);
group.CommitChanges();
}
#endregion
#region Method 与AD的DN解析有关
/// <summary>
/// 获取所有用户所在的安全组
/// </summary>
/// <returns></returns>
private static string GetUserPath()
{
return GetUserPath(null);
}
/// <summary>
/// 获取所有没有在AD组织中的用户DN名称
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
private static string GetUserPath(string userName)
{
StringBuilder sb = new StringBuilder();
sb.Append(LDAP_IDENTITY);
if (userName != null && userName.Length > 0)
{
sb.Append("CN=").Append(userName).Append(",");
}
sb.Append("CN=Users,").Append(GetDomainDN());
return sb.ToString();
}
/// <summary>
/// 根据用户所在的组织结构来构造用户在AD中的DN路径
/// </summary>
/// <param name="userName">用户名称</param>
/// <param name="organzieName">组织结构</param>
/// <returns></returns>
public static string GetUserPath(string userName,string organzieName)
{
StringBuilder sb = new StringBuilder();
sb.Append(LDAP_IDENTITY);
sb.Append("CN=").Append(userName).Append(",").Append(SplitOrganizeNameToDN(organzieName));
return sb.ToString();
}
/// <summary>
/// 获取域的后缀DN名,如域为ExchangeTest.com,则返回"DC=ExchangeTest,DC=Com"
/// </summary>
/// <returns></returns>
public static string GetDomainDN()
{
// return "DC=ExchangeTest,DC=Com";
//
DirectoryEntry domain = new DirectoryEntry();
return domain.Name;
}
public static string GetOrganizeNamePath(string organizeUnit)
{
StringBuilder sb = new StringBuilder();
sb.Append(LDAP_IDENTITY);
return sb.Append(SplitOrganizeNameToDN(organizeUnit)).ToString();
}
/// <summary>
/// 分离组织名称为标准AD的DN名称,各个组织级别以"/"或"\"分开。如"总部/物业公司/小区",并且当前域为
/// ExchangeTest.Com,则返回的AD的DN表示名为"OU=小区,OU=物业公司,OU=总
/// 部,DC=ExchangeTest,DC=Com"。
/// </summary>
/// <param name="organizeName">组织名称</param>
/// <returns>返回一个级别</returns>
public static string SplitOrganizeNameToDN(string organizeName)
{
StringBuilder sb = new StringBuilder();
if (organizeName != null && organizeName.Length > 0)
{
string[] allOu = organizeName.Split(new char[]{'/','\\'});
for (int i = allOu.Length - 1; i >= 0; i--)
{
string ou = allOu[i];
if (sb.Length > 0 )
{
sb.Append(",");
}
sb.Append("OU=").Append(ou);
}
}
//如果传入了组织名称,则添加,
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(GetDomainDN());
return sb.ToString();
}
#endregion
}
}
以上代码会有一些异常需要自已定义