MS.Tech - IT人

.NET & 微软企业服务器 & 前沿技术和产品
随笔 - 107, 评论 - 1269, 引用 - 87

导航

关于

所有内容和观点仅代表个人观点,如有问题和建议请发Email给我。

标签

每月存档

最新留言

广告

两个问题

    昨天难得几家公司的一些开发人员聚集在一起讨论了些项目实施中的问题,摘录两个比较有趣的问题:

  • 关于工作日志问题:大家都认识到做工作总结的重要性。但是以什么方式做总结,以及在实施情况都不大一致。其中有的是以硬性规定程序员必须每天下班前填写工作日志,每周周五填写周报形式进行总结;有的则是以小型随便的圆桌会议进行项目组内部面对面沟通,周五则在会议室召开例会进行周总结;有的则每周只有周五进行一次例会;有的公司甚至好几次反复执行填写工作日志制度。但是,大家这样做的目标都是为了了解当前项目进度,同时进行计划调整与安排,增进成员间各种交流,方面上级领导视察工作情况,作为绩效考评之一。
    [个人观点]:填写工作日志是好的,一份好的工作日志确实能反映出很多问题。但是工作日志毕竟只是一种工具,那就要看怎么去用,才能用好它了。ZDNet里就有一篇《工作日志的好处》的文章。但是看似非常好的东西往往在执行过程中就变味了。比如有的工作日志是只填写给项目经理或上级领导看的,那就缺少了成员间技术等多方面交流的环节;有的工作日志简单到只写了“今天我做了XXX事,完成了XXX模块”之类,而没有把碰到的问题,解决的思路,最后的解决方案等写出来,形成了无用的信息垃圾;有的为了写给项目经理或领导看,夸大了自己的工作成绩,如果项目经理片面相信工作日志,就会埋下一定隐患。等等诸如此类问题。所以我觉得能做到象《工作日志的好处》里写的,那么你可以考虑执行。如果在你执行一段时间后,发现碰到上面所说的一些问题,你就该考虑出了什么问题,要不要纠正然后继续执行然后采取其他更适合自己团对的工具与手段?
  • 测试与版本管理等软件工程实施问题:这个问题可能比较受忽视,但却是真的十分严重的问题。几家公司中,讨论后发现这块比较好知名度也比较高的一家公司,它略去单元测试,他们采用MSF,在版本管理和变更管理上也算达到百分六七十成功了(套用那晚一个PPT上一句话,100%成功的配置管理耗费资源太多,能做到百分六七十就算实际了)。另一家采用类似XP编程方式,单元测试、代码重构、持续集成等都相对靠拢,当然结对编程也没实施(我怀疑结对编程在中国是否存在)。而另外一家也没单元测试,就进行功能测试性能测试,版本管理差不多也在去年初才使用SourceSafe管理。这之间讨论出现的问题就是,版本混乱、BUG跟踪、BUG报告等问题。我印象最深的是上述第一家公司用Excel做BUG跟踪、第二家之前也用Excel后来因为购买了Rational系列软件而采用Rational ClearQuest,但用不起来;第三家不清楚。
    [个人观点]:我想这个问题更多的是要求要有思想上的转变以及管理上的配合。现在的软件工程中的开发方法开发方式等呈现百花齐放景象,问题在于这些软件工程的方法生搬硬套并不能解决问题。我一直理解软件工程方法为一套实施参考指南,而非一套标准,这是我个人的理解。所以在实施一系列过程中,就应该在实践中去总结出自己最行之有效又合乎实际的方法。你能说出用Excel跟踪BUG的多点坏处,但是在目前情况目前财力物力下,如果管理通顺配合Excel管理BUG跟踪却是十分实际的做法。你能说没采用结对编程,参考实施XP其他有点就无法发挥其优势了吗?

posted on 2004-05-29 15:08:00 by liuhuimiao  评论(7) 阅读(2580)

Reflector、PInvoke.NET、XP&ADHelper

  1. Reflector 4.0 :真感谢Lutz Roeder一直在升级Reflector,一个.NET反编译软件。这几天最新的4.0版本的反编译效果又有进一步改善,把以前3.x里的变量定义杂乱的问题也修正了。
  2. PInvoke.NET下载):一款VS.NET Add-In工具,可让你直接把查找到非托管函数插入代码里,免去了你手工输入的困扰。同时对于非托管函数的声明都可以在http://www.pinvoke.net/里找到。安装完后,在代码文件里可从鼠标右键看到“Insert PInvoke Signatures...”的菜单,点入即可进一步进行插入非托管代码声明的操作。
  3. .NET下的极限编程工具:大家应该都听说过极限编程Extreme Programming(XP)了,它是一种全新的、生气勃勃的开发方式。正如我们大家都这样认为的,软件开发融艺术和工程于一体。虽然目前有着各种各样的开发工具、千奇百怪的开发方式,但是,检验软件的唯一途径,只有测试。测试就要求我们倾听客户的需求,然后编写程序,最后再同客户进行核实,然后不断重复这一过程,直到完成所的工作为止。相对于诸如瀑布式、原形法、分步交付法、RUP等的开发方法,个人认为XP(属于敏捷开发Agile)的厉害之处,在于不仅达到了满足客户需求,而且提高的软件质量(主要体现在降低Bug数量)上。也许,你有看过〈重构〉一书,没错,XP和重构背后都有一个居功至深的人——Kent Beck,因此XP和重构之间的关系想必大家也就清楚了。XP的价值观在于“简单、交流、反馈、勇气”。简单即为在管用能完成事情的前提下,做最简单的事;交流即整个开发过程应该都需要及时交流,这里交流侧重口头交流和能简单明了说明问题的文档交流,屏弃烦琐杂乱的文档和计划等;反馈即整个项目任何时候都需要客户和内部人员的反馈,以保证整个软件不断处于设计与编程与修复BUG的状态中;勇气即要求你必须有足够信心对自己的代码乃至别人的代码进行重构。呵呵,我在刚被XP思想吸引不久,又看到一个测试驱动编程,真感觉变化真快。在.NET下的极限编程主要工具,主要有:
    NUnit(单元测试工具):http://sourceforge.net/projects/nunit
         ◇使用NUnit在.Net编程中进行单元测试
         ◇在.NET环境中使用单元测试工具NUnit
         ◇Get Test Infected with NUnit: Unit Test Your .NET Data Access Layer
         ◇Adventures in C#: Using NUnit
    NAnt(自动编译工具):http://nant.sourceforge.net/
          ◇“蚂蚁”爬进.NET?
         ◇Nantpad——一款不错的NAnt build文件编辑器
    推荐书籍:《敏捷软件开发—原则、模式和实践》、《极限编程--基础、案例与实施》
  4. 改进了一个活动目录操作辅助类ADHelper,以后要改进的将主要在配置信息的存放、AD里对象基本属性操作的增强、与DSML结合等。如有修改会立即更新上来。里面用到了Kaneboy用户模拟类,在次表示感谢。J

posted on 2004-05-09 20:29:00 by liuhuimiao  评论(6) 阅读(10015)

ADHelper 活动目录用户操作类

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,

              ///

              /// 用户帐号被禁用

              ///

              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;

         }

     }

 

}

 

posted on 2004-05-08 17:49:00 by liuhuimiao  评论(35) 阅读(16807)

Powered by: Joycode.MVC引擎 0.5.2.0