Example #1
0
        private void Load()
        {
            // find the userid in the AD
            string ldap = LDAP_Server;

            System.DirectoryServices.DirectoryEntry    colleagues = new System.DirectoryServices.DirectoryEntry(ldap, LDAP_UserName, LDAP_Password);
            System.DirectoryServices.DirectorySearcher searcher   = new System.DirectoryServices.DirectorySearcher(colleagues);
            searcher.Filter       = "(&(objectClass=user)(samAccountName=" + _samAccount + "))";
            searcher.SearchScope  = System.DirectoryServices.SearchScope.Subtree;
            searcher.PageSize     = 9999999;
            searcher.CacheResults = true;

            System.DirectoryServices.SearchResultCollection results = null;

            results = searcher.FindAll();

            if (results.Count > 0)
            {
                System.DirectoryServices.DirectoryEntry entry = results[0].GetDirectoryEntry();
                _name             = GetProperty(entry, "displayName");
                _office           = GetProperty(entry, "physicalDeliveryOfficeName");
                _title            = GetProperty(entry, "title");
                _email            = GetProperty(entry, "mail");
                _phone            = GetProperty(entry, "telephoneNumber");
                _hasDirectReports = GetProperty(entry, "extensionAttribute5");
            }
        }
        public JsonResult ValidateLdapUser(string user)
        {
            Boolean userExists = false;

            System.DirectoryServices.SearchResultCollection sResults = null;
            string path      = "LDAP://Falabella.com";
            string criterios = "(&(objectClass=user)(samAccountName=" + user + "))";

            try
            {
                System.DirectoryServices.DirectoryEntry    dEntry    = new System.DirectoryServices.DirectoryEntry(path);
                System.DirectoryServices.DirectorySearcher dSearcher = new System.DirectoryServices.DirectorySearcher(dEntry);
                dSearcher.Filter = criterios;
                sResults         = dSearcher.FindAll();

                int result = sResults.Count;
                if (result >= 1)
                {
                    userExists = true;
                }
                else
                {
                    userExists = false;
                }
            }
            catch (Exception ex)
            {
                return(Json(userExists, JsonRequestBehavior.AllowGet));
            }

            return(Json(userExists, JsonRequestBehavior.AllowGet));
        }
        public JsonResult SearchUserLDAP()
        {
            Boolean userExists = false;

            System.DirectoryServices.SearchResultCollection sResults = null;
            string path      = "LDAP://201.217.205.157:389/DC =ita, DC=com";
            string criterios = "(&(objectClass=user))";

            try
            {
                System.DirectoryServices.DirectoryEntry    dEntry    = new System.DirectoryServices.DirectoryEntry(path);
                System.DirectoryServices.DirectorySearcher dSearcher = new System.DirectoryServices.DirectorySearcher(dEntry);
                dSearcher.Filter = criterios;
                sResults         = dSearcher.FindAll();

                int result = sResults.Count;
                if (result >= 1)
                {
                    userExists = true;
                }
                else
                {
                    userExists = false;
                }
            }
            catch (Exception ex)
            {
                return(Json(userExists, JsonRequestBehavior.AllowGet));
            }
            return(Json(userExists, JsonRequestBehavior.AllowGet));
        }
Example #4
0
        public void FindLockedAccounts()
        {
            System.DirectoryServices.ActiveDirectory.Forest forest = System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest();

            System.DirectoryServices.ActiveDirectory.DirectoryContext context = null;
            foreach (System.DirectoryServices.ActiveDirectory.Domain thisDomain in forest.Domains)
            {
                string domainName = thisDomain.Name;
                System.Console.WriteLine(domainName);
                context = new System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Domain, domainName);
            } // Next thisDomain

            //get our current domain policy
            System.DirectoryServices.ActiveDirectory.Domain domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(context);
            System.DirectoryServices.DirectoryEntry         root   = domain.GetDirectoryEntry();

            // System.DirectoryServices.DirectoryEntry AdRootDSE = new System.DirectoryServices.DirectoryEntry("LDAP://rootDSE");
            // string rootdse = System.Convert.ToString(AdRootDSE.Properties["defaultNamingContext"].Value);
            // System.DirectoryServices.DirectoryEntry root = new System.DirectoryServices.DirectoryEntry(rootdse);

            DomainPolicy policy = new DomainPolicy(root);


            //default for when accounts stay locked indefinitely
            string qry = "(lockoutTime>=1)";

            // System.TimeSpan duration = new TimeSpan(0, 30, 0);
            System.TimeSpan duration = policy.LockoutDuration;

            if (duration != System.TimeSpan.MaxValue)
            {
                System.DateTime lockoutThreshold = System.DateTime.Now.Subtract(duration);
                qry = string.Format("(lockoutTime>={0})", lockoutThreshold.ToFileTime());
            } // End if (duration != System.TimeSpan.MaxValue)

            System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(root, qry);

            using (System.DirectoryServices.SearchResultCollection src = ds.FindAll())
            {
                foreach (System.DirectoryServices.SearchResult sr in src)
                {
                    long ticks = (long)sr.Properties["lockoutTime"][0];
                    System.Console.WriteLine("{0} locked out at {1}", sr.Properties["name"][0], System.DateTime.FromFileTime(ticks));
                } // Next sr
            }     // End Using src
        }         // End Sub FindLockedAccounts
        private void GetAllUsers()
        {
            System.DirectoryServices.SearchResultCollection sResulta2  = null;
            System.DirectoryServices.DirectorySearcher      dsBuscador = null;

            string path      = "LDAP://201.217.205.157:389/DC =ita, DC=com";
            string criterios = "(&(objectClass=user))";

            System.DirectoryServices.DirectoryEntry dEntry = new System.DirectoryServices.DirectoryEntry(path);


            dsBuscador        = new System.DirectoryServices.DirectorySearcher(dEntry);
            dsBuscador.Filter = "(&(objectCategory=User)(objectClass=person))";

            sResulta2 = dsBuscador.FindAll();

            foreach (System.DirectoryServices.SearchResult sr in sResulta2)
            {
                // Agregar usuarios a combo
            }
        }
Example #6
0
 private static System.Data.DataTable GetDataSourceLDAP(System.String book, System.String connectstring, System.String connectusername, System.String connectpassword, System.String searchfilter, System.String namecolumn, System.String mailcolumn, System.String ownercolumn)
 {
     System.Data.DataTable datasource = GetDataSourceDataTable(namecolumn, mailcolumn, ownercolumn, book);
     System.DirectoryServices.DirectoryEntry direntry = new System.DirectoryServices.DirectoryEntry(connectstring);
     direntry.Username = connectusername;
     direntry.Password = connectpassword;
     System.DirectoryServices.DirectorySearcher dirsearcher = new System.DirectoryServices.DirectorySearcher(direntry);
     dirsearcher.Filter      = searchfilter;
     dirsearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
     dirsearcher.PropertiesToLoad.Add(namecolumn);
     dirsearcher.PropertiesToLoad.Add(mailcolumn);
     System.DirectoryServices.SearchResultCollection results = null;
     try {
         results = dirsearcher.FindAll();
     } catch (System.Exception e) {
         if (log.IsErrorEnabled)
         {
             log.Error("Error while doing LDAP query", e);
         }
         return(null);
     }
     System.String name, value;
     foreach (System.DirectoryServices.SearchResult result in results)
     {
         name  = null;
         value = null;
         if (result.Properties.Contains(namecolumn) && result.Properties.Contains(mailcolumn) && result.Properties[namecolumn].Count > 0 && result.Properties[mailcolumn].Count > 0)
         {
             name  = result.Properties[namecolumn][0].ToString();
             value = result.Properties[mailcolumn][0].ToString();
         }
         if (name != null && value != null)
         {
             try {
                 datasource.Rows.Add(new object[] { name, value });
             } catch (System.Exception) {}
         }
     }
     return(datasource);
 }
        } // End Function GetUserList

        private System.Data.DataTable GetUserList(string strUserName)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            dt.Columns.Add("sAMAccountName", typeof(string));
            dt.Columns.Add("DistinguishedName", typeof(string));
            dt.Columns.Add("cn", typeof(string));
            dt.Columns.Add("DisplayName", typeof(string));

            dt.Columns.Add("EmailAddress", typeof(string));
            dt.Columns.Add("DomainName", typeof(string));
            dt.Columns.Add("Department", typeof(string));
            dt.Columns.Add("title", typeof(string));
            dt.Columns.Add("company", typeof(string));
            dt.Columns.Add("memberof", typeof(string));


            //using (System.DirectoryServices.DirectoryEntry rootDSE = new System.DirectoryServices.DirectoryEntry("LDAP://DC=cor,DC=local", username, password))
            using (System.DirectoryServices.DirectoryEntry rootDSE = LdapTools.GetDE(m_RootDn))
            {
                using (System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(rootDSE))
                {
                    search.PageSize = 1001;// To Pull up more than 100 records.

                    //search.Filter = "(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";//UserAccountControl will only Include Non-Disabled Users.

                    string strUserCondition = "";
                    if (!string.IsNullOrEmpty(strUserName))
                    {
                        // strUserCondition = "(samAccountName=" + strUserName + ")";
                        strUserCondition  = "(|(samAccountName=" + strUserName + ")";
                        strUserCondition += "(userPrincipalName=" + strUserName + ")";
                        strUserCondition += "(mail=" + strUserName + "))";
                    }


                    //UserAccountControl will only Include Non-Disabled Users.
                    //search.Filter = "(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(samAccountName=stefan.steiger))";

                    search.Filter = string.Format("(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2){0})", strUserCondition);

                    using (System.DirectoryServices.SearchResultCollection result = search.FindAll())
                    {
                        foreach (System.DirectoryServices.SearchResult item in result)
                        {
                            string sAMAccountName    = null;
                            string DistinguishedName = null;
                            string cn           = null;
                            string DisplayName  = null;
                            string EmailAddress = null;
                            string DomainName   = null;
                            string Department   = null;
                            string title        = null;
                            string company      = null;
                            string memberof     = null;


                            if (item.Properties["sAMAccountName"].Count > 0)
                            {
                                sAMAccountName = item.Properties["sAMAccountName"][0].ToString();
                            }

                            if (item.Properties["distinguishedName"].Count > 0)
                            {
                                DistinguishedName = item.Properties["distinguishedName"][0].ToString();
                            }

                            if (item.Properties["cn"].Count > 0)
                            {
                                cn = item.Properties["cn"][0].ToString();
                            }

                            if (item.Properties["DisplayName"].Count > 0)
                            {
                                DisplayName = item.Properties["DisplayName"][0].ToString();
                            }

                            if (item.Properties["mail"].Count > 0)
                            {
                                EmailAddress = item.Properties["mail"][0].ToString();
                            }

                            if (item.Properties["SamAccountName"].Count > 0)
                            {
                                DomainName = item.Properties["SamAccountName"][0].ToString();
                            }

                            if (item.Properties["department"].Count > 0)
                            {
                                Department = item.Properties["department"][0].ToString();
                            }

                            if (item.Properties["title"].Count > 0)
                            {
                                title = item.Properties["title"][0].ToString();
                            }

                            if (item.Properties["company"].Count > 0)
                            {
                                company = item.Properties["company"][0].ToString();
                            }

                            if (item.Properties["DistinguishedName"].Count > 0)
                            {
                                DistinguishedName = item.Properties["DistinguishedName"][0].ToString();
                            }

                            if (item.Properties["memberof"].Count > 0)
                            {
                                // memberof = item.Properties["memberof"][0].ToString();
                                memberof = LdapTools.GetGroups(DistinguishedName, true);
                            }


                            if (item.Properties["AccountExpirationDate"].Count > 0)
                            {
                                string aaa = item.Properties["AccountExpirationDate"][0].ToString();
                            }


                            System.Data.DataRow dr = dt.NewRow();

                            dr["sAMAccountName"]    = sAMAccountName;
                            dr["DistinguishedName"] = DistinguishedName;
                            dr["cn"]           = cn;
                            dr["DisplayName"]  = DisplayName;
                            dr["EmailAddress"] = EmailAddress;
                            dr["DomainName"]   = DomainName;
                            dr["Department"]   = Department;
                            dr["title"]        = title;
                            dr["company"]      = company;
                            dr["memberof"]     = memberof;

                            dt.Rows.Add(dr);



                            DisplayName  = string.Empty;
                            EmailAddress = string.Empty;
                            DomainName   = string.Empty;
                            Department   = string.Empty;
                            title        = string.Empty;
                            company      = string.Empty;
                            memberof     = string.Empty;

                            //rootDSE.Dispose();
                        } // Next SearchResult item
                    }     // End Using SearchResultCollection result
                }         // End Using search
            }             // End Using rootDSE

            return(dt);
        } // End Function GetUserList
        } // End Function GetUserList

        private System.Data.DataTable GetGroupList(string strUserName)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            dt.Columns.Add("sAMAccountName", typeof(string));
            dt.Columns.Add("DistinguishedName", typeof(string));
            dt.Columns.Add("cn", typeof(string));
            dt.Columns.Add("DomainName", typeof(string));


            //using (System.DirectoryServices.DirectoryEntry rootDSE = new System.DirectoryServices.DirectoryEntry("LDAP://DC=cor,DC=local", username, password))
            using (System.DirectoryServices.DirectoryEntry rootDSE = LdapTools.GetDE(m_RootDn))
            {
                using (System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(rootDSE))
                {
                    search.PageSize = 1001;// To Pull up more than 100 records.

                    //search.Filter = "(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";//UserAccountControl will only Include Non-Disabled Users.

                    string strUserCondition = "";
                    if (!string.IsNullOrEmpty(strUserName))
                    {
                        // strUserCondition = "(samAccountName=" + strUserName + ")";
                        strUserCondition  = "(|(samAccountName=" + strUserName + ")";
                        strUserCondition += "(cn=" + strUserName + ")";
                        strUserCondition += "(name=" + strUserName + "))";
                    }


                    //UserAccountControl will only Include Non-Disabled Users.
                    //search.Filter = "(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(samAccountName=stefan.steiger))";
                    search.Filter = string.Format("(&(objectClass=group)(!userAccountControl:1.2.840.113556.1.4.803:=2){0})", strUserCondition);

                    using (System.DirectoryServices.SearchResultCollection result = search.FindAll())
                    {
                        foreach (System.DirectoryServices.SearchResult item in result)
                        {
                            string sAMAccountName    = null;
                            string DistinguishedName = null;
                            string cn         = null;
                            string DomainName = null;


                            if (item.Properties["sAMAccountName"].Count > 0)
                            {
                                sAMAccountName = item.Properties["sAMAccountName"][0].ToString();
                            }

                            if (item.Properties["distinguishedName"].Count > 0)
                            {
                                DistinguishedName = item.Properties["distinguishedName"][0].ToString();
                            }

                            if (item.Properties["cn"].Count > 0)
                            {
                                cn = item.Properties["cn"][0].ToString();
                            }


                            if (item.Properties["SamAccountName"].Count > 0)
                            {
                                DomainName = item.Properties["SamAccountName"][0].ToString();
                            }


                            if (item.Properties["DistinguishedName"].Count > 0)
                            {
                                DistinguishedName = item.Properties["DistinguishedName"][0].ToString();
                            }


                            System.Data.DataRow dr = dt.NewRow();

                            dr["sAMAccountName"]    = sAMAccountName;
                            dr["DistinguishedName"] = DistinguishedName;
                            dr["cn"]         = cn;
                            dr["DomainName"] = DomainName;

                            dt.Rows.Add(dr);

                            sAMAccountName    = string.Empty;
                            DistinguishedName = string.Empty;
                            cn         = string.Empty;
                            DomainName = string.Empty;

                            //rootDSE.Dispose();
                        } // Next SearchResult item
                    }     // End Using SearchResultCollection result
                }         // End Using search
            }             // End Using rootDSE

            return(dt);
        } // End Function GetGroupList
Example #9
0
        static void GetGroupMembers()
        {
            string ldapHost = MySamples.TestSettings.ldapHost;
            int    ldapPort = MySamples.TestSettings.ldapPort;//System.Convert.ToInt32(args[1]);

            string msldap = $"LDAP://{ldapHost}:{ldapPort}/DC=COR,DC=local";
            string ms1    = $"LDAP://{ldapHost}:{ldapPort}/OU=Gruppen,OU=COR,DC=COR,DC=local";

            string loginDN  = MySamples.TestSettings.loginDN;  // args[2];
            string password = MySamples.TestSettings.password; // args[3];

            string strGroup = "COR-VMPost";

            strGroup = "G-ADM-APERTURE-UAT";

            // System.DirectoryServices.AccountManagement.
            //bool valid = false;
            //// https://stackoverflow.com/questions/326818/how-to-validate-domain-credentials
            //using (System.DirectoryServices.AccountManagement.PrincipalContext context =
            //    new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain))
            //{
            //    valid = context.ValidateCredentials("username", "password");
            //}

            bool bException = false;

            using (System.DirectoryServices.DirectoryEntry ldapConnection =
                       new System.DirectoryServices.DirectoryEntry(msldap, loginDN, password))
            {
                try
                {
                    // deRootObject.boun
                    if (ldapConnection.NativeObject == null)
                    {
                        bException = true;
                    }
                }
                catch (System.Exception ex)
                {
                    bException = true;
                    System.Console.WriteLine(ex.Message);
                    System.Console.WriteLine(ex.StackTrace);
                    throw new System.InvalidOperationException("Cannot login with wrong credentials or LDAP-Path.");
                }

                using (System.DirectoryServices.DirectorySearcher dsSearcher =
                           new System.DirectoryServices.DirectorySearcher(ldapConnection))
                {
                    dsSearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                    dsSearcher.Filter      = "(&(objectCategory=group)(CN=" + strGroup + "))";

                    using (System.DirectoryServices.SearchResultCollection srcSearchResultCollection =
                               dsSearcher.FindAll())
                    {
                        try
                        {
                            foreach (System.DirectoryServices.SearchResult srSearchResult in srcSearchResultCollection)
                            {
                                System.DirectoryServices.ResultPropertyCollection resultPropColl = srSearchResult.Properties;
                                System.DirectoryServices.PropertyValueCollection  memberProperty = srSearchResult.GetDirectoryEntry().Properties["member"];

                                for (int i = 0; i < memberProperty.Count; ++i)
                                {
                                    string strUserName = System.Convert.ToString(memberProperty[i]);
                                    System.Console.WriteLine(strUserName);
                                } // Next i
                            }     // Next srSearchResult
                        }         // End Try
                        catch (System.Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                            System.Console.WriteLine(ex.StackTrace);
                        }
                    } // End using srcSearchResultCollection
                }     // End Using dsSearcher
            }         // End Using ldapConnection

            System.Console.WriteLine(System.Environment.NewLine);
            System.Console.WriteLine(" --- Press any key to continue --- ");
            System.Console.ReadKey();
        }
Example #10
0
        /// <summary>
        /// 验证域用户
        /// </summary>
        /// <param name="account">域账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public object queryUser()
        {
            try
            {
                string        accounts    = HttpContext.Current.Request["accounts"];
                StringBuilder sb          = new StringBuilder();
                string        domainIP    = Config.GetValue("DomainName"); //域名
                string        userAccount = Config.GetValue("Account");    //域账号
                string        Password    = Config.GetValue("Pwd");        //域账号密码          
                using (System.DirectoryServices.DirectoryEntry deUser = new System.DirectoryServices.DirectoryEntry(@"LDAP://" + domainIP, userAccount, Password))
                {
                    System.DirectoryServices.DirectorySearcher src = new System.DirectoryServices.DirectorySearcher(deUser);
                    if (!string.IsNullOrWhiteSpace(accounts))
                    {
                        StringBuilder sbAcounts = new StringBuilder();
                        string[]      arr       = accounts.Split(',');
                        foreach (string str in arr)
                        {
                            sbAcounts.AppendFormat("(sAMAccountName=*{0})", accounts);
                        }
                        src.Filter = string.Format("(&(objectClass=user)(company=*广西华昇新材料有限公司)(|({0})))", sbAcounts.ToString());//筛选条件
                    }
                    else
                    {
                        src.Filter = "(&(objectClass=user)(company=*广西华昇新材料有限公司))";//筛选条件
                    }
                    src.SearchRoot  = deUser;
                    src.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                    System.DirectoryServices.SearchResultCollection results = src.FindAll();

                    sb.AppendFormat("总共{0}条记录\n", results.Count);
                    foreach (System.DirectoryServices.SearchResult result in results)
                    {
                        System.DirectoryServices.PropertyCollection rprops = result.GetDirectoryEntry().Properties;
                        string account = "";
                        //获取账号
                        if (rprops["sAMAccountName"] != null)
                        {
                            if (rprops["sAMAccountName"].Value != null)
                            {
                                account = rprops["sAMAccountName"].Value.ToString();
                            }
                        }
                        string realName = "";
                        //获取姓名
                        if (rprops["displayName"] != null)
                        {
                            if (rprops["displayName"].Value != null)
                            {
                                realName = rprops["displayName"].Value.ToString();
                            }
                        }
                        string mobile = "";
                        //获取手机号
                        if (rprops["telephoneNumber"] != null)
                        {
                            if (rprops["telephoneNumber"].Value != null)
                            {
                                mobile = rprops["telephoneNumber"].Value.ToString();
                            }
                        }
                        string department = "";
                        //获取部门名称
                        if (rprops["department"] != null)
                        {
                            if (rprops["department"].Value != null)
                            {
                                department = rprops["department"].Value.ToString();
                            }
                        }
                        sb.AppendFormat("账号:{0},姓名:{1},手机号:{2},部门:{3}\n", account, realName, mobile, department);
                        sb.Append("\n");
                    }
                }
                return(new { code = 0, message = sb.ToString() });
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText(string.Format(@"D:\logs\{0}.log", DateTime.Now.ToString("yyyyMMdd")), ex.Message);
                return(new { code = 1, message = ex.Message });
            }
        }
Example #11
0
        // GET api/<controller>/5
        /// <summary>
        /// 获取域用户信息并更新系统用户(广西华昇)
        /// </summary>
        /// <param name="accounts">需要同步的用户账号(多个用逗号分隔)</param>
        /// <param name="orgId">单位Id</param>
        /// <returns></returns>
        public object SyncUser(string orgId = "2b322255-c10b-a8e6-8bd1-d2fcc7e677f8")
        {
            try
            {
                string        accounts    = HttpContext.Current.Request["accounts"]; //需要更新的账号,为空则获取更新所有匹配的用户
                StringBuilder sb          = new StringBuilder();
                string        domainIP    = Config.GetValue("DomainName");           //域名
                string        userAccount = Config.GetValue("Account");              //域账号
                string        Password    = Config.GetValue("Pwd");                  //域账号密码          
                using (System.DirectoryServices.DirectoryEntry deUser = new System.DirectoryServices.DirectoryEntry(@"LDAP://" + domainIP, userAccount, Password))
                {
                    System.DirectoryServices.DirectorySearcher src = new System.DirectoryServices.DirectorySearcher(deUser);
                    if (!string.IsNullOrWhiteSpace(accounts))
                    {
                        StringBuilder sbAcounts = new StringBuilder();
                        string[]      arr       = accounts.Split(',');
                        foreach (string str in arr)
                        {
                            sbAcounts.AppendFormat("(sAMAccountName=*{0})", accounts);
                        }
                        src.Filter = string.Format("(&(objectClass=user)(company=*广西华昇新材料有限公司)(|({0})))", sbAcounts.ToString());//筛选条件
                    }
                    else
                    {
                        src.Filter = "(&(objectClass=user)(company=*广西华昇新材料有限公司))";//筛选条件
                    }
                    //src.PropertiesToLoad.Add("cn");
                    src.SearchRoot  = deUser;
                    src.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                    System.DirectoryServices.SearchResultCollection results = src.FindAll();

                    sb.AppendFormat("总共{0}条记录\n", results.Count);
                    List <object>     list     = new List <object>();
                    List <UserEntity> lstUsers = new List <UserEntity>();
                    DepartmentEntity  org      = deptBll.GetEntity(orgId);
                    string            orgCode  = org.EnCode;
                    foreach (System.DirectoryServices.SearchResult result in results)
                    {
                        System.DirectoryServices.PropertyCollection rprops = result.GetDirectoryEntry().Properties;
                        string account = "";
                        //获取账号
                        if (rprops["sAMAccountName"] != null)
                        {
                            if (rprops["sAMAccountName"].Value != null)
                            {
                                account = rprops["sAMAccountName"].Value.ToString();
                            }
                        }
                        string realName = "";
                        //获取姓名
                        if (rprops["displayName"] != null)
                        {
                            if (rprops["displayName"].Value != null)
                            {
                                realName = rprops["displayName"].Value.ToString();
                            }
                        }
                        string mobile = "";
                        //获取手机号
                        if (rprops["telephoneNumber"] != null)
                        {
                            if (rprops["telephoneNumber"].Value != null)
                            {
                                mobile = rprops["telephoneNumber"].Value.ToString();
                            }
                        }
                        string department = "";
                        string deptId     = ""; //部门ID
                        string deptCode   = ""; //部门编码
                        string pxDeptId   = ""; //培训平台部门ID
                        string pxDeptCode = ""; //培训平台部门编码
                        string roleId     = ""; //角色ID
                        string roleName   = ""; //角色名称
                        //获取部门名称
                        if (rprops["department"] != null)
                        {
                            if (rprops["department"].Value != null)
                            {
                                department = rprops["department"].Value.ToString();
                                System.Data.DataTable dtDept = new System.Data.DataTable();
                                System.Data.DataTable dtRole = new System.Data.DataTable();
                                if (department == "公司领导")
                                {
                                    deptId   = pxDeptId = orgId;
                                    deptCode = pxDeptCode = orgCode;
                                    dtDept   = deptBll.GetDataTable(string.Format("select d.departmentid,d.encode,d.deptkey from base_department d where departmentid='{0}'", orgId));

                                    //如果是公司领导则赋予普通用户和公司级用户角色
                                    dtRole = deptBll.GetDataTable(string.Format("select r.roleid,r.fullname from base_role r where r.category=1 and fullname in('普通用户','公司级用户')"));
                                }
                                else //如果是部门
                                {
                                    dtDept = deptBll.GetDataTable(string.Format("select d.departmentid,d.encode,d.deptkey from base_department d where organizeid='{1}' and d.fullname='{0}'", department, orgId));

                                    //如果是公司领导则赋予普通用户和部门级用户角色
                                    dtRole = deptBll.GetDataTable(string.Format("select r.roleid,r.fullname from base_role r where r.category=1 and fullname in('普通用户','部门级用户')"));
                                }
                                if (dtRole.Rows.Count > 0)
                                {
                                    roleId   = string.Join(",", dtRole.AsEnumerable().Select(t => t.Field <string>("roleid")).ToArray());
                                    roleName = string.Join(",", dtRole.AsEnumerable().Select(t => t.Field <string>("fullname")).ToArray());
                                }

                                if (dtDept.Rows.Count > 0)
                                {
                                    deptId   = pxDeptId = dtDept.Rows[0][0].ToString();
                                    deptCode = pxDeptCode = dtDept.Rows[0][1].ToString();
                                    string deptKey = dtDept.Rows[0][2].ToString();
                                    //转换成培训平台对应的部门ID
                                    if (!string.IsNullOrWhiteSpace(deptKey))
                                    {
                                        string[] arr = deptKey.Split('|');
                                        pxDeptId = arr[0];
                                        if (arr.Length > 1)
                                        {
                                            pxDeptCode = arr[1];
                                        }
                                    }
                                }
                                else  //部门名称不匹配
                                {
                                    sb.AppendFormat("用户(账号:{0},姓名:{1},部门:{2})部门与系统部门名称不匹配,无法同步!\n", account, realName, department);
                                    continue;
                                }
                            }
                        }
                        sb.AppendFormat("账号:{0},姓名:{1},手机号:{2},部门:{3}\n", account, realName, mobile, department);
                        sb.Append("\n");
                        System.Data.DataTable dtUser = deptBll.GetDataTable(string.Format("select userid from base_user where account='{0}'", account));

                        UserEntity user     = new UserEntity();
                        string     action   = "add";
                        string     userId   = Guid.NewGuid().ToString();
                        string     password = "******";
                        if (dtUser.Rows.Count > 0)  //修改
                        {
                            action = "edit";
                            userId = dtUser.Rows[0][0].ToString();

                            user     = userBll.GetEntity(userId);
                            password = null;
                            if (user.RoleName.Contains("部门级"))
                            {
                                user.DepartmentId   = deptId;
                                user.DepartmentCode = deptCode;
                            }
                        }
                        else   //新增
                        {
                            user.UserId         = userId;
                            user.Account        = account;
                            user.Password       = password;
                            user.RoleId         = roleId;
                            user.RoleName       = roleName;
                            user.IsEpiboly      = "0";
                            user.IsPresence     = "1";
                            user.DeleteMark     = 0;
                            user.EnabledMark    = 1;
                            user.DepartmentId   = deptId;
                            user.DepartmentCode = deptCode;
                            user.OrganizeCode   = orgCode;
                            user.OrganizeId     = orgId;
                        }
                        user.OpenId   = 1; //此字段标记数据来源于预控用户
                        user.RealName = realName;
                        user.Mobile   = mobile;
                        userId        = userBll.SaveForm(userId, user);
                        if (!string.IsNullOrWhiteSpace(userId))
                        {
                            object obj = new
                            {
                                action     = action,
                                time       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                userId     = userId,
                                userName   = realName,
                                password   = password,
                                account    = account,
                                deptId     = pxDeptId,
                                deptCode   = pxDeptCode,
                                sex        = user.Gender,
                                idCard     = user.IdentifyID,
                                email      = user.Email,
                                mobile     = user.Mobile,
                                birth      = user.Birthday,
                                postId     = user.DutyId,
                                postName   = user.DutyName,          //岗位
                                age        = user.Age.ToIntOrNull(), //年龄
                                native     = user.Native,            //籍贯
                                nation     = user.Nation,            //民族
                                encode     = user.EnCode,            //工号
                                jobTitle   = user.JobTitle,
                                techLevel  = user.TechnicalGrade,
                                workType   = user.Craft,
                                companyId  = org.InnerPhone,
                                trainRoles = user.TrainRoleId,
                                role       = 0//角色(0:学员,1:培训管理员)
                            };
                            list.Add(obj);
                            user.Password = password;
                            lstUsers.Add(user);
                            sb.AppendFormat("已同步用户信息(账号:{0},姓名:{1},部门:{2},手机号:{3})!\n", account, realName, department, mobile);
                        }
                    }
                    //推送用户数据到消息队列
                    if (list.Count > 0)
                    {
                        if (list.Count > 50)
                        {
                            int page  = 0;
                            int total = list.Count;
                            if (total % 50 == 0)
                            {
                                page = total / 50;
                            }
                            else
                            {
                                page = total / 50 + 1;
                            }
                            for (int j = 0; j < page; j++)
                            {
                                Busines.JPush.JPushApi.PushMessage(list.Skip(j * 50).Take(50), 1);
                            }
                        }
                        else
                        {
                            Busines.JPush.JPushApi.PushMessage(list, 1);
                        }
                        System.IO.File.AppendAllText(string.Format(@"D:\logs\{0}.log", DateTime.Now.ToString("yyyyMMdd")), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + list.ToJson() + "\n\n");
                    }
                    //同步用户信息到班组
                    if (lstUsers.Count > 0)
                    {
                        ImportUsersToBZ(lstUsers);
                    }
                }
                return(new { code = 0, message = sb.ToString() });
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText(string.Format(@"D:\logs\{0}.log", DateTime.Now.ToString("yyyyMMdd")), ex.Message);
                return(new { code = 1, message = ex.Message });
            }
        }