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));
        }
Example #2
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 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 static IEnumerable <SyncRecord> DcSyncAll(DcSyncAllSettings settings)
        {
            if (User.IsSystem())
            {
                throw new InvalidOperationException("Current session is running as SYSTEM, dcsync won't work.");
            }

            System.Diagnostics.Debug.Write("[PSH BINDING - DCSYNCALL] User is not running as SYSTEM.");

            if (string.IsNullOrEmpty(settings.Domain))
            {
                settings.Domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
            }

            if (string.IsNullOrEmpty(settings.Domain))
            {
                throw new ArgumentException("Domain parameter must be specified.");
            }

            System.Diagnostics.Debug.WriteLine("[PSH BINDING - DCSYNCALL] Running against domain " + settings.Domain);

            using (var adRoot = new System.DirectoryServices.DirectoryEntry(string.Format("LDAP://{0}", settings.Domain)))
                using (var searcher = new System.DirectoryServices.DirectorySearcher(adRoot))
                {
                    searcher.SearchScope     = System.DirectoryServices.SearchScope.Subtree;
                    searcher.ReferralChasing = System.DirectoryServices.ReferralChasingOption.All;
                    searcher.Filter          = "(objectClass=user)";
                    searcher.PropertiesToLoad.Add("samAccountName");

                    using (var searchResults = searcher.FindAll())
                    {
                        System.Diagnostics.Debug.WriteLine("[PSH BINDING - DCSYNCALL] Search resulted in results: " + searchResults.Count.ToString());
                        foreach (System.DirectoryServices.SearchResult searchResult in searchResults)
                        {
                            if (searchResult != null)
                            {
                                var username = searchResult.Properties["samAccountName"][0].ToString();
                                System.Diagnostics.Debug.WriteLine("[PSH BINDING - DCSYNCALL] Found account: " + username);

                                if (settings.IncludeMachineAccounts || !username.EndsWith("$"))
                                {
                                    var record = DcSync(string.Format("{0}\\{1}", settings.Domain, username), settings.DomainController, settings.DomainFqdn);

                                    if (record != null && (settings.IncludeEmpty || !string.IsNullOrEmpty(record.NtlmHash)))
                                    {
                                        yield return(record);
                                    }
                                }
                            }
                        }
                    }
                }
        }
Example #5
0
        } // End Sub cbIntegratedSecurity_CheckedChanged

        static void test()
        {
            string domainAndUsername = string.Empty;
            string domain            = string.Empty;
            string userName          = string.Empty;
            string passWord          = string.Empty;

            System.DirectoryServices.AuthenticationTypes at = System.DirectoryServices.AuthenticationTypes.Anonymous;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            domain            = @"LDAP://w.x.y.z";
            domainAndUsername = @"LDAP://w.x.y.z/cn=Lawrence E." + @" Smithmier\, Jr.,cn=Users,dc=corp," + "dc=productiveedge,dc=com";
            userName          = "******";
            passWord          = "******";
            at = System.DirectoryServices.AuthenticationTypes.Secure;

            System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(domain, userName, passWord, at);

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

            System.DirectoryServices.SearchResultCollection results;
            string filter = "maxPwdAge=*";

            mySearcher.Filter = filter;

            results = mySearcher.FindAll();
            long maxDays = 0;

            if (results.Count >= 1)
            {
                long maxPwdAge = (long)results[0].Properties["maxPwdAge"][0];
                maxDays = maxPwdAge / -864000000000;
            } // End if (results.Count >= 1)

            System.DirectoryServices.DirectoryEntry entryUser = new System.DirectoryServices.DirectoryEntry(domainAndUsername, userName, passWord, at);
            mySearcher = new System.DirectoryServices.DirectorySearcher(entryUser);

            results = mySearcher.FindAll();
            long daysLeft = 0;

            if (results.Count >= 1)
            {
                var lastChanged = results[0].Properties["pwdLastSet"][0];
                daysLeft = maxDays - System.DateTime.Today.Subtract(System.DateTime.FromFileTime((long)lastChanged)).Days;
            } // End if (results.Count >= 1)

            System.Console.WriteLine("You must change your password within {0} days", daysLeft);
            System.Console.ReadLine();
        }
Example #6
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 #8
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);
 }
        public bool GetADInformation()
        {
            string strUserId = "", strFilter = "";

            if(!SAMAccountName.Equals( "" ))
            {
                strUserId = SAMAccountName;

                if(strUserId.Contains( @"\" ))
                    strUserId = strUserId.Substring( 5 );

                // only EmCare/EMSC users
                strFilter = string.Format( "(|(&(objectClass=User)(sAMAccountName={0})(|(company=EmCare*)(company=EMSC*))))", strUserId );
            }

            if(!LastName.Equals( "" ))
                // only EmCare/EMSC users
                strFilter = string.Format( "(|(&(objectClass=User)(givenname={0})(sn={1})(|(company=EmCare*)(company=EMSC*))))", FirstName, LastName );

            string strServer = System.Configuration.ConfigurationManager.AppSettings["EMSC"].ToString();
            string strADUser = System.Configuration.ConfigurationManager.AppSettings["LDAPUID"].ToString();
            string strADPwd = System.Configuration.ConfigurationManager.AppSettings["LDAPPwd"].ToString();

            string sLDAPPath = string.Format("LDAP://{0}/DC=EMSC,DC=root01,DC=org", strServer);
            System.DirectoryServices.DirectoryEntry objDE = null;
            System.DirectoryServices.DirectorySearcher objDS = null;
            try
            {
                objDE = new System.DirectoryServices.DirectoryEntry( sLDAPPath, strADUser, strADPwd, System.DirectoryServices.AuthenticationTypes.Secure );

                objDS = new System.DirectoryServices.DirectorySearcher( objDE );

                // get the LDAP filter string based on selections
                objDS.Filter = strFilter;
                objDS.ReferralChasing = System.DirectoryServices.ReferralChasingOption.None;

                //String strResult = String.Format(
                //"(&(objectClass={0})(givenname={1})(sn={2}))",
                //sLDAPUserObjectClass, sFirstNameSearchFilter, sLastNameSearchFilter);
                //string sFilter =
                //String.Format("(&(objectclass=user)(MemberOf=CN={0},OU=Groups,DC={1},DC=root01,DC=org))",
                //    strGroupName, strDomain);

                objDS.PropertiesToLoad.Add( "userAccountControl" );
                objDS.PropertiesToLoad.Add( "SAMAccountName" );
                objDS.PropertiesToLoad.Add( "givenName" );
                objDS.PropertiesToLoad.Add( "sn" );
                objDS.PropertiesToLoad.Add( "TelephoneNumber" );
                objDS.PropertiesToLoad.Add( "mail" );
                objDS.PropertiesToLoad.Add( "title" );
                objDS.PropertiesToLoad.Add( "department" );
                objDS.PropertiesToLoad.Add( "company" );
                objDS.PropertiesToLoad.Add( "physicalDeliveryOfficeName" );
                objDS.PropertiesToLoad.Add( "displayName" );

                //start searching
                System.DirectoryServices.SearchResultCollection objSRC = objDS.FindAll();

                try
                {
                    if( objSRC.Count != 0 )
                    {
                        //if(objSRC.Count > 1)
                        //    Found = Found;

                        // grab the first search result
                        System.DirectoryServices.SearchResult objSR = objSRC[ 0 ];

                        Found = true;

                        displayName = objSR.Properties[ "displayName" ][ 0 ].ToString();
                        givenName = objSR.Properties[ "givenName" ][ 0 ].ToString();
                        sn = objSR.Properties[ "sn" ][ 0 ].ToString();
                        SAMAccountName = objSR.Properties[ "SAMAccountName" ][ 0 ].ToString();

                        userAccountControl = objSR.Properties[ "userAccountControl" ][ 0 ].ToString();
                        int iInactiveFlag = Convert.ToInt32( userAccountControl );
                        iInactiveFlag = iInactiveFlag & 0x0002;
                        Active = iInactiveFlag <= 0;

                        if( objSR.Properties[ "TelephoneNumber" ].Count > 0 )
                            TelephoneNumber = objSR.Properties[ "TelephoneNumber" ][ 0 ].ToString();
                        if( objSR.Properties[ "mail" ].Count > 0 )
                            mail = objSR.Properties[ "mail" ][ 0 ].ToString();
                        if( objSR.Properties[ "title" ].Count > 0 )
                            title = objSR.Properties[ "title" ][ 0 ].ToString();
                        if( objSR.Properties[ "department" ].Count > 0 )
                            department = objSR.Properties[ "department" ][ 0 ].ToString();
                        if( objSR.Properties[ "company" ].Count > 0 )
                            company = objSR.Properties[ "company" ][ 0 ].ToString();
                        if( objSR.Properties[ "physicalDeliveryOfficeName" ].Count > 0 )
                            physicalDeliveryOfficeName = objSR.Properties[ "physicalDeliveryOfficeName" ][ 0 ].ToString();
                    }
                    else
                    {
                        Found = false;
                        return Found;
                    }
                }
                catch( Exception )
                {
                    // ignore errors
                    Found = false;
                    return false;
                }
                finally
                {
                    objDE.Dispose();
                    objSRC.Dispose();
                    //objDS.Dispose();
                }
            }
            catch( Exception )
            {
                // ignore errors
                Found = false;
                return false;
            }
            finally
            {
                objDS.Dispose();
            }

            return Found;
        }
Example #10
0
        public void DatenAusAd()
        {
            try
            {
                // Deklaration für das DirectoryEntry
                System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(Properties.Settings.Default.Organisationseinheit);
                string DomainDN = System.Convert.ToString(entry.Properties["DefaultNamingContext"].Value);
                System.DirectoryServices.DirectoryEntry    ADEntry    = new System.DirectoryServices.DirectoryEntry(Properties.Settings.Default.Organisationseinheit + DomainDN);
                System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(ADEntry);


                mySearcher.Filter = "(& (objectCategory=Person)(objectClass=user)(sAMAccountName=*" + "*.*" + "))";

                string VollenUserNamen   = Environment.UserName;
                string User              = VollenUserNamen.Remove(0, 2); // Barthelmes
                Font   SchriftMuliFett10 = new Font("Muli", 10.0F);

                // StandardText in der csv datei m übernommen aus der Originaldatei
                string StandardText = "#Registrationsdaten" + Environment.NewLine + "#Format Version:3.1.6.0"
                                      + Environment.NewLine + "#Exportdatum: 07/14/2018 10:39:49" + Environment.NewLine + "#Gerätename:" + Environment.NewLine
                                      + "#Adresse:" + Environment.NewLine + "#Registrations-Nr.,Typ,Name,Anwendernamen-Anzeige,Index,Oft,Titel 1,Titel 2,Titel 3,E-Mail-Adresse,Name verwenden als,Absender schützen,Passwort,Anwendercode/Gerätelogin-Anwendername,Gruppen, denen der Anwender angehört,Destinazione fax,Faxziel,Linientyp,Internationaler Übertragungsmodus,Fax-Header,Name einfügen 1. Zeile (Wahl),Name einfügen 2. Zeile (Zeichenkette),Ordner schützen,Passwort-Verschlüsselung,Protokoll,Anschluss-Nr.,Servername,Pfad,Anwendername,Japanischer Zeichencode,Zugriffsprivileg auf Anwender,Zugriffsprivileg auf Geschützte Dateien,IP-Faxprotokoll,IP-Faxziel,Login-Passwort für Gerät,Passwortverfahren,SMTP-Authentifizierung,SMTP-Authentifizierung: Login-Anwendername,SMTP-Authentifizierung: Login-Passwort,Passwortverfahren,Ordner-Authentifizierung,Ordner-Authentifizierung: Login-Passwort,Passwortverfahren,LDAP-Authentifizierung,LDAP-Authentifizierung: Login-Anwendername,LDAP-Authentifizierung: Login-Passwort,Passwortverfahren,Direkt SMTP,Anzeigepriorität" + Environment.NewLine
                                      + "<index>,<type>,<name>,<displayName>,<phoneticName>,<common>,<tagSet1>,<tagSet2>,<tagSet3>,<address>,<isSender>,<protect>,<password>,<userCode>,<group>,<faxNumber>,<lineType>,<isAbroad>,<ttiNo>,<label1>,<label2String>,<messageNo>,<protectFolder>,<passwordEncoding>,<folderProtocol>,<ftpPort>,<folderServer>,<folderPath>,<folderUser>,<ftpCharCoding>,<entryACL>,<documentACL>,<IPfaxProtocol>,<IPfaxAddress>,<authPassword>,<passwordEncoding2>,<SMTPAuth>,<SMTPUser>,<SMTPPassword>,<passwordEncoding3>,<folderAuth>,<folderPassword>,<passwordEncoding4>,<LDAPAuth>,<LDAPUser>,<LDAPPassword>,<passwordEncoding5>,<DirectSMTP>,<displayPriority>" + Environment.NewLine;


                // Standardeinträge einer .csv datei generieren
                this.TextBox4.AppendText(StandardText);

                // Für jeden eintrag in der AD, erstelle einen String und schreibe in die Textbox
                foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
                {
                    System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();

                    // Deklarationen
                    string Username               = de.Properties["samAccountName"].Value.ToString();
                    string value                  = Username;
                    int    startIndex             = 2;
                    int    length                 = 1;
                    string substring              = value.Substring(startIndex, length);
                    int    NamenstastenNummer     = 0;
                    string DruckerStringOhneEmail = "";
                    // Den Usernamen müssen wir noch Formatieren: aus h.barthelmes wird H. Barthelmes
                    string substring2       = Username.Substring(0, 1).ToUpper() + Username.Substring(1); // Wir schreiben das H góß
                    string substring3       = Username.Substring(0, 3).ToUpper() + Username.Substring(3); // Wir schreiben das B Groß
                    string substring4       = Username.Substring(0, 3).ToUpper() + Username.Substring(3);
                    string original         = substring4;
                    string modifiedUsername = original.Insert(2, " "); // der punkt wird durch ein leerzeichen ersetzt

                    // Hier werden die Nachnamen den Namenstasten zugeordnet AB = 1 BC = 2 DE
                    if (substring == "a" | substring == "ä" | substring == "b")
                    {
                        NamenstastenNummer = 1;
                    }
                    else if (substring == "c" | substring == "d")
                    {
                        NamenstastenNummer = 2;
                    }
                    else if (substring == "e" | substring == "f")
                    {
                        NamenstastenNummer = 3;
                    }
                    else if (substring == "g" | substring == "h")
                    {
                        NamenstastenNummer = 4;
                    }
                    else if (substring == "i" | substring == "j" | substring == "k")
                    {
                        NamenstastenNummer = 5;
                    }
                    else if (substring == "l" | substring == "m" | substring == "n")
                    {
                        NamenstastenNummer = 6;
                    }
                    else if (substring == "o" | substring == "ö" | substring == "p" | substring == "q")
                    {
                        NamenstastenNummer = 7;
                    }
                    else if (substring == "r" | substring == "s" | substring == "t")
                    {
                        NamenstastenNummer = 8;
                    }
                    else if (substring == "u" | substring == "ü" | substring == "v" | substring == "w")
                    {
                        NamenstastenNummer = 9;
                    }
                    else if (substring == "x" | substring == "y" | substring == "z")
                    {
                        NamenstastenNummer = 10;
                    }
                    else
                    {
                        NamenstastenNummer = 1;// Falls der name ein umlaut hat, wird der wert der Namenstaste auf 1  gesetzt
                    }
                    // Dim KurzerName As String = modifiedUsername.Substring(0, 5)

                    if (modifiedUsername.Count() - 1 > 12)
                    {
                        DruckerStringOhneEmail = "[" + i + "], [A],[" + modifiedUsername + "],[" + modifiedUsername.Substring(0, 11) + "],,[0],[" + NamenstastenNummer + "],[0],[0],,[0],,,,,,,,,,,,[0], [omitted],[0],,,[" + Properties.Settings.Default.UserHomePfad + "" + Username + "],,,,,,,, [omitted],[0],,, [omitted],[2],, [omitted],[0],,, [omitted],,[5]";
                    }
                    else
                    {
                        DruckerStringOhneEmail = "[" + i + "], [A],[" + modifiedUsername + "],[" + modifiedUsername + "],,[0],[" + NamenstastenNummer + "],[0],[0],,[0],,,,,,,,,,,,[0], [omitted],[0],,,[" + Properties.Settings.Default.UserHomePfad + "" + Username + "],,,,,,,, [omitted],[0],,, [omitted],[2],, [omitted],[0],,, [omitted],,[5]";
                    }


                    this.TextBox4.AppendText(DruckerStringOhneEmail + Environment.NewLine);

                    // Zähler hochzählen
                    i = i + 1;
                }


                List <string> UserMitEmail = new List <string>();
                List <string> MeinArray    = new List <string>();
                if (System.IO.File.Exists(Pfad) == true)
                {
                    using (System.IO.StreamReader StreamReader = new System.IO.StreamReader(Pfad))
                    {
                        do
                        {
                            MeinArray.Add(StreamReader.ReadLine());
                        }while (StreamReader.Peek() < 0);
                    }
                    foreach (string Zeile in MeinArray)
                    {
                        UserMitEmail.Add(Zeile);
                    }
                }
                else
                {
                }

                System.DirectoryServices.DirectoryEntry entry2 = new System.DirectoryServices.DirectoryEntry(Properties.Settings.Default.Organisationseinheit);
                string DomainDN2 = System.Convert.ToString(entry2.Properties["DefaultNamingContext"].Value);
                System.DirectoryServices.DirectoryEntry         ADEntry2    = new System.DirectoryServices.DirectoryEntry(Properties.Settings.Default.Organisationseinheit + DomainDN2);
                System.DirectoryServices.DirectorySearcher      mySearcher2 = new System.DirectoryServices.DirectorySearcher(ADEntry2);
                System.DirectoryServices.SearchResultCollection oResults2;



                try
                {
                    // Für jeden eintrag in der AD, erstelle einen String und schreibe in die Textbox
                    foreach (string mitarbeiter in rtbUsermitMail.Lines)
                    {
                        if (mitarbeiter != "")
                        {
                            mySearcher2.Filter = "(& (objectClass=Person)(sAMAccountName=*" + mitarbeiter + "))";
                            oResults2          = mySearcher2.FindAll();



                            // Für jeden eintrag in der AD, erstelle einen String und schreibe in die Textbox
                            foreach (System.DirectoryServices.SearchResult resEnt in mySearcher2.FindAll())
                            {
                                // Deklarationen
                                System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
                                // Deklarationen
                                string Email    = de.Properties["mail"].Value.ToString();
                                string Username = de.Properties["samAccountName"].Value.ToString();

                                string value                   = Username;
                                int    startIndex              = 2;
                                int    length                  = 1;
                                string substring               = value.Substring(startIndex, length);
                                int    NamenstastenNummer      = 0;
                                string DruckerStringMitDrucker = "";

                                // Den Usernamen müssen wir noch Formatieren: aus h.barthelmes wird H. Barthelmes
                                string substring2       = Username.Substring(0, 1).ToUpper() + Username.Substring(1); // Wir schreiben das H góß
                                string substring3       = Username.Substring(0, 3).ToUpper() + Username.Substring(3); // Wir schreiben das B Groß
                                string substring4       = Username.Substring(0, 3).ToUpper() + Username.Substring(3);
                                string original         = substring4;
                                string modifiedUsername = original.Insert(2, " "); // der punkt wird durch ein leerzeichen ersetzt

                                // Hier werden die Nachnamen den Namenstasten zugeordnet AB = 1 BC = 2 DE
                                if (substring == "a" | substring == "ä" | substring == "b")
                                {
                                    NamenstastenNummer = 1;
                                }
                                else if (substring == "c" | substring == "d")
                                {
                                    NamenstastenNummer = 2;
                                }
                                else if (substring == "e" | substring == "f")
                                {
                                    NamenstastenNummer = 3;
                                }
                                else if (substring == "g" | substring == "h")
                                {
                                    NamenstastenNummer = 4;
                                }
                                else if (substring == "i" | substring == "j" | substring == "k")
                                {
                                    NamenstastenNummer = 5;
                                }
                                else if (substring == "l" | substring == "m" | substring == "n")
                                {
                                    NamenstastenNummer = 6;
                                }
                                else if (substring == "o" | substring == "ö" | substring == "p" | substring == "q")
                                {
                                    NamenstastenNummer = 7;
                                }
                                else if (substring == "r" | substring == "s" | substring == "t")
                                {
                                    NamenstastenNummer = 8;
                                }
                                else if (substring == "u" | substring == "ü" | substring == "v" | substring == "w")
                                {
                                    NamenstastenNummer = 9;
                                }
                                else if (substring == "x" | substring == "y" | substring == "z")
                                {
                                    NamenstastenNummer = 10;
                                }
                                else
                                {
                                    NamenstastenNummer = 1;// Falls der name ein umlaut hat, wird der wert der Namenstaste auf 1  gesetzt
                                }
                                // Dim KurzerName As String = modifiedUsername.Substring(0, 5)
                                if (modifiedUsername.Count() - 1 > 12)
                                {
                                    DruckerStringMitDrucker = "[" + i + "], [A],[" + modifiedUsername + "],[" + modifiedUsername.Substring(0, 11) + "],,[0],[8],[0],[0],[" + Email + "],[0],,,,,,,,[1],,,[0],, [omitted],,,,,,,,,,,, [omitted],[0],,, [omitted],[0],, [omitted],[0],,, [omitted],[0],[5]";
                                }
                                else
                                {
                                    DruckerStringMitDrucker = "[" + i + "], [A],[" + modifiedUsername + "],[" + modifiedUsername + "],,[0],[8],[0],[0],[" + Email + "],[0],,,,,,,,[1],,,[0],, [omitted],,,,,,,,,,,, [omitted],[0],,, [omitted],[0],, [omitted],[0],,, [omitted],[0],[5]";
                                }



                                // Dim DruckerStringMitDrucker As String = "[" & i & "], [A],[" & modifiedUsername & "],[" & modifiedUsername & "],,[0],[8],[0],[0],[" & Email & "],[0],,,,,,,,[1],,,[0],, [omitted],,,,,,,,,,,, [omitted],[0],,, [omitted],[0],, [omitted],[0],,, [omitted],[0],[5]"


                                this.TextBox4.AppendText(DruckerStringMitDrucker + Environment.NewLine);

                                // Zähler hochzählen
                                i = i + 1;
                            }
                        }
                    }
                }
                catch
                {
                }
            }

            // Änderung an der Fehlerbehandlung vorenommen, mit internetverbindug Testen ob verbindung zu stande kommt
            catch (System.Runtime.InteropServices.COMException ex)
            {
            }
            finally
            {
                // Server wird jedesmal hinzugefügt, kann aber änderungen beinhalten, daher die möglichkeit geben das der User das von aussen ändern kann
                //string Server = "[" + i + "], [A],[Server],[Server],,[1],[0],[1],[1],,[0],,,,,,,,,,,,[0],[omitted],[0],,,[" + Properties.Settings.Default.ServerSMBPfad + @"],,,,,,,,[omitted],[0],,,[omitted],[2],,[omitted],[0],,,[omitted],,[5]";
                //this.TextBox4.AppendText(Server + Environment.NewLine);
                Speichern();
            }
        }
Example #11
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 #14
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 #15
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 #16
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 });
            }
        }