Exemplo n.º 1
1
        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;
        }
Exemplo n.º 2
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;
              }
           }
        }
     }
      }
 }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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();
         }
     }
 }
Exemplo n.º 6
0
        public bool CreateUserPrincipal()
        {
            // Create connection to domain and do a search for the user
            try
            {
                context = new PrincipalContext(ContextType.Domain, givenDomain);

                    UserPrincipal tempUserPrincipal = new UserPrincipal(context);
                    tempUserPrincipal.SamAccountName = givenUserName;

                    // Search for user
                    PrincipalSearcher searchUser = new PrincipalSearcher();
                    searchUser.QueryFilter = tempUserPrincipal;

                    UserPrincipal foundUser = (UserPrincipal)searchUser.FindOne();

                    userPrincipal = foundUser;
                    userGroups = userPrincipal.GetGroups();
                    return true;

            }
            catch (PrincipalServerDownException)
            {
                System.Windows.Forms.MessageBox.Show("Cannot contact the server.");
                return false;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message, "Unknown Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }
        }
Exemplo n.º 7
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;
            }
        }
Exemplo n.º 8
0
        /// <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;
        }
Exemplo n.º 9
0
        /// <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()));
            }
        }
        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);
                }
            }
        }
Exemplo n.º 11
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);
         }
     }
 }
Exemplo n.º 12
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);
            }
        }
Exemplo n.º 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;
     }
 }
Exemplo n.º 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);
            }
        }
Exemplo n.º 15
0
 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);
     }
 }
Exemplo n.º 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;
            }
        }
Exemplo n.º 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;
        }
Exemplo n.º 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);
        }
Exemplo n.º 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;
        }
Exemplo n.º 20
0
        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);
                }
            }
        }
Exemplo n.º 22
0
    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();
        }
    }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        public void Execute()
        {
            var queryFilter = new UserPrincipal(new PrincipalContext(ContextType.Machine), _query.UserName, _query.Password, true);
            var searcher = new PrincipalSearcher(queryFilter);
            var result = searcher.FindOne();

            var response = new ConnectionResponse { Id = _query.Id };
            if (result != null)
            {
                var sessionId = Guid.NewGuid();
                ConnectionsStorage.Instanse.Add(sessionId);
                response.Accepted = true;
                response.SessionId = sessionId;
            }

            _responseSender.Send(response, _query.ResponseEndPoint);
        }
Exemplo n.º 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();
 }
Exemplo n.º 26
0
        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);
        }
        public LocalPrincipalData CreateUser(string userName)
        {
            string rvUserName = null;
            string rvPassword = null;
            LocalPrincipalData rv = null;

            using (var context = new PrincipalContext(ContextType.Machine))
            {
                bool userSaved = false;
                ushort tries = 0;
                UserPrincipal user = null;

                do
                {
                    try
                    {
                        rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant();
                        user = new UserPrincipal(context, userName, rvPassword, true);
                        user.DisplayName = "Warden User " + userName;
                        user.Save();
                        userSaved = true;
                    }
                    catch (PasswordException ex)
                    {
                        log.DebugException(ex);
                    }

                    ++tries;
                }
                while (userSaved == false && tries < 5);

                if (userSaved)
                {
                    rvUserName = user.SamAccountName;
                    var groupQuery = new GroupPrincipal(context, IIS_IUSRS_NAME);
                    var searcher = new PrincipalSearcher(groupQuery);
                    var iisUsersGroup = searcher.FindOne() as GroupPrincipal;
                    iisUsersGroup.Members.Add(user);
                    iisUsersGroup.Save();

                    rv =  new LocalPrincipalData(rvUserName, rvPassword);
                }
            }

            return rv;
        }
Exemplo n.º 28
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;
 
        }
 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();
         }
     }
 }
Exemplo n.º 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;
        }
Exemplo n.º 32
0
        /// <summary>
        /// Seeks one computer account in Active Directory whose name exactly matches the parameter.
        /// </summary>
        /// <param name="computerName">The name of the computer account to look for.</param>        
        /// <returns>Returns a computer model of the computer found, or an empty model.</returns>
        public static Computer GetADComputerByName(string computerName)
        {
            using (var context = new PrincipalContext(ContextType.Domain, Properties.Resources.DC1UPN, Properties.Resources.DomainRootOU, Properties.Resources.DomainAccount, Properties.Resources.domain))
            {
                try
                {
                    var searchPrinciple = new ComputerPrincipal(context){Name = computerName};
                    var search = new PrincipalSearcher(searchPrinciple);
                    var searchResult = (ComputerPrincipal)search.FindOne();

                    return searchResult != null ? PrincipalToADComputer(searchResult) : null;
                }
                catch (Exception ex)
                {
                    throw new Exception("GetADComputerByName.\n" + ex.Message);
                }
            }
        }
Exemplo n.º 33
0
 /// <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;
         }
     }
 }
Exemplo n.º 34
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;
     }
 }
Exemplo n.º 35
0
        // The core query operation.
        // Given a PrincipalSearcher containg a query filter, transforms it into the store schema
        // and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit,
        // or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1).
        // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null),
        // matches all principals in the store.
        //
        // The collection may not be complete, i.e., paging - the returned ResultSet will automatically
        // page in additional results as needed.
        internal override ResultSet Query(PrincipalSearcher ps, int sizeLimit)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Query");

            Debug.Assert(sizeLimit >= -1);

            // Build the description of the properties we'll filter by.  In SAMStoreCtx, the "native" searcher
            // is simply the QbeFilterDescription, which will be passed to the SAMQuerySet to use to
            // manually filter out non-matching results.
            QbeFilterDescription propertiesToMatch = (QbeFilterDescription)PushFilterToNativeSearcher(ps);

            // Get the entries we'll iterate over.  Write access to Children is controlled through the
            // ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all
            // the child entries.  So we have to clone the ctxBase --- not ideal, but it prevents
            // multithreading issues.
            DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children;

            Debug.Assert(entries != null);

            // Determine the principal types of interest.  The SAMQuerySet will use this to restrict
            // the types of DirectoryEntry objects returned.
            Type qbeFilterType = typeof(Principal);

            if (ps.QueryFilter != null)
            {
                qbeFilterType = ps.QueryFilter.GetType();
            }

            List <string> schemaTypes = GetSchemaFilter(qbeFilterType);

            // Create the ResultSet that will perform the client-side filtering
            SAMQuerySet resultSet = new SAMQuerySet(
                schemaTypes,
                entries,
                _ctxBase,
                sizeLimit,
                this,
                new QbeMatcher(propertiesToMatch));

            return(resultSet);
        }
Exemplo n.º 36
0
        private PrincipalSearchResult <Principal> FindAll(bool returnOne)
        {
            int num;

            if (this.qbeFilter != null)
            {
                if (this.qbeFilter.unpersisted)
                {
                    if (!this.HasReferentialPropertiesSet())
                    {
                        StoreCtx          queryCtx          = this.ctx.QueryCtx;
                        PrincipalSearcher principalSearcher = this;
                        if (returnOne)
                        {
                            num = 1;
                        }
                        else
                        {
                            num = -1;
                        }
                        ResultSet resultSet = queryCtx.Query(principalSearcher, num);
                        PrincipalSearchResult <Principal> principals = new PrincipalSearchResult <Principal>(resultSet);
                        return(principals);
                    }
                    else
                    {
                        throw new InvalidOperationException(StringResources.PrincipalSearcherNonReferentialProps);
                    }
                }
                else
                {
                    throw new InvalidOperationException(StringResources.PrincipalSearcherPersistedPrincipal);
                }
            }
            else
            {
                throw new InvalidOperationException(StringResources.PrincipalSearcherMustSetFilter);
            }
        }
Exemplo n.º 37
0
        public static ActiveDirectory Load(string domain, string name)
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
            var Busca           = new System.DirectoryServices.AccountManagement.PrincipalSearcher();

            Busca.QueryFilter             = new UserPrincipal(pc);
            Busca.QueryFilter.DisplayName = name;
            var Resultado = Busca.FindOne();

            if (null != Resultado)
            {
                var UsuarioLogado = Resultado as UserPrincipal;
                return(new ActiveDirectory()
                {
                    Name = UsuarioLogado.DisplayName,
                    Email = UsuarioLogado.EmailAddress,
                    Credential = UsuarioLogado.Description,
                    WindowsUser = UsuarioLogado.Name
                });
            }
            return(null);
        }
Exemplo n.º 38
0
        // Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native
        // searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one
        // doesn't already exist) and returns the native searcher.
        // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null),
        // produces a query that will match all principals in the store.
        //
        // For stores which don't have a native searcher (SAM), the StoreCtx
        // is free to create any type of object it chooses to use as its internal representation of the query.
        //
        // Also adds in any clauses to the searcher to ensure that only principals, not mere
        // contacts, are retrieved from the store.
        internal override object PushFilterToNativeSearcher(PrincipalSearcher ps)
        {
            // There's no underlying searcher for SAM
            Debug.Assert(ps.UnderlyingSearcher == null);

            Principal            qbeFilter = ps.QueryFilter;
            QbeFilterDescription filters;

            // If they specified a filter object, extract the set properties from it.
            // Otherwise, use an empty set.  Note that we don't worry about filtering by
            // the type of the qbeFilter object (e.g., restricting the returned principals
            // to only Users, or only Groups) --- that's handled in Query().
            if (qbeFilter != null)
            {
                filters = BuildQbeFilterDescription(qbeFilter);
            }
            else
            {
                filters = new QbeFilterDescription();
            }

            return(filters);
        }
Exemplo n.º 39
0
 // The core query operation.
 // Given a PrincipalSearcher containg a query filter, transforms it into the store schema
 // and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit,
 // or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1).
 // If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null),
 // matches all principals in the store.
 //
 // The collection may not be complete, i.e., paging - the returned ResultSet will automatically
 // page in additional results as needed.
 internal abstract ResultSet Query(PrincipalSearcher ps, int sizeLimit);
Exemplo n.º 40
0
 // Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native
 // searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one
 // doesn't already exist) and returns the native searcher.
 // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null),
 // produces a query that will match all principals in the store.
 //
 // For stores which don't have a native searcher (SAM), the StoreCtx
 // is free to create any type of object it chooses to use as its internal representation of the query.
 //
 // Also adds in any clauses to the searcher to ensure that only principals, not mere
 // contacts, are retrieved from the store.
 internal abstract object PushFilterToNativeSearcher(PrincipalSearcher ps);
Exemplo n.º 41
0
        // Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native
        // searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one
        // doesn't already exist) and returns the native searcher.
        // If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null),
        // produces a query that will match all principals in the store.
        //
        // For stores which don't have a native searcher (SAM), the StoreCtx
        // is free to create any type of object it chooses to use as its internal representation of the query.
        //
        // Also adds in any clauses to the searcher to ensure that only principals, not mere
        // contacts, are retrieved from the store.
        internal override object PushFilterToNativeSearcher(PrincipalSearcher ps)
        {
            // This is the first time we're being called on this principal.  Create a fresh searcher.
            if (ps.UnderlyingSearcher == null)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: creating fresh DirectorySearcher");

                ps.UnderlyingSearcher = new DirectorySearcher(this.ctxBase);
                ((DirectorySearcher)ps.UnderlyingSearcher).PageSize        = ps.PageSize;
                ((DirectorySearcher)ps.UnderlyingSearcher).ServerTimeLimit = new TimeSpan(0, 0, 30);  // 30 seconds
            }

            DirectorySearcher ds = (DirectorySearcher)ps.UnderlyingSearcher;

            Principal qbeFilter = ps.QueryFilter;

            StringBuilder ldapFilter = new StringBuilder();

            if (qbeFilter == null)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: no qbeFilter specified");

                // No filter specified.  Search for all principals (all users, computers, groups).
                ldapFilter.Append("(|(objectClass=user)(objectClass=computer)(objectClass=group))");
            }
            else
            {
                //
                // Start by appending the appropriate objectClass given the Principal type
                //
                ldapFilter.Append(GetObjectClassPortion(qbeFilter.GetType()));

                //
                // Next, fill in the properties (if any)
                //
                QbeFilterDescription filters = BuildQbeFilterDescription(qbeFilter);

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: using {0} filters", filters.FiltersToApply.Count);

                Hashtable filterTable = (Hashtable)s_filterPropertiesTable[this.MappingTableIndex];

                foreach (FilterBase filter in filters.FiltersToApply)
                {
                    FilterPropertyTableEntry entry = (FilterPropertyTableEntry)filterTable[filter.GetType()];

                    if (entry == null)
                    {
                        // Must be a property we don't support
                        throw new InvalidOperationException(
                                  SR.Format(
                                      SR.StoreCtxUnsupportedPropertyForQuery,
                                      PropertyNamesExternal.GetExternalForm(filter.PropertyName)));
                    }

                    ldapFilter.Append(entry.converter(filter, entry.suggestedADPropertyName));
                }

                //
                // Wrap off the filter
                //
                ldapFilter.Append(')');
            }

            // We don't need any attributes returned, since we're just going to get a DirectoryEntry
            // for the result.  Per RFC 2251, OID 1.1 == no attributes.
            //ds.PropertiesToLoad.Add("1.1");
            BuildPropertySet(qbeFilter.GetType(), ds.PropertiesToLoad);

            ds.Filter = ldapFilter.ToString();
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "PushFilterToNativeSearcher: using LDAP filter {0}", ds.Filter);

            return(ds);
        }
Exemplo n.º 42
-1
    protected void fillBtn_Click(object sender, EventArgs e)
    {
        if ( isNull() )
            return;

        using ( PrincipalContext context = new PrincipalContext( ContextType.Domain, "ITSERVICES" ) )
        {
            ComputerPrincipal computer = new ComputerPrincipal( context );
            computer.Name = ComputerTextBox.Text;
            using ( PrincipalSearcher searcher = new PrincipalSearcher( computer ) )
            {
                Principal result = searcher.FindOne();

                AuthenticablePrincipal auth = result as AuthenticablePrincipal;
                if ( auth != null )
                {
                    lblName.Text = auth.Name;
                    lblLastLogon.Text = auth.LastLogon.ToString();
                    lblEnabled.Text = auth.Enabled.ToString();
                    lblDistinguishedName.Text = auth.DistinguishedName;
                }
            }
        }
        ComputerPanel.Visible = true;
    }