zoukankan      html  css  js  c++  java
  • ADEntryj简单的增删改属性设置

    namespace SMCManager.Business
    {
        public class CTreeManager : ITreeManager
        {
            //private string _dc = Convert.ToString(ConfigurationManager.AppSettings["DC"]);
            //private string _rootLdap = Convert.ToString(ConfigurationManager.AppSettings["RootLDAP"]);
            //private string _domain = Convert.ToString(ConfigurationManager.AppSettings["Domain"]);
            //private string _admin = Convert.ToString(ConfigurationManager.AppSettings["Admin"]);
            //private string _password = Convert.ToString(ConfigurationManager.AppSettings["Password"]);
    
            //private string GetADPath(string ldap)
            //{
            //    string path = string.Empty;
            //    if (string.IsNullOrEmpty(ldap))
            //        path = string.Format("LDAP://{0}/{1}", _dc, _rootLdap);
            //    else
            //    {
            //        path = string.Format("LDAP://{0}/{1}", _dc, ldap);
            //    }
            //    return path;
            //}
    
            //private bool GetADEntry(string path, out DirectoryEntry Ad_DC, out string strError)
            //{
            //    bool bResult = false;
            //    strError = string.Empty;
            //    Ad_DC = null;
            //    try
            //    {
            //        Ad_DC = new DirectoryEntry(path);
            //        bResult = true;
            //    }
            //    catch (Exception ex)
            //    {
            //        //日志
            //        strError = "实例化ADEntry失败,Error:" + ex.Message;
            //        bResult = false;
            //    }
            //    return bResult;
            //}
    
            /// <summary>
            /// 同步数据
            /// </summary>
            /// <param name="item"></param>
            /// <param name="strError"></param>
            /// <returns></returns>
            public bool GetTreeData(out CTreeItem item, out string strError)
            {
                bool bResult = false;
                strError = string.Empty;
                item = new CTreeItem();
                string path = CommonManager.GetRootADPath();
                DirectoryEntry Ad_DC = null;
                if (CommonManager.GetADEntryByPath(path, out Ad_DC, out strError))
                {
                    item.ID = Ad_DC.Properties["distinguishedName"].Value == null ? "" : Ad_DC.Properties["distinguishedName"].Value.ToString();
                    item.DisplayName = Ad_DC.Properties["name"].Value == null ? "" : Ad_DC.Properties["name"].Value.ToString();
                    item.ItemType = SMCEntity.Common.TreeTypeEnum.OU;
                    if (Ad_DC != null)
                    {
                        Ad_DC.Close();
                        Ad_DC.Dispose();
                        Ad_DC = null;
                    }
                    bResult = true;
                }
                //ADBase adBase = ADFactoryManager.GetADBase("");
                //if (!adBase.Connect(out strError))
                //{
                //    return false;
                //}
                //try
                //{
                //    item.ID = adBase._adConnect.Entry.Properties["distinguishedName"].Value == null ? "" : adBase._adConnect.Entry.Properties["distinguishedName"].Value.ToString();
                //    item.DisplayName = adBase._adConnect.Entry.Properties["name"].Value == null ? "" : adBase._adConnect.Entry.Properties["name"].Value.ToString();
                //    item.ItemType = SMCEntity.Common.TreeTypeEnum.OU;
                //    bResult = true;
                //}
                //catch (Exception ex)
                //{
                //    strError = ex.Message;
                //    bResult = false;
                //}
                //adBase._adConnect.Dispose();
                //DirectoryEntry root;
                //string ladp = Convert.ToString(ConfigurationManager.AppSettings["RootLADP"]);
                //if (GetRootTreeAd(ladp, out root))
                //{
                //    item.ID = root.Properties["distinguishedName"].Value == null ? "" : root.Properties["distinguishedName"].Value.ToString();
                //    item.DisplayName = root.Properties["name"].Value == null ? "" : root.Properties["name"].Value.ToString();
                //    item.ItemType = SMCEntity.Common.TreeTypeEnum.OU;
                //    bResult = true;
    
                //    if (root != null)
                //    {
                //        root.Close();
                //        root.Dispose();
                //        root = null;
                //    }
                //}
                //else
                //{
                //    //日志
                //}
                return bResult;
            }
    
            /// <summary>
            /// 获取父节点下单层节点数据集
            /// </summary>
            /// <param name="item">父节点</param>
            /// <param name="items">节点数据集</param>
            /// <param name="strError">返回信息</param>
            /// <returns></returns>
            public bool GetTreeData(string itemID, out List<CTreeItem> items, out string strError)
            {
                bool bResult = false;
                strError = string.Empty;
                items = new List<CTreeItem>();
                DirectoryEntry Ad_DC = null;
                if (CommonManager.GetADEntryByLdap(itemID, out Ad_DC, out strError))
                {
                    try
                    {
                        DirectorySearcher Ad_deSearch = new DirectorySearcher();
                        Ad_deSearch.SearchRoot = Ad_DC;
                        Ad_deSearch.Filter = "(|(objectClass=organizationalUnit)(objectClass=user))";
                        Ad_deSearch.SearchScope = SearchScope.OneLevel;
                        Ad_deSearch.PageSize = 1000;
                        SearchResultCollection results = Ad_deSearch.FindAll();
                        //获取DC下的全部OU
                        if (results != null && results.Count > 0)
                        {
                            DirectoryEntry CN = null;
                            CTreeItem item = null;
                            foreach (SearchResult Result in results)
                            {
                                item = new CTreeItem();
                                CN = Result.GetDirectoryEntry();
                                object[] objectClasses = CN.Properties["objectClass"].Value == null ? new object[] { } : (object[])(CN.Properties["objectClass"].Value);
                                foreach (string objectClass in objectClasses)
                                {
                                    if (objectClass == "organizationalUnit")
                                    {
                                        item.ItemType = SMCEntity.Common.TreeTypeEnum.OU;
                                        break;
                                    }
                                    else if (objectClass == "user")
                                    {
                                        item.ItemType = SMCEntity.Common.TreeTypeEnum.User;
                                        break;
                                    }
                                }
                                item.ID = CN.Properties["distinguishedName"].Value == null ? "" : CN.Properties["distinguishedName"].Value.ToString();
                                item.DisplayName = CN.Properties["name"].Value == null ? "" : CN.Properties["name"].Value.ToString();
                                items.Add(item);
                            }
                            bResult = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        strError = ex.Message;
                        bResult = false;
                    }
                }
                //if (string.IsNullOrEmpty(itemID))
                //{
                //    strError = "传入参数不能为空";
                //    return false;
                //}
                //ADBase adBase = ADFactoryManager.GetADBase(itemID);
                //if (!adBase.Connect(out strError))
                //{
                //    return false;
                //}
                //try
                //{
                //    DirectorySearcher Ad_deSearch = new DirectorySearcher();
                //    Ad_deSearch.SearchRoot = adBase._adConnect.Entry;
                //    Ad_deSearch.Filter = "(|(objectClass=organizationalUnit)(objectClass=user))";
                //    Ad_deSearch.SearchScope = SearchScope.OneLevel;
                //    Ad_deSearch.PageSize = 1000;
                //    SearchResultCollection results = Ad_deSearch.FindAll();
                //    //获取DC下的全部OU
                //    if (results != null && results.Count > 0)
                //    {
                //        DirectoryEntry CN = null;
                //        CTreeItem item = null;
                //        foreach (SearchResult Result in results)
                //        {
                //            item = new CTreeItem();
                //            CN = Result.GetDirectoryEntry();
                //            List<string> dsasa = CN.Properties["objectClass"].Value as List<string>;
                //            string objectClass = CN.Properties["objectClass"].Value == null ? "" : CN.Properties["objectClass"].Value.ToString();
                //            if (objectClass == "organizationalUnit")
                //                item.ItemType = SMCEntity.Common.TreeTypeEnum.OU;
                //            else if (objectClass == "user")
                //                item.ItemType = SMCEntity.Common.TreeTypeEnum.User;
    
                //            item.ID = CN.Properties["distinguishedName"].Value == null ? "" : CN.Properties["distinguishedName"].Value.ToString();
                //            item.DisplayName = CN.Properties["name"].Value == null ? "" : CN.Properties["name"].Value.ToString();
                //            items.Add(item);
                //        }
                //    }
                //}
                //catch (Exception ex)
                //{
                //    //日志
                //    strError = ex.Message;
                //    bResult = false;
                //}
                //adBase._adConnect.Dispose();
                return bResult;
            }
            public bool PwdUserAD(string ldap, string newPwd, out string strError)
            {
                DirectoryEntry ad_DC = null;
                if (CommonManager.GetADEntryByLdap(ldap, out ad_DC, out strError))
                {
                    try
                    {
                        if (CommonManager.SecurityVerification(out strError))
                        {
                            using (ad_DC)
                            {
                                ad_DC.Invoke("SetPassword", new object[] { newPwd });   //set user's password
                                ad_DC.CommitChanges();
                            }
                        }
                    }
                    catch (COMException ex)
                    {
                        strError = ex.Message;
                        return false;
                    }
                    return true;
                }
                return false;
            }
            public bool DelUserAD(string ldap, out string strError)
            {
                DirectoryEntry ad_DC = null;
                if (CommonManager.GetADEntryByLdap(ldap, out ad_DC, out strError))
                {
                    try
                    {
                        if (CommonManager.SecurityVerification(out strError))
                        {
                            using (ad_DC)
                            {
                                ad_DC.DeleteTree();
                            }
                        }
                    }
                    catch (COMException ex)
                    {
                        strError = ex.Message;
                        return false;
                    }
                    return true;
                }
                return false;
            }
            public bool GreateUserAD(string ldap, CUserEntity userEntity, out string strError)
            {
                DirectoryEntry ad_DC = null;
                if (CommonManager.GetADEntryByLdap(ldap, out ad_DC, out strError))
                {
                    try
                    {
                        if (CommonManager.SecurityVerification(out strError))
                        {
                            if (!string.IsNullOrEmpty(userEntity.DisplayName))//传值为空报异常
                            {
                                using (ad_DC)
                                {
                                    using (DirectoryEntry user = ad_DC.Children.Add("CN=" + userEntity.DisplayName, "user"))
                                    {
                                        user.Properties["sAMAccountName"].Add(userEntity.DisplayName);//拼音
                                        user.Properties["displayName"].Add(userEntity.DisplayName);
                                        if (!string.IsNullOrEmpty(userEntity.Account))//传值为空报异常
                                            user.Properties["userPrincipalName"].Add(userEntity.Account);//登陆邮箱
                                        if (!string.IsNullOrEmpty(userEntity.UserBase.FristName))//传值为空报异常
                                            user.Properties["sn"].Add(userEntity.UserBase.FristName);//姓
                                        if (!string.IsNullOrEmpty(userEntity.UserBase.LastName))//传值为空报异常
                                            user.Properties["givenName"].Add(userEntity.UserBase.LastName);//名
                                        if (!string.IsNullOrEmpty(userEntity.UserBase.OfficeName))//传值为空报异常
                                            user.Properties["physicalDeliveryOfficeName"].Add(userEntity.UserBase.OfficeName);//名
                                        if (!string.IsNullOrEmpty(userEntity.UserBase.Discription))//传值为空报异常
                                            user.Properties["description"].Add(userEntity.UserBase.Discription);
                                        if (!string.IsNullOrEmpty(userEntity.UserBase.TelephoneNumber))//传值为空报异常
                                            user.Properties["telephoneNumber"].Add(userEntity.UserBase.TelephoneNumber);
                                        user.CommitChanges();
                                        user.Invoke("SetPassword", new object[] { userEntity.UserBase.Password });   //set user's password
                                        //用户帐户控制 userAccountControl (启用:512,禁用:514, 密码永不过期:66048)
                                        int val = (int)user.Properties["userAccountControl"].Value;//默认值546,val & ~2=544参数:启用且密码可以为空
                                        user.Properties["userAccountControl"].Value = val & ~2;
                                        user.CommitChanges();
                                    }
    
                                }
                            }
                        }
                    }
                    catch (COMException ex)
                    {
                        strError = ex.Message;
                        return false;
                    }
                    return true;
                }
                return false;
            }
            public bool ModifyUserAD(string ldap, CUserEntity userEntity, out string strError)
            {
                DirectoryEntry ad_DC = null;
                if (CommonManager.GetADEntryByLdap(ldap, out ad_DC, out strError))
                {
                    try
                    {
                        if (CommonManager.SecurityVerification(out strError))
                        {
                            if (!string.IsNullOrEmpty(userEntity.DisplayName))//传值为空报异常
                            {
                                using (ad_DC)
                                {
                                    if (ad_DC.Properties.Contains("displayName"))
                                        ad_DC.Properties["displayName"][0] = userEntity.DisplayName;
                                    else
                                        ad_DC.Properties["displayName"].Add(userEntity.DisplayName);
                                    if (ad_DC.Properties.Contains("sAMAccountName"))
                                        ad_DC.Properties["sAMAccountName"][0] = userEntity.DisplayName;
                                    else
                                        ad_DC.Properties["sAMAccountName"].Add(userEntity.DisplayName);
    
                                    if (ad_DC.Properties.Contains("sn"))
                                        ad_DC.Properties["sn"][0] = userEntity.UserBase.FristName;
                                    else
                                        ad_DC.Properties["sn"].Add(userEntity.UserBase.FristName);
                                    if (ad_DC.Properties.Contains("givenName"))
                                        ad_DC.Properties["givenName"][0] = userEntity.UserBase.LastName;
                                    else
                                        ad_DC.Properties["givenName"].Add(userEntity.UserBase.LastName);
                                    if (ad_DC.Properties.Contains("telephoneNumber"))
                                        ad_DC.Properties["telephoneNumber"][0] = userEntity.UserBase.TelephoneNumber;
                                    else
                                        ad_DC.Properties["telephoneNumber"].Add(userEntity.UserBase.TelephoneNumber);
                                    if (ad_DC.Properties.Contains("physicalDeliveryOfficeName"))
                                        ad_DC.Properties["physicalDeliveryOfficeName"][0] = userEntity.UserBase.OfficeName;
                                    else
                                        ad_DC.Properties["physicalDeliveryOfficeName"].Add(userEntity.UserBase.OfficeName);
                                    if (ad_DC.Properties.Contains("description"))
                                        ad_DC.Properties["description"][0] = userEntity.UserBase.Discription;
                                    else
                                        ad_DC.Properties["description"].Add(userEntity.UserBase.Discription);
                                    ad_DC.CommitChanges();
                                }
                            }
                        }
                    }
                    catch (COMException ex)
                    {
                        strError = ex.Message;
                        return false;
                    }
                    return true;
                }
                return false;
            }
            public bool GetUserPropertyAD(string ldap, out CUserEntity userEntity, out string strError)
            {
                DirectoryEntry ad_DC = null;
                userEntity = null;
                if (CommonManager.GetADEntryByLdap(ldap, out ad_DC, out strError))
                {
                    try
                    {
                        using (ad_DC)
                        {
                            userEntity = new CUserEntity();
                            CUserBase userBase = new CUserBase();
                            if (ad_DC.Properties.Contains("displayName"))
                                userEntity.DisplayName = ad_DC.Properties["displayName"][0].ToString();
                            if (ad_DC.Properties.Contains("cn"))
                                userBase.FristName = ad_DC.Properties["cn"][0].ToString();
                            if (ad_DC.Properties.Contains("givenName"))
                                userBase.LastName = ad_DC.Properties["givenName"][0].ToString();
                            if (ad_DC.Properties.Contains("telephoneNumber"))
                                userBase.TelephoneNumber = ad_DC.Properties["telephoneNumber"][0].ToString();
                            if (ad_DC.Properties.Contains("physicalDeliveryOfficeName"))
                                userBase.OfficeName = ad_DC.Properties["physicalDeliveryOfficeName"][0].ToString();
                            if (ad_DC.Properties.Contains("description"))
                                userBase.Discription = ad_DC.Properties["description"][0].ToString();
                            userEntity.UserBase = userBase;
                        }
                    }
                    catch (COMException ex)
                    {
                        strError = ex.Message;
                        return false;
                    }
                    return true;
                }
                return false;
            }
            //private bool GetRootTreeAd(string ladp, out DirectoryEntry Ad_DC)
            //{
            //    bool bResult = true;
            //    Ad_DC = null;
            //    if (string.IsNullOrEmpty(ladp))
            //    {
            //        return false;
            //    }
    
            //    try
            //    {
            //        ladp = string.Format("LDAP://{0}/{1}", dc, ladp);
            //        Ad_DC = new DirectoryEntry(ladp);
            //    }
            //    catch (Exception error)
            //    {
            //        //日志
            //        bResult = false;
            //    }
    
            //    return bResult;
            //} }
        }
        public class CommonManager
        {
            public static string GetADPathByLdap(string ldap)
            {
                string dc = Convert.ToString(ConfigurationManager.AppSettings["DC"]);
                if (!string.IsNullOrEmpty(ldap) && !string.IsNullOrEmpty(dc))
                    return string.Format("LDAP://{0}/{1}", dc, ldap);
                return string.Empty;
            }
            public static string GetRootADPath()
            {
                string dc = Convert.ToString(ConfigurationManager.AppSettings["DC"]);
                string rootLdap = Convert.ToString(ConfigurationManager.AppSettings["RootLDAP"]);
                if (!string.IsNullOrEmpty(rootLdap) && !string.IsNullOrEmpty(dc))
                    return string.Format("LDAP://{0}/{1}", dc, rootLdap);
                return string.Empty;
            }
    
            public static bool GetADEntryByPath(string path, out DirectoryEntry Ad_DC, out string strError)
            {
                bool bResult = false;
                strError = string.Empty;
                Ad_DC = null;
                if (string.IsNullOrEmpty(path))
                {
                    strError = "Path路径为空";
                    return false;
                }
                try
                {
                    Ad_DC = new DirectoryEntry(path);
                    bResult = true;
                }
                catch (Exception ex)
                {
                    //日志
                    strError = "实例化ADEntry失败,实例化Path路径为:" + path + ",Error:" + ex.Message;
                    bResult = false;
                }
                return bResult;
            }
    
            public static bool GetADEntryByLdap(string ldap, out DirectoryEntry Ad_DC, out string strError)
            {
                bool bResult = false;
                strError = string.Empty;
                Ad_DC = null;
                if (string.IsNullOrEmpty(ldap))
                {
                    strError = "ldap为空";
                    return false;
                }
                string path = string.Empty;
                try
                {
                    path = GetADPathByLdap(ldap);
                    Ad_DC = new DirectoryEntry(path);
                    bResult = true;
                }
                catch (COMException ex)
                {
                    //日志
                    strError = "实例化ADEntry失败,实例化Path路径为:" + path + ",Error:" + ex.Message;
                    bResult = false;
                }
                return bResult;
            }
    
            public static bool SecurityVerification(out string strError)
            {
                string admin = Convert.ToString(ConfigurationManager.AppSettings["Admin"]);
                string password = Convert.ToString(ConfigurationManager.AppSettings["Password"]);
                return SecurityVerification(admin, password, out  strError);
                ////模拟身份安全 begin
                //strError = string.Empty;
                //SubmitSecurity subSecurity = new SubmitSecurity();
                //string domain = Convert.ToString(ConfigurationManager.AppSettings["Domain"]);
                //string admin = Convert.ToString(ConfigurationManager.AppSettings["Admin"]);
                //string password = Convert.ToString(ConfigurationManager.AppSettings["Password"]);
                //if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(admin) && !string.IsNullOrEmpty(password))
                //{
                //    if (!subSecurity.impersonateValidUser(admin, domain, password))
                //    {
                //        strError = "用户名或密码错误,验证失败";
                //        return false;
                //    }
                //    else
                //    {
                //        return true;
                //    }
                //}
                //strError = "传值失败";
                //return false;
            }
            public static bool SecurityVerification(string account, string pwd, out string strError)
            {
                //模拟身份安全 begin
                SubmitSecurity subSecurity = new SubmitSecurity();
                string domain = Convert.ToString(ConfigurationManager.AppSettings["Domain"]);
                strError = string.Empty;
                if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(pwd) && !string.IsNullOrEmpty(account))
                {
                    if (!subSecurity.impersonateValidUser(account, domain, pwd))
                    {
                        strError = "用户名或密码错误,验证失败";
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                strError = "传值失败";
                return false;
            }
    
            public static bool GetADEntryByAccount(string path, string account, string pwd, out DirectoryEntry Ad_DC, out string strError)
            {
                bool bResult = false;
                strError = string.Empty;
                Ad_DC = null;
                //AD 身份验证
                //DirectoryEntry用于登陆ad全局只要存在的用户,deSearch.Filter则细化过滤指定ldap下的用户匹配
                if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(account) || string.IsNullOrEmpty(pwd))
                {
                    strError = "传值为空";
                    return false;
                }
                try
                {
                    DirectoryEntry de = new DirectoryEntry(path, account, pwd, AuthenticationTypes.Secure);
                    DirectorySearcher deSearch = new DirectorySearcher(de);
                    deSearch.Filter = "(&(objectClass=user)(userPrincipalName=" + account + "))";
                    deSearch.SearchScope = SearchScope.Subtree;
                    SearchResult resultDE = deSearch.FindOne();
                    if (resultDE != null)
                    {
                        Ad_DC = resultDE.GetDirectoryEntry();
                        bResult = true;
                    }
                    else
                    {
                        strError = "AD中不存在该用户";
                        bResult = false;
                    }
                }
                catch (Exception ex)
                {
                    strError = "验证出错,Error:" + ex.Message;
                    bResult = false;
                }
                return bResult;
            }
            public static bool GetADEntryByAccount(string account, string pwd, out DirectoryEntry Ad_DC, out string strError)
            {
                string path = GetRootADPath();
                return GetADEntryByAccount(path, account, pwd, out Ad_DC, out strError);
            }
    
            public static bool OperateLogger(SystemLogEntity logEntity, out string strError)
            {
                strError = string.Empty;
                DBUtility.Logger.Info(string.Format("用户:{0}操作信息:{1}时间:{2}", logEntity.User, logEntity.ErrorContext, logEntity.CreateTime));
                return false;
            }
            public static bool OperateLogger(OperateLoggerEntity logEntity, out string strError)
            {
                strError = string.Empty;
                DBUtility.Logger.Info(string.Format("用户:{0}操作类型:{1}操作信息:{2}被操作者:{3}操作结果(成功与否):{4}时间:{5}", logEntity.Account, logEntity.OperateType, logEntity.OperateContent, logEntity.OperateAccount, logEntity.OperateResult, logEntity.OperateTime));
                return false;
            }
            public static bool OperateLogger(string account, string operateAccount, string operateContent, out string strError)
            {
                strError = string.Empty;
                OperateLoggerEntity logEntity = new OperateLoggerEntity();
                logEntity.OperateContent = operateContent;
                logEntity.OperateAccount = operateAccount;
                logEntity.Account = account;
                logEntity.OperateResult = true;
                logEntity.OperateType = "AD用户操作";
                logEntity.OperateTime = DateTime.Now;
                DBUtility.Logger.Info(string.Format("用户:{0}操作类型:{1}操作信息:{2}被操作者:{3}操作结果(成功与否):{4}时间:{5}", logEntity.Account, logEntity.OperateType, logEntity.OperateContent, logEntity.OperateAccount, logEntity.OperateResult, logEntity.OperateTime));
                return false;
            }
        }
    }
    

      

  • 相关阅读:
    python json 和 pickle的补充 hashlib configparser logging
    go 流程语句 if goto for swich
    go array slice map make new操作
    go 基础
    块级元素 行内元素 空元素
    咽炎就医用药(慢性肥厚性咽炎)
    春季感冒是风寒还是风热(转的文章)
    秋季感冒 咳嗽 怎么选药
    解决IE浏览器“无法显示此网页”的问题
    常用的 css 样式 记录
  • 原文地址:https://www.cnblogs.com/wangfengderizi/p/2834025.html
Copyright © 2011-2022 走看看