您的位置:首页 > 编程语言 > C#

c# 域操作实例 AD身份验证

2009-11-10 08:02 495 查看
domainName 域服務器名稱 例如 AD1.Domain.com.tw

ADPATH = LDAP://AD1.Domain.com.cn/DC= Domain,DC=com,DC=cn

private static
DirectoryEntry GetDirectoryObject(string domainName, string
adUser, string adPassword)

{

DirectoryEntry entry = new
DirectoryEntry("LDAP://ad服務器名稱/DC=xxx,DC=com,DC=cn",
adUser, adPassword, AuthenticationTypes.Secure);

return entry;
}

public static DirectoryEntry GetDirectoryEntry(string domainName, string
commonName, string password)
{

try

{

DirectoryEntry de =
GetDirectoryObject(domainName, commonName, password);

DirectorySearcher
deSearch = new DirectorySearcher(de);

deSearch.Filter = "(SAMAccountName="
+ commonName + ")";

deSearch.SearchScope = SearchScope.Subtree;

SearchResult result = deSearch.FindOne();

de = new DirectoryEntry(result.Path);

return de;

}

catch(Exception
e)

{

return null;

}

}

原來是LDAP要加上AD電腦名稱 DirectoryEntry objDirEnt = new DirectoryEntry("LDAP://AD1.Domain.com.tw/CN=王小明,OU=客服部,DC=Domain,DC=com,DC=cn","帳號","密碼");

AD1.Domain.com.tw 域服務器名稱

using System;

using System.DirectoryServices;

namespace SystemFrameworks.Helper

{

///

///活动目录辅助类。封装一系列活动目录操作相关的方法。

///

public sealed class ADHelper

{

///

///域名

///

private static string DomainName = "MyDomain";

///

/// LDAP 地址

///

private static string LDAPDomain = "DC=MyDomain,DC=local";

///

/// LDAP绑定路径

///

private static string ADPath = "LDAP://brooks.mydomain.local";

///

///登录帐号

///

private static string ADUser = "Administrator";

///

///登录密码

///

private static string ADPassword = "password";

///

///扮演类实例

///

private static IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);

///

///用户登录验证结果

///

public enum LoginResult

{

///

///正常登录

///

LOGIN_USER_OK = 0,

///

///用户不存在

///

LOGIN_USER_DOESNT_EXIST,

///

///用户帐号被禁用

t;

///

LOGIN_USER_ACCOUNT_INACTIVE,

///

///用户密码不正确

///

LOGIN_USER_PASSWORD_INCORRECT

}

///

///用户属性定义标志

///

public enum ADS_USER_FLAG_ENUM

{

///

///登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。

///

ADS_UF_SCRIPT = 0X0001,

///

///用户帐号禁用标志

///

ADS_UF_ACCOUNTDISABLE = 0X0002,

///

///主文件夹标志

///

ADS_UF_HOMEDIR_REQUIRED = 0X0008,

///

///过期标志

///

ADS_UF_LOCKOUT = 0X0010,

///

///用户密码不是必须的

///

ADS_UF_PASSWD_NOTREQD = 0X0020,

///

///密码不能更改标志

///

ADS_UF_PASSWD_CANT_CHANGE = 0X0040,

///

///使用可逆的加密保存密码

///

ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,

///

///本地帐号标志

///

ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,

///

///普通用户的默认帐号类型

///

ADS_UF_NORMAL_ACCOUNT = 0X0200,

///

///跨域的信任帐号标志

///

ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,

///

///工作站信任帐号标志

///

ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,

///

///服务器信任帐号标志

///

ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,

///

///密码永不过期标志

///

ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,

///

/// MNS 帐号标志

///

ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,

///

///交互式登录必须使用智能卡

///

ADS_UF_SMARTCARD_REQUIRED = 0X40000,

///

///当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任

///

ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,

///

///当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托

///

ADS_UF_NOT_DELEGATED = 0X100000,

///

///此帐号需要 DES 加密类型

///

ADS_UF_USE_DES_KEY_ONLY = 0X200000,

///

///不要进行 Kerberos 预身份验证

///

ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,

///

///用户密码过期标志

///

ADS_UF_PASSWORD_EXPIRED = 0X800000,

///

///用户帐号可委托标志

///

ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000

}

public ADHelper()

{

//

}

#region GetDirectoryObject

///

///获得DirectoryEntry对象实例,以管理员登陆AD

///

///

private static DirectoryEntry GetDirectoryObject()

{

DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);

return entry;

}

///

///根据指定用户名和密码获得相应DirectoryEntry实体

///

///

///

///

private static DirectoryEntry GetDirectoryObject(string userName, string password)

{

DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);

return entry;

}

///

/// i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com

///

///

///

private static DirectoryEntry GetDirectoryObject(string domainReference)

{

DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);

return entry;

}

///

///获得以UserName,Password创建的DirectoryEntry

///

///

///

///

///

private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)

{

DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);

return entry;

}

#endregion

#region GetDirectoryEntry

///

///根据用户公共名称取得用户的 对象

///

///

用户公共名称

///如果找到该用户,则返回用户的 对象;否则返回 null

public static DirectoryEntry GetDirectoryEntry(string commonName)

{

DirectoryEntry de = GetDirectoryObject();

DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";

deSearch.SearchScope = SearchScope.Subtree;

try

{

SearchResult result = deSearch.FindOne();

de = new DirectoryEntry(result.Path);

return de;

}

catch

{

return null;

}

}

///

///根据用户公共名称和密码取得用户的 对象。

///

///

用户公共名称

///

用户密码

///如果找到该用户,则返回用户的 对象;否则返回 null

public static DirectoryEntry GetDirectoryEntry(string commonName, string password)

{

DirectoryEntry de = GetDirectoryObject(commonName, password);

DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";

deSearch.SearchScope = SearchScope.Subtree;

try

{

SearchResult result = deSearch.FindOne();

de = new DirectoryEntry(result.Path);

return de;

}

catch

{

return null;

}

}

///

///根据用户帐号称取得用户的 对象

///

///

用户帐号名

///如果找到该用户,则返回用户的 对象;否则返回 null

public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)

{

DirectoryEntry de = GetDirectoryObject();

DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";

deSearch.SearchScope = SearchScope.Subtree;

try

{

SearchResult result = deSearch.FindOne();

de = new DirectoryEntry(result.Path);

return de;

}

catch

{

return null;

}

}

///

///根据用户帐号和密码取得用户的 对象

///

///

用户帐号名

///

用户密码

///如果找到该用户,则返回用户的 对象;否则返回 null

public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)

{

DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);

if (de != null)

{

string commonName = de.Properties["cn"][0].ToString();

if (GetDirectoryEntry(commonName, password) != null)

return GetDirectoryEntry(commonName, password);

else

return null;

}

else

{

return null;

}

}

///

///根据组名取得用户组的 对象

///

///

组名

///

public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)

{

DirectoryEntry de = GetDirectoryObject();

DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";

deSearch.SearchScope = SearchScope.Subtree;

try

{

SearchResult result = deSearch.FindOne();

de = new DirectoryEntry(result.Path);

return de;

}

catch

{

return null;

}

}

#endregion

#region GetProperty

///

///获得指定 指定属性名对应的值

///

///

///

属性名称

///属性值

public static string GetProperty(DirectoryEntry de, string propertyName)

{

if(de.Properties.Contains(propertyName))

{

return de.Properties[propertyName][0].ToString() ;

}

else

{

return string.Empty;

}

}

///

///获得指定搜索结果 中指定属性名对应的值

///

///

///

属性名称

///属性值

public static string GetProperty(SearchResult searchResult, string propertyName)

{

if(searchResult.Properties.Contains(propertyName))

{

return searchResult.Properties[propertyName][0].ToString() ;

}

else

{

return string.Empty;

}

}

#endregion

///

///设置指定 的属性值

///

///

///

属性名称

///

属性值

public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)

{

if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null)

{

if(de.Properties.Contains(propertyName))

{

de.Properties[propertyName][0] = propertyValue;

}

else

{

de.Properties[propertyName].Add(propertyValue);

}

}

}

///

///创建新的用户

///

///

DN 位置。例如:OU=共享平台 或 CN=Users

///

公共名称

///

帐号

///

密码

///

public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)

{

DirectoryEntry entry = GetDirectoryObject();

DirectoryEntry subEntry = entry.Children.Find(ldapDN);

DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");

deUser.Properties["sAMAccountName"].Value = sAMAccountName;

deUser.CommitChanges();

ADHelper.EnableUser(commonName);

ADHelper.SetPassword(commonName, password);

deUser.Close();

return deUser;

}

///

///创建新的用户。默认创建在 Users 单元下。

///

///

公共名称

///

帐号

///

密码

///

public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)

{

return CreateNewUser("CN=Users", commonName, sAMAccountName, password);

}

///

///判断指定公共名称的用户是否存在

///

///

用户公共名称

///如果存在,返回 true;否则返回 false

public static bool IsUserExists(string commonName)

{

DirectoryEntry de = GetDirectoryObject();

DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))"; // LDAP 查询串

SearchResultCollection results = deSearch.FindAll();

if (results.Count == 0)

return false;

else

return true;

}

///

///判断用户帐号是否激活

///

///

用户帐号属性控制器

///如果用户帐号已经激活,返回 true;否则返回 false

public static bool IsAccountActive(int userAccountControl)

{

int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);

int flagExists = userAccountControl & userAccountControl_Disabled;

if (flagExists > 0)

return false;

else

return true;

}

///

///判断用户与密码是否足够以满足身份验证进而登录

///

///

用户公共名称

///

密码

///如能可正常登录,则返回 true;否则返回 false

public static LoginResult Login(string commonName, string password)

{

DirectoryEntry de = GetDirectoryEntry(commonName);

if (de != null)

{

// 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。

int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);

de.Close();

if (!IsAccountActive(userAccountControl))

return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;

if (GetDirectoryEntry(commonName, password) != null)

return LoginResult.LOGIN_USER_OK;

else

return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;

}

else

{

return LoginResult.LOGIN_USER_DOESNT_EXIST;

}

}

///

///判断用户帐号与密码是否足够以满足身份验证进而登录

///

///

用户帐号

///

密码

///如能可正常登录,则返回 true;否则返回 false

public static LoginResult LoginByAccount(string sAMAccountName, string password)

{

DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);

if (de != null)

{

// 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。

int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);

de.Close();

if (!IsAccountActive(userAccountControl))

return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;

if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)

return LoginResult.LOGIN_USER_OK;

else

return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;

}

else

{

return LoginResult.LOGIN_USER_DOESNT_EXIST;

}

}

///

///设置用户密码,管理员可以通过它来修改指定用户的密码。

///

///

用户公共名称

///

用户新密码

public static void SetPassword(string commonName, string newPassword)

{

DirectoryEntry de = GetDirectoryEntry(commonName);

// 模拟超级管理员,以达到有权限修改用户密码

impersonate.BeginImpersonate();

de.Invoke("SetPassword", new object[]{newPassword});

impersonate.StopImpersonate();

de.Close();

}

///

///设置帐号密码,管理员可以通过它来修改指定帐号的密码。

///

///

用户帐号

///

用户新密码

public static void SetPasswordByAccount(string sAMAccountName, string newPassword)

{

DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);

// 模拟超级管理员,以达到有权限修改用户密码

IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);

impersonate.BeginImpersonate();

de.Invoke("SetPassword", new object[]{newPassword});

impersonate.StopImpersonate();

de.Close();

}

///

///修改用户密码

///

///

用户公共名称

///

旧密码

///

新密码

public static void ChangeUserPassword (string commonName, string oldPassword, string newPassword)

{

// to-do: 需要解决密码策略问题

DirectoryEntry oUser = GetDirectoryEntry(commonName);

oUser.Invoke("ChangePassword", new Object[]{oldPassword, newPassword});

oUser.Close();

}

///

///启用指定公共名称的用户

///

///

用户公共名称

public static void EnableUser(string commonName)

{

EnableUser(GetDirectoryEntry(commonName));

}

///

///启用指定 的用户

///

///

public static void EnableUser(DirectoryEntry de)

{

impersonate.BeginImpersonate();

de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;

de.CommitChanges();

impersonate.StopImpersonate();

de.Close();

}

///

///禁用指定公共名称的用户

///

///

用户公共名称

public static void DisableUser(string commonName)

{

DisableUser(GetDirectoryEntry(commonName));

}

///

///禁用指定 的用户

///

///

public static void DisableUser(DirectoryEntry de)

{

impersonate.BeginImpersonate();

de.Properties["userAccountControl"][0]=ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;

de.CommitChanges();

impersonate.StopImpersonate();

de.Close();

}

///

///将指定的用户添加到指定的组中。默认为 Users 下的组和用户。

///

///

用户公共名称

///

组名

public static void AddUserToGroup(string userCommonName, string groupName)

{

DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);

DirectoryEntry oUser = GetDirectoryEntry(userCommonName);

impersonate.BeginImpersonate();

oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);

oGroup.CommitChanges();

impersonate.StopImpersonate();

oGroup.Close();

oUser.Close();

}

///

///将用户从指定组中移除。默认为 Users 下的组和用户。

///

///

用户公共名称

///

组名

public static void RemoveUserFromGroup(string userCommonName, string groupName)

{

DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);

DirectoryEntry oUser = GetDirectoryEntry(userCommonName);

impersonate.BeginImpersonate();

oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);

oGroup.CommitChanges();

impersonate.StopImpersonate();

oGroup.Close();

oUser.Close();

}

}

///

///用户模拟角色类。实现在程序段内进行用户角色模拟。

///

public class IdentityImpersonation

{

[DllImport("advapi32.dll", SetLastError=true)]

public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]

public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]

public extern static bool CloseHandle(IntPtr handle);

// 要模拟的用户的用户名、密码、域(机器名)

private String _sImperUsername;

private String _sImperPassword;

private String _sImperDomain;

// 记录模拟上下文

private WindowsImpersonationContext _imperContext;

private IntPtr _adminToken;

private IntPtr _dupeToken;

// 是否已停止模拟

private Boolean _bClosed;

///

///构造函数

///

///

所要模拟的用户的用户名

///

所要模拟的用户的密码

///

所要模拟的用户所在的域

public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)

{

_sImperUsername = impersonationUsername;

_sImperPassword = impersonationPassword;

_sImperDomain = impersonationDomain;

_adminToken = IntPtr.Zero;

_dupeToken = IntPtr.Zero;

_bClosed = true;

}

///

///析构函数

///

~IdentityImpersonation()

{

if(!_bClosed)

{

StopImpersonate();

}

}

///

///开始身份角色模拟。

///

///

public Boolean BeginImpersonate()

{

Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);

if(!bLogined)

{

return false;

}

Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);

if(!bDuped)

{

return false;

}

WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);

_imperContext = fakeId.Impersonate();

_bClosed = false;

return true;

}

///

///停止身分角色模拟。

///

public void StopImpersonate()

{

_imperContext.Undo();

CloseHandle(_dupeToken);

CloseHandle(_adminToken);

_bClosed = true;

}

}

}

=====================================================

简单的应用

[WebMethod]

public string IsAuthenticated(string UserID,string Password)

{

string _path = "LDAP://" + adm + "/DC=lamda,DC=com,DC=cn";//"LDAP://172.75.200.1/DC=名字,DC=com,DC=cn";

string _filterAttribute=null;

DirectoryEntry entry = new DirectoryEntry(_path,UserID,Password);

try

{

//Bind to the native AdsObject to force authentication.

DirectorySearcher search = new DirectorySearcher(entry);

search.Filter = "(SAMAccountName=" + UserID + ")";

SearchResult result = search.FindOne();

if(null == result)

{

_filterAttribute="登录失败: 未知的用户名或错误密码.";

}

else

{

_filterAttribute="true";

}

}

catch (Exception ex)

{

// if(ex.Message.StartsWith("该服务器不可操作"))

// {

// string mail = ADO.GetConnString("mail");

// entry.Path = "LDAP://"+mail+"/OU=名字,DC=it2004,DC=gree,DC=com,DC=cn";

// try

// {

// DirectorySearcher search = new DirectorySearcher(entry);

// search.Filter = "(SAMAccountName=" + UserID + ")";

// SearchResult result = search.FindOne();

//

// if(null == result)

// {

// _filterAttribute="登录失败: 未知的用户名或错误密码.";

// }

// else

// {

// _filterAttribute="true";

// }

// return _filterAttribute;

//

// }

// catch (Exception ex1)

// {

// return ex1.Message;

// }

//

// }

// else

return ex.Message;

}

return _filterAttribute;

}

[WebMethod]

public string[] LDAPMessage(string UserID)

{

string _path = "LDAP://"+adm+"/DC=it2004,DC=名字,DC=com,DC=cn";

string[] _filterAttribute=new string[5];

string[] msg = {"samaccountname","displayname","department","company"};

DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");

try

{

Object obj = entry.NativeObject;

DirectorySearcher search = new DirectorySearcher(entry);

search.Filter = "(SAMAccountName=" + UserID + ")";

SearchResult result = search.FindOne();

if(null == result)

{

_filterAttribute[0]="登录失败: 未知的用户名或错误密码.";

}

else

{

_filterAttribute[0]="true";

for(int propertyCounter = 1; propertyCounter < 5; propertyCounter++)

{

if(propertyCounter==4 && result.Properties[msg[propertyCounter-1]][0]==null)

break;

_filterAttribute[propertyCounter]=result.Properties[msg[propertyCounter-1]][0].ToString();

}

}

}

catch (Exception ex)

{

//_filterAttribute[0]=ex.Message;

}

return _filterAttribute;

}

[WebMethod]

public string[] AllMembers()

{

string[] msg;

string _path = "LDAP://名字";

DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");

//Bind to the native AdsObject to force authentication.

Object obj = entry.NativeObject;

System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);

mySearcher.Filter = "(SAMAccountName=180037)";

msg=new string[mySearcher.FindAll().Count];

int i=0;

foreach(System.DirectoryServices.SearchResult result in mySearcher.FindAll())

{

msg[i++]=result.Path;

}

return msg;

}

}

//***********************************************************************

//***********************************************************************

//***********************************************************************

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.DirectoryServices;

namespace change

{

/// <summary>

/// Form1 的摘要说明。

/// </summary>

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.ComboBox comboBox2;

private System.Windows.Forms.Label label3;

private System.Windows.Forms.ComboBox comboBox1;

private System.Windows.Forms.Label label2;

string str="";

string strErr="";

string strManager="";

private System.Windows.Forms.Label label1;

private System.Windows.Forms.Label label4;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.TextBox textBox1;

private System.Windows.Forms.TextBox textBox2;

private System.Windows.Forms.TextBox textBox3;

private System.Windows.Forms.CheckBox checkBox1;

private System.Windows.Forms.CheckBox checkBox2;

private System.Windows.Forms.CheckBox checkBox3;

private System.Windows.Forms.Label label5;

private System.Windows.Forms.TextBox textBox4;

private System.Windows.Forms.ComboBox comboBox3;

private System.Windows.Forms.Label label6;

private System.Windows.Forms.ComboBox comboBox4;

private System.Windows.Forms.Label label7;

private System.Windows.Forms.ComboBox comboBox5;

private System.Windows.Forms.Label label8;

private System.Windows.Forms.ComboBox comboBox6;

private System.Windows.Forms.Label label9;

/// <summary>

/// 必需的设计器变量。

/// </summary>

private System.ComponentModel.Container components = null;

public Form1()

{

//

// Windows 窗体设计器支持所必需的

//

InitializeComponent();

//

// TODO: 在 InitializeComponent 调用后添加任何构造函数代码

//

}

/// <summary>

/// 清理所有正在使用的资源。

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows 窗体设计器生成的代码

/// <summary>

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。

/// </summary>

private void InitializeComponent()

{

this.comboBox2 = new System.Windows.Forms.ComboBox();

this.label3 = new System.Windows.Forms.Label();

this.comboBox1 = new System.Windows.Forms.ComboBox();

this.label2 = new System.Windows.Forms.Label();

this.label1 = new System.Windows.Forms.Label();

this.label4 = new System.Windows.Forms.Label();

this.button1 = new System.Windows.Forms.Button();

this.textBox1 = new System.Windows.Forms.TextBox();

this.textBox2 = new System.Windows.Forms.TextBox();

this.textBox3 = new System.Windows.Forms.TextBox();

this.checkBox1 = new System.Windows.Forms.CheckBox();

this.checkBox2 = new System.Windows.Forms.CheckBox();

this.checkBox3 = new System.Windows.Forms.CheckBox();

this.label5 = new System.Windows.Forms.Label();

this.textBox4 = new System.Windows.Forms.TextBox();

this.comboBox3 = new System.Windows.Forms.ComboBox();

this.label6 = new System.Windows.Forms.Label();

this.comboBox4 = new System.Windows.Forms.ComboBox();

this.label7 = new System.Windows.Forms.Label();

this.comboBox5 = new System.Windows.Forms.ComboBox();

this.label8 = new System.Windows.Forms.Label();

this.comboBox6 = new System.Windows.Forms.ComboBox();

this.label9 = new System.Windows.Forms.Label();

this.SuspendLayout();

//

// comboBox2

//

this.comboBox2.Location = new System.Drawing.Point(416, 16);

this.comboBox2.Name = "comboBox2";

this.comboBox2.Size = new System.Drawing.Size(121, 20);

this.comboBox2.TabIndex = 10;

this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged);

//

// label3

//

this.label3.Location = new System.Drawing.Point(320, 20);

this.label3.Name = "label3";

this.label3.Size = new System.Drawing.Size(80, 16);

this.label3.TabIndex = 9;

this.label3.Text = "选择部门(OU)";

//

// comboBox1

//

this.comboBox1.Location = new System.Drawing.Point(144, 16);

this.comboBox1.Name = "comboBox1";

this.comboBox1.Size = new System.Drawing.Size(121, 20);

this.comboBox1.TabIndex = 8;

this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);

//

// label2

//

this.label2.AutoSize = true;

this.label2.Location = new System.Drawing.Point(40, 19);

this.label2.Name = "label2";

this.label2.Size = new System.Drawing.Size(79, 17);

this.label2.TabIndex = 7;

this.label2.Text = "选择公司(OU)";

//

// label1

//

this.label1.Location = new System.Drawing.Point(48, 128);

this.label1.Name = "label1";

this.label1.Size = new System.Drawing.Size(72, 23);

this.label1.TabIndex = 11;

this.label1.Text = "新公司名称";

//

// label4

//

this.label4.Location = new System.Drawing.Point(328, 128);

this.label4.Name = "label4";

this.label4.Size = new System.Drawing.Size(72, 23);

this.label4.TabIndex = 12;

this.label4.Text = "新部门名称";

//

// button1

//

this.button1.Location = new System.Drawing.Point(376, 376);

this.button1.Name = "button1";

this.button1.TabIndex = 15;

this.button1.Text = "开始处理";

this.button1.Click += new System.EventHandler(this.button1_Click);

//

// textBox1

//

this.textBox1.Location = new System.Drawing.Point(144, 128);

this.textBox1.Name = "textBox1";

this.textBox1.Size = new System.Drawing.Size(120, 21);

this.textBox1.TabIndex = 16;

this.textBox1.Text = "";

//

// textBox2

//

this.textBox2.Location = new System.Drawing.Point(416, 128);

this.textBox2.Name = "textBox2";

this.textBox2.Size = new System.Drawing.Size(120, 21);

this.textBox2.TabIndex = 17;

this.textBox2.Text = "";

//

// textBox3

//

this.textBox3.Location = new System.Drawing.Point(32, 232);

this.textBox3.Multiline = true;

this.textBox3.Name = "textBox3";

this.textBox3.ReadOnly = true;

this.textBox3.ScrollBars = System.Windows.Forms.ScrollBars.Both;

this.textBox3.Size = new System.Drawing.Size(504, 120);

this.textBox3.TabIndex = 18;

this.textBox3.Text = "";

//

// checkBox1

//

this.checkBox1.Location = new System.Drawing.Point(64, 192);

this.checkBox1.Name = "checkBox1";

this.checkBox1.TabIndex = 20;

this.checkBox1.Text = "修改公司名称";

//

// checkBox2

//

this.checkBox2.Location = new System.Drawing.Point(200, 192);

this.checkBox2.Name = "checkBox2";

this.checkBox2.TabIndex = 21;

this.checkBox2.Text = "修改部门名称";

//

// checkBox3

//

this.checkBox3.Location = new System.Drawing.Point(336, 192);

this.checkBox3.Name = "checkBox3";

this.checkBox3.TabIndex = 22;

this.checkBox3.Text = "修改部门领导";

//

// label5

//

this.label5.AutoSize = true;

this.label5.Location = new System.Drawing.Point(40, 160);

this.label5.Name = "label5";

this.label5.Size = new System.Drawing.Size(79, 17);

this.label5.TabIndex = 19;

this.label5.Text = "新的部门领导";

//

// textBox4

//

this.textBox4.Location = new System.Drawing.Point(144, 160);

this.textBox4.Name = "textBox4";

this.textBox4.Size = new System.Drawing.Size(392, 21);

this.textBox4.TabIndex = 23;

this.textBox4.Text = "请输入新领导的姓名全拼(域帐号)";

//

// comboBox3

//

this.comboBox3.Location = new System.Drawing.Point(144, 48);

this.comboBox3.Name = "comboBox3";

this.comboBox3.Size = new System.Drawing.Size(121, 20);

this.comboBox3.TabIndex = 25;

this.comboBox3.SelectedIndexChanged += new System.EventHandler(this.comboBox3_SelectedIndexChanged);

//

// label6

//

this.label6.AutoSize = true;

this.label6.Location = new System.Drawing.Point(4, 51);

this.label6.Name = "label6";

this.label6.Size = new System.Drawing.Size(116, 17);

this.label6.TabIndex = 24;

this.label6.Text = "选择二级子部门(OU)";

//

// comboBox4

//

this.comboBox4.Location = new System.Drawing.Point(416, 48);

this.comboBox4.Name = "comboBox4";

this.comboBox4.Size = new System.Drawing.Size(121, 20);

this.comboBox4.TabIndex = 27;

this.comboBox4.SelectedIndexChanged += new System.EventHandler(this.comboBox4_SelectedIndexChanged);

//

// label7

//

this.label7.AutoSize = true;

this.label7.Location = new System.Drawing.Point(284, 51);

this.label7.Name = "label7";

this.label7.Size = new System.Drawing.Size(116, 17);

this.label7.TabIndex = 26;

this.label7.Text = "选择三级子部门(OU)";

//

// comboBox5

//

this.comboBox5.Location = new System.Drawing.Point(416, 80);

this.comboBox5.Name = "comboBox5";

this.comboBox5.Size = new System.Drawing.Size(121, 20);

this.comboBox5.TabIndex = 31;

this.comboBox5.SelectedIndexChanged += new System.EventHandler(this.comboBox5_SelectedIndexChanged);

//

// label8

//

this.label8.Location = new System.Drawing.Point(280, 84);

this.label8.Name = "label8";

this.label8.Size = new System.Drawing.Size(120, 16);

this.label8.TabIndex = 30;

this.label8.Text = "选择级五子部门(OU)";

//

// comboBox6

//

this.comboBox6.Location = new System.Drawing.Point(144, 80);

this.comboBox6.Name = "comboBox6";

this.comboBox6.Size = new System.Drawing.Size(121, 20);

this.comboBox6.TabIndex = 29;

this.comboBox6.SelectedIndexChanged += new System.EventHandler(this.comboBox6_SelectedIndexChanged);

//

// label9

//

this.label9.AutoSize = true;

this.label9.Location = new System.Drawing.Point(4, 83);

this.label9.Name = "label9";

this.label9.Size = new System.Drawing.Size(116, 17);

this.label9.TabIndex = 28;

this.label9.Text = "选择四级子部门(OU)";

//

// Form1

//

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

this.ClientSize = new System.Drawing.Size(584, 429);

this.Controls.Add(this.comboBox5);

this.Controls.Add(this.label8);

this.Controls.Add(this.comboBox6);

this.Controls.Add(this.label9);

this.Controls.Add(this.comboBox4);

this.Controls.Add(this.label7);

this.Controls.Add(this.comboBox3);

this.Controls.Add(this.label6);

this.Controls.Add(this.textBox4);

this.Controls.Add(this.checkBox3);

this.Controls.Add(this.checkBox2);

this.Controls.Add(this.checkBox1);

this.Controls.Add(this.label5);

this.Controls.Add(this.textBox3);

this.Controls.Add(this.textBox2);

this.Controls.Add(this.textBox1);

this.Controls.Add(this.button1);

this.Controls.Add(this.label4);

this.Controls.Add(this.label1);

this.Controls.Add(this.comboBox2);

this.Controls.Add(this.label3);

this.Controls.Add(this.comboBox1);

this.Controls.Add(this.label2);

this.Name = "Form1";

this.Text = "按OU成批修改信息";

this.Load += new System.EventHandler(this.Form1_Load);

this.ResumeLayout(false);

}

#endregion

/// <summary>

/// 应用程序的主入口点。

/// </summary>

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{

//str=listBox1.SelectedItem.ToString();

str=comboBox1.SelectedItem.ToString();

DirectoryEntry de1=new DirectoryEntry();

de1.Path="LDAP://"+str+",DC=test,DC=net";

try

{

comboBox2.Items.Clear();

comboBox2.Text="";

comboBox2.Refresh();

foreach (DirectoryEntry ch1 in de1.Children)

{

// textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

string str1="";

str1=ch1.SchemaClassName.ToString();

if (str1=="organizationalUnit")

{

comboBox2.Items.Add(ch1.Name.ToString());

}

}

de1.Close();

//textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

// MessageBox.Show("finish!!!");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

finally

{}

}

private void Form1_Load(object sender, System.EventArgs e)

{

//初始化公司选择框

DirectoryEntry de1=new DirectoryEntry();

de1.Path="LDAP://DC=test,DC=net";

try

{

foreach (DirectoryEntry ch1 in de1.Children)

{

// textBox1.Text=textBox1.Text+ch1.Name+"/r/n";//ch.Properties["adpath"][0].ToString();

str=ch1.Name.ToString();

string str1="";

//str1=str.Substring(0,str.IndexOf("="));

str1=ch1.SchemaClassName.ToString();

if (str1=="organizationalUnit")

{

//listBox1.Items.Add(ch1.Name.ToString());

comboBox1.Items.Add(ch1.Name.ToString());

// comboBox3.Items.Add(ch1.Name.ToString());

}

}

de1.Close();

//textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

// MessageBox.Show("finish!!!");

}

catch(Exception ex)

{

strErr=ex.Message;

}

finally

{}

}

private void button1_Click(object sender, System.EventArgs e)

{

string strADRoot="";

string strName="";

if(comboBox1.Text==""||comboBox2.Text=="")

{

strErr="请选择合适的OU";

goto e1;

}

if(checkBox1.Checked)

{

if(textBox1.Text=="")

{

strErr="请输入新公司名称";

goto e1;

}

}

if(checkBox2.Checked)

{

if(textBox2.Text=="")

{

strErr="请输入部门名称!";

goto e1;

}

}

if(checkBox3.Checked)

{

if(textBox4.Text=="请输入新领导的姓名全拼(域帐号)")

{

strErr="请输入新领导的姓名全拼(域帐号)!";

goto e1;

}

// string strNewManager="";

//搜索

//检查是否有重复的帐号

DirectoryEntry su=new DirectoryEntry("LDAP://DC=test,DC=net");

DirectorySearcher searcher = new DirectorySearcher();

searcher.SearchRoot=su;

searcher.PropertiesToLoad.Add("CN");

searcher.Filter = "(&(objectClass=user)(sAMAccountName="+textBox4.Text.ToString()+"))";

searcher.SearchScope = SearchScope.Subtree;

searcher.Sort = new SortOption("sAMAccountName", SortDirection.Ascending);

SearchResultCollection results = searcher.FindAll();

DialogResult dlResult;

string strMess="您确认要将该OU下的用户的领导更改为:"+results[0].Properties["CN"][0].ToString();

dlResult=MessageBox.Show(this,strMess,"请确认",MessageBoxButtons.YesNo,

MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,

MessageBoxOptions.RightAlign);

if(dlResult == DialogResult.Yes)

{

strManager= results[0].Properties["adspath"][0].ToString();

strManager=strManager.Remove(0,7);

}

else

{

textBox4.Text="请重新输入新领导的姓名全拼(域帐号)!";

strErr="请重新输入新领导的姓名全拼(域帐号)!";

goto e1;

}

}

if((!checkBox3.Checked)&&(!checkBox2.Checked)&&(!checkBox1.Checked))

{

strErr="请选择要修改的项目!";

goto e1;

}

strADRoot="LDAP://"+str+",DC=test,DC=net";

DirectoryEntry de=new DirectoryEntry();

de.Path=strADRoot;

textBox3.Text="";

try

{

foreach(DirectoryEntry chm in de.Children)

{

string strType="";

strType=chm.SchemaClassName.ToString();

if(strType.ToUpper()=="USER")

{

strName=chm.Name.ToString();

//如果选中了修改领导的话

if(checkBox3.Checked)

{

if(chm.Properties.Contains("manager"))

{

chm.Properties["manager"][0]=strManager;

chm.CommitChanges();

textBox3.Text=textBox3.Text+chm.Name .ToString()+"的领导修改成功!/r/n";

}

else

{

chm.Properties["manager"].Add(strManager);

chm.CommitChanges();

textBox3.Text=textBox3.Text+chm.Name .ToString()+"的领导添加成功!/r/n";

}

}

//修改公司

if(checkBox1.Checked)

{

if(chm.Properties.Contains("company"))

{

chm.Properties["company"][0]=textBox1.Text.ToString();

chm.CommitChanges();

textBox3.Text=textBox3.Text+chm.Name .ToString()+"的公司名称修改成功!/r/n";

}

else

{

chm.Properties["company"].Add(textBox1.Text.ToString());

chm.CommitChanges();

textBox3.Text=textBox3.Text+chm.Name .ToString()+"的公司名称添加成功!/r/n";

//textBox3.Text=textBox3.Text+ch1.Name .ToString()+"/r/n";

}

}

//修改部门

if(checkBox2.Checked)

{

if(chm.Properties.Contains("department"))

{

chm.Properties["department"][0]=textBox2.Text.ToString();

chm.CommitChanges();

textBox3.Text=textBox3.Text+chm.Name .ToString()+"的部门名称修改成功!/r/n";

}

else

{

chm.Properties["department"].Add(textBox2.Text.ToString());

chm.CommitChanges();

//textBox3.Text=textBox3.Text+ch1.Name .ToString()+"/r/n";

textBox3.Text=textBox3.Text+chm.Name .ToString()+"的部门名称添加成功!/r/n";

}

}

}

}

MessageBox.Show("修改成功!");

}

catch(Exception ex)

{

strErr=ex.Message;

goto e1;

}

e1: if(strErr!="")

{

MessageBox.Show(strErr);

}

}

private void comboBox2_SelectedIndexChanged(object sender, System.EventArgs e)

{

//str=listBox1.SelectedItem.ToString();

str=comboBox2.SelectedItem.ToString()+","+comboBox1.SelectedItem.ToString();

DirectoryEntry de1=new DirectoryEntry();

de1.Path="LDAP://"+str+",DC=test,DC=net";

try

{

comboBox3.Items.Clear();

comboBox3.Text="";

comboBox3.Refresh();

foreach (DirectoryEntry ch1 in de1.Children)

{

// textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

string str1="";

str1=ch1.SchemaClassName.ToString();

if (str1=="organizationalUnit")

{

comboBox3.Items.Add(ch1.Name.ToString());

}

}

de1.Close();

//textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

// MessageBox.Show("finish!!!");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

private void comboBox3_SelectedIndexChanged(object sender, System.EventArgs e)

{

str=comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+comboBox1.SelectedItem.ToString();

DirectoryEntry de1=new DirectoryEntry();

de1.Path="LDAP://"+str+",DC=test,DC=net";

try

{

comboBox4.Items.Clear();

comboBox4.Text="";

comboBox4.Refresh();

foreach (DirectoryEntry ch1 in de1.Children)

{

// textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

string str1="";

str1=ch1.SchemaClassName.ToString();

if (str1=="organizationalUnit")

{

comboBox4.Items.Add(ch1.Name.ToString());

}

}

de1.Close();

//textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

// MessageBox.Show("finish!!!");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

private void comboBox4_SelectedIndexChanged(object sender, System.EventArgs e)

{

str=comboBox4.SelectedItem.ToString()+","+comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+comboBox1.SelectedItem.ToString();

DirectoryEntry de1=new DirectoryEntry();

de1.Path="LDAP://"+str+",DC=test,DC=net";

try

{

comboBox6.Items.Clear();

comboBox6.Text="";

comboBox6.Refresh();

foreach (DirectoryEntry ch1 in de1.Children)

{

// textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

string str1="";

str1=ch1.SchemaClassName.ToString();

if (str1=="organizationalUnit")

{

comboBox6.Items.Add(ch1.Name.ToString());

}

}

de1.Close();

//textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

// MessageBox.Show("finish!!!");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

private void comboBox6_SelectedIndexChanged(object sender, System.EventArgs e)

{

str=comboBox6.SelectedItem.ToString()+","+comboBox4.SelectedItem.ToString()+","+

comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+

comboBox1.SelectedItem.ToString();

DirectoryEntry de1=new DirectoryEntry();

de1.Path="LDAP://"+str+",DC=test,DC=net";

try

{

comboBox5.Items.Clear();

comboBox5.Text="";

comboBox5.Refresh();

foreach (DirectoryEntry ch1 in de1.Children)

{

// textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

string str1="";

str1=ch1.SchemaClassName.ToString();

if (str1=="organizationalUnit")

{

comboBox5.Items.Add(ch1.Name.ToString());

}

}

de1.Close();

//textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

// MessageBox.Show("finish!!!");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

private void comboBox5_SelectedIndexChanged(object sender, System.EventArgs e)

{

str=comboBox5.SelectedItem.ToString()+","+comboBox6.SelectedItem.ToString()+","+comboBox4.SelectedItem.ToString()+","+

comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+

comboBox1.SelectedItem.ToString();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: