public static List<string> GetDomainGroups()
        {
            List<string> listGroups = new List<string>();
            try
            {

                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
                PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

                // find all matches
                foreach (var found in srch.FindAll())
                {
                    GroupPrincipal foundGroup = found as GroupPrincipal;

                    if (foundGroup != null)
                    {
                        listGroups.Add(foundGroup.Name);
                    }
                }

                return listGroups;
            }
            catch (Exception ex)
            {

            }

            return listGroups;
        }
        /// <summary>
        /// List all accounts in the Active Directory
        /// </summary>
        /// <param name="domain">Domain</param>
        private static void ListAllAccounts(string domain) {

            try {

                // Construct context to query your Active Directory
                using (var context = new PrincipalContext(ContextType.Domain, domain)) {

                    // Construct UserPrincipal object for this context
                    var userPrincipal = new UserPrincipal(context);

                    // Search and find every user in the system – PrincipalSearcher instance for what we need!
                    using (var searcher = new PrincipalSearcher(userPrincipal)) {

                        var counter = 0u;

                        // Iterate for all users in AD
                        foreach (var result in searcher.FindAll()) {

                            counter++;
                            var de = result.GetUnderlyingObject() as DirectoryEntry;
                            var samAccountName = de.Properties["samAccountName"].Value;
                            var active = IsUserActiveInAD(de);
                            Console.WriteLine("{0}: {1} - {2}", counter, samAccountName, active ? "Yes" : "No");
                        }
                    }
                }
            } catch (PrincipalServerDownException ex) {
                Console.WriteLine(string.Format("Unable to lookup domain: {0}\r\n{1}", domain, ex.ToString()));
            }
        }
Exemple #3
0
 private static void SearchComp(List<CompData> comps, string domainName)
 {
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))
      {
     foreach (var comp in comps)
     {
        if (comp.CompName == null)
        {
           var sp = new ComputerPrincipal(ctx);
           sp.Description = comp.User.Name;
           var searcher = new PrincipalSearcher(sp);
           var res = searcher.FindAll();
           foreach (var p in res)
           {
              if (p is ComputerPrincipal)
              {
                 var findComp = (ComputerPrincipal)p;
                 comp.CompName = findComp.Name;
                 comp.CompPath = findComp.DistinguishedName;
              }
           }
        }
     }
      }
 }
Exemple #4
0
 private static void Main(string[] args)
 {
     var repository = new Repository();
     repository.CreateDatabase();
     using (var context = new PrincipalContext(ContextType.Domain, "infotecs-nt", "lr.knowledge.base", ",jrcnfgjx"))
     {
         UserPrincipal u = new UserPrincipal(context);
         PrincipalSearcher search = new PrincipalSearcher(u);
         foreach (UserPrincipal result in search.FindAll())
         {
             repository.AddUsers(new[]
             {
                 new User()
                 {
                     FirstName = result.DisplayName ?? string.Empty,
                     LastName = string.Empty,
                     MiddleName = string.Empty,
                     ActiveDirectoryId = @"infotecs-nt\" + result.SamAccountName,
                     IsManager = result.IsManager()
                 }
             });
             Console.WriteLine(string.Format("Добавлен пользователь: {0}", result.DisplayName));
             repository.Save();
         }
     }
 }
Exemple #5
0
        //if you want to get Groups of Specific OU you have to add OU Name in Context
        public static List <ADUser> GetallAdUsers()
        {
            List <ADUser> AdUsers = new List <ADUser>();
            //MBS.com My Domain Controller which i created
            //OU=DevOU --Organizational Unit which i created
            //and create users and groups inside it
            var           ctx      = new PrincipalContext(ContextType.Domain, "MBS", "OU=DevOU,DC=MBS,DC=com");
            UserPrincipal userPrin = new UserPrincipal(ctx);

            userPrin.Name = "*";
            var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher();

            searcher.QueryFilter = userPrin;
            var results = searcher.FindAll();

            foreach (Principal p in results)
            {
                AdUsers.Add(new ADUser
                {
                    DisplayName    = p.DisplayName,
                    Samaccountname = p.SamAccountName
                });
            }
            return(AdUsers);
        }
Exemple #6
0
        public static List<Student> getMatchingStudents(string givenName, string surname)
        {
            List<Student> matches = new List<Student>();

            using (PrincipalContext pc = new PrincipalContext(
                ContextType.ApplicationDirectory, "ailds01v.home.ad1.sou.edu:1556",
                "CN=Users,CN=University", ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
            {
                SouPerson findPerson = new SouPerson(pc);
                findPerson.GivenName = givenName;
                findPerson.Surname = surname;

                PrincipalSearcher searcher = new PrincipalSearcher(findPerson);
                PrincipalSearchResult<Principal> results = searcher.FindAll();

                foreach (SouPerson person in results)
                {
                    if (person.souStudent == true)
                    {
                        Student s = new Student();
                        s.setKey1(person.souStudentKey1);
                        s.setKey2(person.souStudentKey2);
                        s.setUsername(person.Name);
                        matches.Add(s);
                    }
                }

                return matches;
            }
        }
        /// <summary>
        /// Gets a list of enabled users in Active Directory
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static List<Users> GetEnabledUsers()
        {
            List<Users> enabledUsers = new List<Users>(6000);

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Config.ServiceSettings.PrimaryDC, Config.ServiceSettings.Username, Config.ServiceSettings.Password))
            {
                using (UserPrincipal up = new UserPrincipal(pc))
                {
                    up.Enabled = false;

                    using (PrincipalSearcher ps = new PrincipalSearcher(up))
                    {
                        PrincipalSearchResult<Principal> results = ps.FindAll();
                        foreach (Principal r in results)
                        {
                            enabledUsers.Add(new Users()
                            {
                                UserGuid = (Guid)r.Guid,
                                DisplayName = r.DisplayName,
                                UserPrincipalName = r.UserPrincipalName,
                                SamAccountName = r.SamAccountName,
                                DistinguishedName = r.DistinguishedName,
                                IsEnabled = false
                            });
                        }
                    }
                }
            }

            return enabledUsers;
        }
Exemple #8
0
        public static List <User> GetallAdUsers()
        {
            List <User> AdUsers = new List <User>();

            try
            {
                var           ctx      = new PrincipalContext(ContextType.Domain, null);
                UserPrincipal userPrin = new UserPrincipal(ctx);
                userPrin.Name = "*";
                var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher();
                searcher.QueryFilter = userPrin;
                var results = searcher.FindAll();
                foreach (Principal p in results)
                {
                    AdUsers.Add(new User
                    {
                        DisplayName    = p.DisplayName,
                        Samaccountname = p.SamAccountName,
                        Description    = p.Description
                    });
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return(AdUsers);
        }
        static void Main(string[] args)
        {
            //string connectionEmployeeDatabase = "DSN=Test;Uid=walden;Pwd=walden";
            string connectionMessagingDatabase = "Server=COS-DEV01\\SQLEXPRESS;Database=Messaging;Uid=sa;Pwd=0Griswold;";

            List<EBSEmployee> employeeDataList = new List<EBSEmployee>();
            EBSEmployee employeeData = new EBSEmployee();

            var principalContext = new PrincipalContext(ContextType.Domain, "ct-ortho.com");
            UserPrincipal userPrin = new UserPrincipal(principalContext);
            var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher();
            searcher.QueryFilter = userPrin;
            var results = searcher.FindAll();
            foreach (Principal p in results)
            {

                UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, p.SamAccountName);

                employeeData = new EBSEmployee();

                if (string.IsNullOrEmpty(userPrincipal.GivenName))
                {
                    employeeData.FirstName = string.Empty;
                }
                else
                {
                    employeeData.FirstName = userPrincipal.GivenName;
                }

                if (string.IsNullOrEmpty(userPrincipal.Surname))
                {
                    employeeData.LastName = string.Empty;
                }
                else
                {
                    employeeData.LastName = userPrincipal.Surname;
                }
                if (string.IsNullOrEmpty(p.SamAccountName))
                {
                    employeeData.UserName = string.Empty;
                }
                else
                {
                    employeeData.UserName = p.SamAccountName;
                }

                employeeData.UserID = p.Guid.ToString();

                if (CheckToSeeIfUserExists(connectionMessagingDatabase, p.Guid.ToString()))
                {
                    UpdateEmployeeRecords(connectionMessagingDatabase, employeeData);
                }
                else
                {
                    InsertEmployeeRecords(connectionMessagingDatabase, employeeData);
                }
            }
        }
 private static void DownloadAdsGroups()
 {
     using (var context = new OnlineFilesEntities())
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
     using (var groupPrincipal = new GroupPrincipalEx(ctx))
     using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
     {
         int max = search.FindAll().Count();
         int c = 0;
         foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
         {
             Console.WriteLine("Processing " + c + " of " + max);
             c++;
             if (gp != null)
             {
                 if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                     continue;
                 var so = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                 if (so == null)
                 {
                     so = new SecurityObject
                     {
                         ActiveDirectoryId = gp.Guid,
                         FullName = gp.Name,
                         Username = gp.SamAccountName,
                         EmailAddress = gp.EmailAddress ?? "",
                         IsGroup = true,
                         LastLogInOn = DateTime.Now,
                         IsActive = true,
                         HomeFolder = null
                     };
                     context.SecurityObjects.Add(so);
                 }
                 else
                 {
                     so.IsGroup = true;
                     so.FullName = gp.Name;
                     so.Username = gp.SamAccountName;
                     so.EmailAddress = gp.EmailAddress ?? "";
                 }
             }
             context.SaveChanges();
         }
     }
 }
Exemple #11
0
        public void ReadGroup()
        {
            // Group Principal Searcher Creation
            GroupPrincipal Access = new GroupPrincipal(ctx);

            PrincipalSearcher search = new PrincipalSearcher(Access);

            foreach (GroupPrincipal iter in search.FindAll())
            {
                Console.WriteLine("{0} - {1}", iter.SamAccountName, iter.Name);
            }
        }
Exemple #12
0
 public Task<List<User>> GetAllUsers()
 {
     using (var ctx = _directoryContext.LoadAndConnect())
     {
         var filter = new UserPrincipal(ctx) { DisplayName = "*", Enabled = true };
         using (var search = new PrincipalSearcher(filter))
         {
             var users = search.FindAll().OfType<UserPrincipal>().AsUserList();
             return Task.FromResult(users);
         }
     }
 }
Exemple #13
0
 public List<string> GetAllUsers(string term)
 {
     using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
     {
         UserPrincipal qbeUser = new UserPrincipal(context);
         qbeUser.SamAccountName = "*" + term + "*";
         PrincipalSearcher search = new PrincipalSearcher(qbeUser);
         var users = search.FindAll();
         var result = users.Select(p => p.Name).ToList();
         return result;
     }
 }
Exemple #14
0
        public static void DisplayADUserwDB()
        {
            try
            {
                Console.Clear();
                int eintraege = 0;

                if (variablen.domain == "Place your Domain here!")
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Bitte Suchdomain umändern!");
                    Console.ResetColor();
                }
                else
                {

                    string udomain = Environment.UserDomainName;

                    if (variablen.domain == string.Empty)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Keine Domain angegeben!");
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }
                    else
                    {
                        PrincipalContext pc = new PrincipalContext(ContextType.Domain, variablen.domain);
                        PrincipalSearcher us = new PrincipalSearcher(new UserPrincipal(pc));
                        PrincipalSearchResult<Principal> psr = us.FindAll();

                        Console.WriteLine("User werden nun angezeigt!");
                        foreach (UserPrincipal up2 in psr)
                        {
                            eintraege++;
                            DateTime lastlog = up2.LastLogon.GetValueOrDefault(variablen.nuller);
                            string ausgabe = String.Format("\r\nsAMAccount: {0}, \r\n LastLog: {1}", up2.SamAccountName, lastlog);
                            Console.WriteLine(ausgabe);

                        }
                        Console.WriteLine("Auslesen fertig! Angezeigte User: "******"Fehler bei Domänenausgabe... ");
                Console.ForegroundColor = ConsoleColor.Gray;
                logger._elogger(ex);
            }
        }
 private void ListUsers()
 {
     UserPrincipal ObjectUserPrincipal = new UserPrincipal(insPrincipalContext);
     ObjectUserPrincipal.Name = "*";
     PrincipalSearcher ObjectPrincipalSearcher = new PrincipalSearcher();
     ObjectPrincipalSearcher.QueryFilter = ObjectUserPrincipal;
     PrincipalSearchResult<Principal> SearchResults = ObjectPrincipalSearcher.FindAll();
     ADUsersComboBox.Items.Clear();
     foreach (Principal p in SearchResults)
     {
         ADUsersComboBox.Items.Add(p);
     }
 }
Exemple #16
0
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            try
            { 
                if (textBoxSearch.TextLength > 0)
                {
                    List<string> Domain = new List<string>();
                    List<Users> users = new List<Users>();
                     
                    Domain.Add("prd.manulifeusa.com");
                    Domain.Add("MLIDDOMAIN1");


                    foreach(string domain in Domain)
                    {
                        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain);
                        UserPrincipal up = new UserPrincipal(ctx);
                             
                        up.DisplayName = "*" + textBoxSearch.Text + "*";                          
                        //up.SamAccountName = "*" + textBoxSearch.Text + "*";
                                                 
                         
                        PrincipalSearcher search = new PrincipalSearcher(up);                      
                                                 
                        //foreach (Principal p in search.FindAll().OrderBy(a=> a.DisplayName))
                        foreach (Principal p in search.FindAll())
                        { 
                            var FoundUser = p as UserPrincipal;                         
                            Users user = new Users();
                            user.UserName = p.SamAccountName;
                            user.AccountName = p.SamAccountName;
                            user.DisplayName = FoundUser.DisplayName;
                            user.Email = FoundUser.EmailAddress;
                            user.LastName = FoundUser.Surname;
                            user.FirstName = FoundUser.GivenName;
                            user.Domain = domain;
                            users.Add(user);
                        } 
                    }
                     
                    
                    dataGridViewUsers.DataSource = users.OrderBy(a=>a.DisplayName).ToList(); 
                     
                } 

            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #17
0
        public static List<ListClass> GetGroupListFromAdUnit(string adQuery)
        {
            List<ListClass> list = new List<ListClass>();

            var domain = new PrincipalContext(ContextType.Domain, "UN1T.GROUP", String.Format("{0}, DC=UN1T,DC=GROUP", adQuery));
            GroupPrincipal groupList = new GroupPrincipal(domain, "*");
            PrincipalSearcher ps = new PrincipalSearcher(groupList);

            foreach (var grp in ps.FindAll())
            {
                list.Add(new ListClass() {Name =grp.Name,Id= grp.Sid.ToString()});
            }

            return list;
        }
Exemple #18
0
        public List <USER> getOU(string container, string name, string OU)
        {
            List <USER> _lstUser = new List <USER>();
            //string container = @"OU=Friesland Foods Dutch Lady Malaysia,DC=domaina,DC=int,DC=net";
            string strDomain = "domaina.int.net"; string strUserName = "******"; string strPassword = "******";
            //string container = "OU=IVGHN,DC=ivg,DC=vn";
            var           ctx1  = new PrincipalContext(ContextType.Domain, strDomain, container, strUserName, strPassword);
            UserPrincipal prUsr = new UserPrincipal(ctx1);

            prUsr.Name = "*";
            var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher();

            searcher.QueryFilter = prUsr;
            var results = searcher.FindAll();
            int i       = 1;

            if (!String.IsNullOrEmpty(name))
            {
                foreach (UserPrincipal p in results)
                {
                    if (p.SamAccountName.ToUpper().Contains(name.ToUpper()))
                    {
                        USER u = new USER();
                        u.Username    = p.SamAccountName;
                        u.DisplayName = p.DisplayName;
                        u.Email       = p.EmailAddress;
                        u.GUID        = p.Guid.Value;

                        u.User_Id = i++;
                        _lstUser.Add(u);
                    }
                }
            }
            else
            {
                foreach (UserPrincipal p in results)
                {
                    USER u = new USER();
                    u.Username    = p.SamAccountName;
                    u.DisplayName = p.DisplayName;
                    u.Email       = p.EmailAddress;
                    u.GUID        = p.Guid.Value;
                    u.User_Id     = i++;
                    _lstUser.Add(u);
                }
            }
            return(_lstUser);
        }
Exemple #19
0
        public List<User> FindMatching(UserPrincipal filterCriteria)
        {
            List<User> results = new List<User>();

            PrincipalSearcher principalSearcher = new PrincipalSearcher();

            principalSearcher.QueryFilter = filterCriteria;

            PrincipalSearchResult<Principal> principals = principalSearcher.FindAll();
            foreach (UserPrincipal userPrincipal in principals)
            {
                results.Add(new User(userPrincipal));
            }
            results = results ?? new List<User>();
            return results;
        }
        public static List <ActiveDirectory> LoadUsers(string domain)
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
            var search          = new System.DirectoryServices.AccountManagement.PrincipalSearcher(new UserPrincipal(pc));

            search.QueryFilter.Description = "*";
            ((UserPrincipal)search.QueryFilter).EmailAddress = "*";
            return(search.FindAll().Where(d => d != null && d is UserPrincipal).Select(UsuarioLogado =>
                                                                                       new ActiveDirectory()
            {
                Name = UsuarioLogado.DisplayName,
                Email = ((UserPrincipal)UsuarioLogado).EmailAddress,
                Credential = UsuarioLogado.Description,
                WindowsUser = UsuarioLogado.Name,
            }).ToList());
        }
        public void FindGroup(string name)
        {
            using (var principalContext = new PrincipalContext(ContextType.Domain, _options.Domain))
            {
                var groupPrincipal = new GroupPrincipal(principalContext) { Name = name };

                var searcher = new PrincipalSearcher(groupPrincipal);

                var searchResult = searcher.FindAll();

                foreach (var group in searchResult.OfType<GroupPrincipal>())
                {
                    _output.WriteGroup(group);
                }
            }
        }
Exemple #22
0
        public List <Person> GetPeople()
        {
            List <Person> people = new List <Person>();

            var path = new PrincipalContext(ContextType.Domain, "test", "DC=test, DC=local");

            UserPrincipal user = new UserPrincipal(path);

            user.Enabled = true;
            user.Name    = "*";
            user.VoiceTelephoneNumber = "*";
            user.EmailAddress         = "*";
            user.Description          = "*";

            var search = new System.DirectoryServices.AccountManagement.PrincipalSearcher();

            search.QueryFilter = user;
            var results = search.FindAll();

            foreach (UserPrincipal item in results)
            {
                var directoryEntry = item.GetUnderlyingObject() as DirectoryEntry;

                people.Add(new Person
                {
                    Name                 = item.Name,
                    PhoneNumber          = "45-29-" + item.VoiceTelephoneNumber,
                    ExtensionPhoneNumber = item.VoiceTelephoneNumber,
                    Email                = item.EmailAddress,
                    Office               = directoryEntry.Properties["physicalDeliveryOfficeName"].Value as string,
                    Department           = item.Description,
                    Title                = directoryEntry.Properties["title"].Value as string,
                    DepartmentNumber     = Convert.ToInt32(directoryEntry.Properties["departmentNumber"].Value),
                    Subdivision          = directoryEntry.Properties["department"].Value as string,
                    Manager              = directoryEntry.Properties["manager"].Value as string,
                    Mobile               = directoryEntry.Properties["mobile"].Value as string,
                    EmployeeNumber       = Convert.ToInt32(directoryEntry.Properties["employeeNumber"].Value)
                });

                if (User.Identity.Name == item.SamAccountName)
                {
                    ViewData["UserName"]   = item.Name;
                    ViewData["Department"] = item.Description;
                }
            }
            return(people);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if ( !IsPostBack )
        {
            fname.Attributes.Add( "readonly", "readonly" );
            lname.Attributes.Add( "readonly", "readonly" );

            email.Focus();
            populate();

            foreach ( ListItem room in epaRoomNums )
            {
                epaRooms.Items.Add( room );
            }
            foreach ( ListItem room in kRoomNums )
            {
                kRooms.Items.Add( room );
            }
            foreach ( ListItem room in epaTrainNums )
            {
                epaTraining.Items.Add( room );
            }

            using ( PrincipalContext pc = new PrincipalContext( System.DirectoryServices.AccountManagement.ContextType.Domain, "ITSERVICES" ) )
            {
                using ( UserPrincipal user = new UserPrincipal( pc ) )
                {
                    user.EmailAddress = "*";
                    using ( PrincipalSearcher ps = new PrincipalSearcher() )
                    {
                        ps.QueryFilter = user;
                        ((DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 500;
                        PrincipalSearchResult<Principal> psr = ps.FindAll();
                        AD_Users = new string[psr.Count()];

                        int i = 0;
                        foreach ( UserPrincipal u in psr )
                        {
                            AD_Users[i++] = u.EmailAddress.Split('@')[0];
                        }
                    }
                }
            }

           //Debug_FillForm();
        }
    }
        public ActionResult GetManager()
        {
            //This came from Ignacio's code, I am assumign it is the name the user has given as a search tool
            var search = Request.Params["id"];

            System.Diagnostics.Debug.WriteLine(search.Split(' ')[0]);
            System.Diagnostics.Debug.WriteLine(search.Split(' ')[1]);

            PrincipalContext prinCon = new PrincipalContext(ContextType.Domain);

            UserPrincipal query = new UserPrincipal(prinCon);
            query.GivenName = search.Split(' ')[0];
            query.Surname = search.Split(' ')[1];

            System.Diagnostics.Debug.WriteLine(query.GivenName);
            System.Diagnostics.Debug.WriteLine(query.Surname);

            PrincipalSearcher searcher = new PrincipalSearcher(query);
            List<String> firstName = new List<String>();
            List<String> lastName = new List<String>();
            List<String> userName = new List<String>();

            foreach (UserPrincipal result in searcher.FindAll())
            {
                firstName.Add(result.GivenName);
                lastName.Add(result.Surname);
                userName.Add(result.UserPrincipalName);
            };

            //data contains an array of result users
            var data = new
            {
                items = new[] {
                new { key = 1, firstname = firstName[0], lastname = lastName[0], username = userName[0] },
                new { key = 2,  firstname = firstName[1], lastname = lastName[1], username = userName[1]},
                new { key = 3,  firstname = firstName[2], lastname = lastName[2], username = userName[2]}
             }
            };

            String[] hello = new string[0];
            //this should be an empty array in other words nothing found.
            var data1 = new { items = hello };

            //just change between the two values data1 or data to see the empty array sent in bellow
            return Json(data, JsonRequestBehavior.AllowGet);
        }
Exemple #25
0
 public static IEnumerable<User> GetUsers()
 {
     List<User> users = new List<User>();
     using (var context = new PrincipalContext(ContextType.Domain, "corp.devexpress.com")) {
         using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) {
             foreach (var result in searcher.FindAll()) {
                 DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                 string email = $"{(string)de.Properties["mail"].Value}";
                 string displayName = (string)de.Properties["displayname"].Value;
                 string userName = (string)de.Properties["samaccountname"].Value;
                 displayName = string.IsNullOrEmpty(displayName) ? displayName : displayName.Replace(" (DevExpress)", string.Empty);
                 users.Add(new User(userName, email, displayName));
             }
         }
     }
     return users.Where(x => !string.IsNullOrEmpty(x.Email)).ToList();
 }
Exemple #26
0
        public static List<DirectoryEntry> GetPeople(string domain, string query)
        {
            List<DirectoryEntry> list = new List<DirectoryEntry>();
 
 
            using (var context = new PrincipalContext(ContextType.Domain, domain))
            {
         
                UserPrincipal qbeUser = new UserPrincipal(context);
                qbeUser.Surname = query + "*";
                using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
                {
                    // find all matches
                    foreach (var result in srch.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        list.Add(de);
                    }
                }
 
 
                qbeUser = new UserPrincipal(context);
                qbeUser.Name = query + "*";
 
                using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
                {
                    // find all matches
                    foreach (var result in srch.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
             
 
                        list.Add(de);
 
 
                    }
                }
 
 
 
 
            }
            return list;
 
        }
 /// <summary>
 /// Delete a computer account from Active Directory.
 /// </summary>
 /// <param name="computerName">The name of the computer account to delete.</param>
 /// <param name="whatif">if true, it will run through all the logic, but will not remove the account.</param>
 /// <returns>Returns whether the account was successfully removed or not. (or would have been if whatif is true)</returns>
 public static bool DeleteADComputerByName(string computerName, bool whatif = false)
 {
     using (var context = new PrincipalContext(ContextType.Domain, Properties.Resources.DC1UPN, Properties.Resources.DomainRootOU, Properties.Resources.DomainAccount, Properties.Resources.domain))
     {
         try
         {
             var search = new PrincipalSearcher(new ComputerPrincipal(context));
             var searchResult = search.FindAll().Select(l => l as ComputerPrincipal).FirstOrDefault(computer => computer.Name == computerName);
             if (!whatif) searchResult?.Delete();
             return true;
         }
         catch (Exception ex)
         {
             var newException = new Exception("Exception in Global.cs -> DeleteADComputerByName.\n" + ex.Message);
             throw newException;
         }
     }
 }
Exemple #28
0
 protected void Page_Load(object sender, EventArgs e)
 {
     UserPanel.Visible = false;
     ComputerPanel.Visible = false;
     PrincipalContext pc = new PrincipalContext( ContextType.Domain, "ITSERVICES" );
     ComputerPrincipal computer = new ComputerPrincipal( pc );
     computer.Name = "*"; //reg expression
     PrincipalSearcher ps = new PrincipalSearcher();
     ps.QueryFilter = computer;
     ((System.DirectoryServices.DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 500;
     PrincipalSearchResult<Principal> psr = ps.FindAll();
     AD_Computers = new string[psr.Count()];
     int i = 0;
     foreach ( ComputerPrincipal cp in psr )
     {
         AD_Computers[i++] = cp.Name;
     }
 }
        /// <summary>
        /// Gets all the existing windows users.
        /// </summary>
        /// <returns>Local users account names.</returns>
        public static string[] GetUsers()
        {
            List<string> users = new List<string>();

            using (var context = new PrincipalContext(ContextType.Machine))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        users.Add(de.Name);
                    }
                }
            }

            return users.ToArray();
        }
Exemple #30
0
        public void Test()
        {
            PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "infotecs-nt");
            UserPrincipal user = new UserPrincipal(domainContext);

            DirectorySearcher searcher = new DirectorySearcher();
            PrincipalSearcher pSeracher = new PrincipalSearcher();

            pSeracher.QueryFilter = user;

            searcher.Filter = "CN=Lyapin Nikita,OU=MgmtSystemDev,OU=TDC,OU=InfoTeCS,OU=Company,DC=infotecs-nt";

            var results = pSeracher.FindAll();
            results.ToString();

            var all= searcher.FindAll();
            all.ToString();
        }
        /// <summary>
        /// Gets all the existing windows users with descriptions.
        /// </summary>
        /// <returns>Local users account names with descriptions.</returns>
        public static Dictionary<string, string> GetUsersDescription()
        {
            Dictionary<string, string> users = new Dictionary<string, string>();

            using (var context = new PrincipalContext(ContextType.Machine))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        users.Add(de.Name, de.Properties["Description"].Value.ToString());
                    }
                }
            }

            return users;
        }
Exemple #32
0
        public static void TestDomain()
        {
            // Get current User login on Windows
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            Console.WriteLine(userName);
            // print: DOMAIN/tamtq

            // Gets the network domain name associated with the current user
            string userdomain = Environment.UserDomainName;
            Console.WriteLine(userdomain);
            // print: DOMAIN

            // Get current full Domain
            // Gets an object that provides information about the local computer's network connectivity and traffic statistics.
            string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            Console.WriteLine(domain);
            Console.ReadKey();
            // print: domain.local

            // Get all user in domain
            // Run in any windows client
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, domain))
                {
                    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                    {
                        foreach (var result in searcher.FindAll())
                        {
                            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
                            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value); // print: tamtq
                            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value); //print: [email protected]
                            Console.WriteLine();
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            Console.ReadLine();
        }
Exemple #33
0
 public static string AuthenticateUser(WindowsIdentity windowsIdentity)
 {
     return GenerateNewApikey();
     using (var context = new PrincipalContext(ContextType.Domain, "ester.local"))
     {
         using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
         {
             foreach (var result in searcher.FindAll())
             {
                 var de = result.GetUnderlyingObject() as DirectoryEntry;
                 Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                 Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
                 Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
                 Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
                 Console.WriteLine();
             }
         }
     }
 }
Exemple #34
0
        public static UserInfo GetUniqueFirstNameLastName(UserInfo userInfo, PrincipalContext root)
        {
            //Search if there are already users with same first and last name
            var up = new UserPrincipal(root)
            {
                Surname = string.Format("*{0}*", userInfo.LastName),
                GivenName = string.Format("*{0}*", userInfo.FirstName)
            };

            var safeFirstName = RemoveChars(userInfo.FirstName);
            var safeLastName = RemoveChars(userInfo.LastName);

            var ps = new PrincipalSearcher(up);
            var srcCount = ps.FindAll().Count();

            var firstNameLast = string.Format("{0} {1}", safeFirstName, safeLastName);
            if (srcCount < 1)
            {
                userInfo.SamName = firstNameLast;
                if (firstNameLast.Length > 20)
                {
                    userInfo.SamName = firstNameLast.Substring(0, 20);
                }
            }
            else
            {
                var firstNameLastNameCount = string.Format("{0} {1}{2}", safeFirstName, safeLastName, srcCount);
                if (firstNameLastNameCount.Length > 20)
                {
                    var byHowMuch = firstNameLastNameCount.Length - 20;
                    firstNameLast = firstNameLast.Substring(0, firstNameLast.Length - byHowMuch);
                    userInfo.SamName = string.Format("{0}{1}", firstNameLast, srcCount);
                }
                else
                {
                    userInfo.SamName = firstNameLastNameCount;
                }
                userInfo.LastName = string.Format("{0}{1}", userInfo.LastName, srcCount);
            }

            return userInfo;
        }
Exemple #35
0
        public Dictionary<string, string> FindActiveDirectoryMatches(string term)
        {
            Principals = new List<UserPrincipal>();
            Wigglers = new List<Wiggler>(6000);

            var ctx = new PrincipalContext(ContextType.Domain, domainName);
            var user = new UserPrincipal(ctx) { DisplayName = term + "*", Enabled = true };
            var ps = new PrincipalSearcher { QueryFilter = user };
            ((DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 3000;

            var result = ps.FindAll();
            Console.WriteLine(result.Count());
            foreach (UserPrincipal p in result)
            {
                if (string.IsNullOrEmpty(p.EmailAddress)) continue;
                Principals.Add(p);
                Wigglers.Add(new Wiggler { EmailAddress = p.EmailAddress, Name = p.Name });
            }

            return Wigglers.OrderBy(w => w.Name).Take(100).ToDictionary(wiggler => wiggler.EmailAddress, wiggler => wiggler.Name);
        }