예제 #1
0
        public static bool CheckUserinAD(string domain, string username)
        {
            var ADUser_Id = "PRINT\\erp"; //make sure user name has domain name.
            var Password  = "******";
            var context   = new PrincipalContext(ContextType.Domain, "192.168.26.250", ADUser_Id, Password);

            /* server_address = "192.168.15.36"; //don't include ldap in url */


            using (var domainContext = new PrincipalContext(ContextType.Domain, "192.168.26.250", ADUser_Id, Password))
            {
                using (var user = new UserPrincipal(domainContext))
                {
                    user.SamAccountName = username;

                    using (var pS = new PrincipalSearcher())
                    {
                        pS.QueryFilter = user;

                        using (PrincipalSearchResult <Principal> results = pS.FindAll())
                        {
                            if (results != null && results.Count() > 0)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
        private void GroupSearch(ADGroup branch, Principal group, PrincipalContext context)
        {
            GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, group.SamAccountName);
            PrincipalSearchResult <Principal> grouplist = grp.GetGroups();

            if (grouplist.Count <Principal>() > 0)
            {
                ADGroup maingroup = new ADGroup
                {
                    Groupname = group.Name
                };
                foreach (var groupmember in grouplist)
                {
                    GroupSearch(maingroup, groupmember, context);
                }
                groupList.Add(group.Name);
                branch.Subgroups.Add(maingroup);
            }
            else
            {
                groupList.Add(group.Name);
                branch.Subgroups.Add(new ADGroup()
                {
                    Groupname = group.Name
                });
            }
        }
예제 #3
0
        public List <User> GetAllUsers()
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain);

            _logger.Debug($"Using PrincipalContext: {context.Name} - Server: {context.ConnectedServer}");
            UserPrincipal userPrincipal = new UserPrincipal(context);

            _logger.Debug($"Using UserPrincipal: {userPrincipal.Name} - Default");

            PrincipalSearcher search = new PrincipalSearcher(userPrincipal);
            List <User>       users  = new List <User>();
            PrincipalSearchResult <Principal> searchResults = search.FindAll();

            _logger.Debug($"Principal search executed. Result: Count: {searchResults.Count()}");

            foreach (UserPrincipal result in searchResults)
            {
                if (!string.IsNullOrWhiteSpace(result.SamAccountName) && !string.IsNullOrWhiteSpace(result.EmailAddress) &&
                    (!string.IsNullOrEmpty(result.GivenName) || !string.IsNullOrEmpty(result.Surname)))
                {
                    users.Add(new User()
                    {
                        FirstName    = result.GivenName,
                        LastName     = result.Surname,
                        PayId        = new User.Pid(result.SamAccountName),
                        EmailAddress = result.EmailAddress
                    });
                }
            }

            _logger.Trace(LoggerHelper.ExecutedFunctionMessage(users));

            return(users);
        }
예제 #4
0
        public bool IsUsernameAvailable(String username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, _server, _ldapContainer, _adminuser, _password);

            // define a "query-by-example" principal - here, we search for a UserPrincipal



            UserPrincipal qbeUser = new UserPrincipal(ctx);

            qbeUser.SamAccountName = username;
            PrincipalSearcher ps = new PrincipalSearcher(qbeUser);
            PrincipalSearchResult <Principal> psr = ps.FindAll();


            // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....


            if (psr.Count() != 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        /// <summary>
        ///  Makes user with given login name member of group with given name if exists.
        /// </summary>
        /// <param name="groupName">group name</param>
        public void AssignUserGroup(string loginName, string groupName)
        {
            // Find user entry by login name
            UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain,
                                                                   IdentityType.SamAccountName,
                                                                   loginName);

            // Search for group with matching name
            PrincipalSearchResult <Principal> activeDirectoryGroups = this.ListGroupsByName(
                this.activeDirectoryDomain, groupName);

            if (activeDirectoryGroups.Count <Principal>() != 0)
            {
                GroupPrincipal group = (GroupPrincipal)activeDirectoryGroups.First <Principal>();

                // make user member of group
                group.Members.Add(userEntry);

                // save changes
                group.Save();
                group.Dispose();
            }
            else
            {
                // throw exception to notify the group does not exists
                throw new ApplicationException("Domain group not found.");
            }

            // dispose the objects
            userEntry.Dispose();
            activeDirectoryGroups.Dispose();
        }
예제 #6
0
        public static bool CheckUserinAD(string domain, string username)
        {
            using (var domainContext = new PrincipalContext(ContextType.Domain, domain, "ggonzalez", "Gedgonz792*"))
            {
                using (var user = new UserPrincipal(domainContext))
                {
                    user.SamAccountName = username;

                    using (var pS = new PrincipalSearcher())
                    {
                        pS.QueryFilter = user;

                        using (PrincipalSearchResult <Principal> results = pS.FindAll())
                        {
                            if (results != null && results.Count() > 0)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
예제 #7
0
파일: dLibAd.cs 프로젝트: ddmunhoz/Seeker
        public PrincipalSearchResult <Principal> GetADGroup(PrincipalContext ctx, string groupName, bool exactSearch)
        {
            PrincipalSearchResult <Principal> results = null;
            GroupPrincipal    group    = new GroupPrincipal(ctx);
            PrincipalSearcher searcher = new PrincipalSearcher();

            groupName = dLibAd.EscapeLdapSearchFilter(groupName);
            if (exactSearch)
            {
                group.SamAccountName = String.Format("{0}", groupName.Trim());
                searcher.QueryFilter = group;
                results = searcher.FindAll();
            }
            else
            {
                group.DisplayName    = String.Format("*{0}*", groupName.Trim());
                searcher.QueryFilter = group;
                results = searcher.FindAll();
                if (results.Count() <= 0)
                {
                    group = new GroupPrincipal(ctx);
                    group.SamAccountName = "*" + groupName.Trim() + "*";
                    searcher.QueryFilter = group;
                    results = searcher.FindAll();
                }
            }


            return(results);
        }
예제 #8
0
        private UserPrincipal GetEmployeeFromAD(PrincipalContext pc, Employee employee, string domainNetbiosName)
        {
            UserPrincipal userPrincipal = null;

            if (!String.IsNullOrEmpty(employee.ADLogin))
            {
                try
                {
                    userPrincipal = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, employee.ADLogin.ToLower().Replace(domainNetbiosName + "\\", ""));
                }
                catch (Exception)
                {
                    userPrincipal = null;
                }
            }

            if (userPrincipal == null)
            {
                try
                {
                    userPrincipal = UserPrincipal.FindByIdentity(pc, IdentityType.Name, employee.FullName);
                }
                catch (Exception)
                {
                    userPrincipal = null;
                }
            }
            if (userPrincipal == null &&
                !String.IsNullOrEmpty(employee.Email) &&
                employee.Email.Equals("*****@*****.**") == false)
            {
                try
                {
                    UserPrincipal qbeUser = new UserPrincipal(pc);
                    qbeUser.EmailAddress = employee.Email;

                    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

                    PrincipalSearchResult <Principal> srchResult = srch.FindAll();

                    if (srchResult != null && srchResult.Count() == 1)
                    {
                        userPrincipal = srch.FindOne() as UserPrincipal;
                    }
                }
                catch (Exception)
                {
                    userPrincipal = null;
                }
            }
            return(userPrincipal);
        }
예제 #9
0
        public GroupPrincipal GetGroup(string SamAccountName)
        {
            PrincipalSearchResult <Principal> ps = SearchGroups(new object[] { SamAccountName }, new int[] { (int)UserFilter.SamAccountName });

            if (ps.Count() == 1)
            {
                return((GroupPrincipal)ps.ToArray()[0]);
            }

            else
            {
                MessageBox.Show("Keine Gruppe gefunden");
                return(null);
            }
        }
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Helper helper = (Helper)e.Argument;

            try
            {
                PrincipalContext ctx  = new PrincipalContext(ContextType.Domain, helper.UserDomain);
                UserPrincipal    user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, helper.Username);
                PrincipalSearchResult <Principal> grouplist = user.GetGroups();
                ADGroup root = new ADGroup
                {
                    Groupname = user.Name,
                    Subgroups = new ObservableCollection <ADGroup>()
                };
                int count   = 1;
                int maximum = grouplist.Count <Principal>();

                foreach (Principal group in grouplist)
                {
                    GroupSearch(root, group, ctx);
                    int progress = Convert.ToInt32(((decimal)count / (decimal)maximum) * 100);
                    (sender as BackgroundWorker).ReportProgress(progress);
                    count++;
                }
                e.Result = root;
            }
            catch (Exception exc)
            {
                switch (exc.GetType().ToString())
                {
                case "System.NullReferenceException":
                    MessageBox.Show("User Not Found", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    break;

                case "System.DirectoryServices.AccountManagement.PrincipalServerDownException":
                    MessageBox.Show("Server Down", "Error", MessageBoxButton.OK, MessageBoxImage.Hand);
                    break;

                default:
                    MessageBox.Show(exc.Message.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    break;
                }
            }
        }
예제 #11
0
        private static void ComputersAccounts()
        {
            try
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                PrincipalContext  principalContext          = new PrincipalContext(ContextType.Domain, "mydomain.com");
                PrincipalSearcher principalSearcher         = new PrincipalSearcher(new ComputerPrincipal(principalContext));
                PrincipalSearchResult <Principal> computers = principalSearcher.FindAll();

                stopWatch.Stop();
                TimeSpan ts          = stopWatch.Elapsed;
                string   elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                Console.WriteLine($"{computers.Count()} computers, run for {elapsedTime}");
            }
            catch (ArgumentException) { throw; }
            catch (InvalidOperationException) { throw; }
        }
예제 #12
0
        public ActionResult Create([Bind(Include = "Id,ContactName,UserId,Organisation,Telephone,Email,ContactStatusId,ContactNotes")] ContactsModels contactsModels)
        {
            if (contactsModels.UserId == null)
            {
                //lets try to find the userId from the UserName
                string userName = contactsModels.ContactName;
                string email    = contactsModels.Email.ToLower();
                email = email.Replace("ncl", "newcastle");
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "campus.ncl.ac.uk"))
                {
                    PrincipalSearcher search = new PrincipalSearcher();
                    UserPrincipal     user   = new UserPrincipal(ctx);
                    user.Enabled       = true;
                    user.DisplayName   = userName;
                    user.EmailAddress  = email;
                    search.QueryFilter = user;
                    PrincipalSearchResult <Principal> results = search.FindAll();

                    if (results.Count() == 1)
                    {
                        //have definitely found the user and can now save the users ID
                        contactsModels.UserId = results.FirstOrDefault().SamAccountName;
                    }
                }
            }

            if (ModelState.IsValid)
            {
                db.ContactsModels.Add(contactsModels);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ContactStatusId = new SelectList(db.ContactStatusModels.Where(s => s.Deleted == null), "Id", "ContactStatusName", contactsModels.ContactStatusId);
            return(View(contactsModels));
        }
예제 #13
0
    public MachinePermissions()
    {
        machineName = Environment.MachineName;
        PrincipalContext ctx = new PrincipalContext(ContextType.Machine, Environment.MachineName);
        GroupPrincipal   gp  = new GroupPrincipal(ctx);

        gp.Name = "*";
        PrincipalSearcher ps = new PrincipalSearcher();

        ps.QueryFilter = gp;
        PrincipalSearchResult <Principal> result = ps.FindAll();

        if (result.Count() > 0)
        {
            localGroups = new List <LocalGroup>();
            foreach (Principal p in result)
            {
                LocalGroup g = new LocalGroup();
                g.groupName = p.Name;
                g.users     = GetGroupMembers(g.groupName);
                localGroups.Add(g);
            }
        }
    }
예제 #14
0
        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            this.Log("username:"******"Parameters pageIndex and pageSize cannot be negative.");
            }
            if (pageSize < 1)
            {
                throw new ArgumentException("Parameter pageSize should be greater than or equal to 1.");
            }
            MembershipUserCollection users = new MembershipUserCollection();
            int num = 0;

            MembershipUser user = null;

            totalRecords = -1;
            int    partialTotalRecords;
            string domain = null;
            string name   = null;

            try
            {
                ADUtil.splitDomainAndName(usernameToMatch, out domain, out name);
                if ((domain == null) || domain.Equals(""))
                {
                    domain = this.dnsroot2NETBIOSName[this.currentDomainName];
                }
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, null, domain, this.userNameAD, this.passwordAD))
                {
                    using (UserPrincipal principal = new UserPrincipal(context))
                    {
                        principal.SamAccountName = name + "*";
                        using (PrincipalSearcher searcher = new PrincipalSearcher())
                        {
                            searcher.QueryFilter = principal;
                            using (PrincipalSearchResult <Principal> result = searcher.FindAll())
                            {
                                //users = new MembershipUserCollection();

                                try
                                {
                                    foreach (UserPrincipal principal2 in result)
                                    {
                                        if (principal2 != null)
                                        {
                                            num++;
                                            if (num > ((pageIndex + 1) * pageSize))
                                            {
                                                totalRecords = result.Count <Principal>();
                                                return(users);
                                            }
                                            if (num > (pageIndex * pageSize))
                                            {
                                                if ((principal2.DistinguishedName != null) && !principal2.DistinguishedName.Equals(""))
                                                {
                                                    user = new MembershipUser(this.providerName, this.ncname2NETBIOSName[ADUtil.getDCcomponent(principal2.DistinguishedName)] + @"\" + principal2.SamAccountName, null, principal2.EmailAddress, null, principal2.Name, false, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
                                                    users.Add(user);
                                                }
                                                principal2.Dispose();
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw new ProviderException("Finding users by name using filter '" + usernameToMatch + "' failed." + ex.Message, ex);
                                }

                                partialTotalRecords = result.Count <Principal>();
                                //return users;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                this.Log(e.Message, MethodBase.GetCurrentMethod().Name);
                throw;
            }

            //sql server

            try
            {
                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM Users WHERE Username LIKE @Username", connection))
                    {
                        cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = string.Format(CultureInfo.InvariantCulture, "%{0}%", usernameToMatch);
                        connection.Open();
                        int sqlRecords = (int)cmd.ExecuteScalar();

                        if (sqlRecords <= 0)
                        {
                            totalRecords = partialTotalRecords;
                            return(users);
                        }
                        else
                        {
                            totalRecords = partialTotalRecords + sqlRecords;
                        }
                    }

                    using (SqlCommand cmd = new SqlCommand("SELECT Id, Username FROM Users WHERE Username LIKE @Username ORDER BY Username ASC", connection))
                    {
                        cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = string.Format(CultureInfo.InvariantCulture, "%{0}%", usernameToMatch);

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    num++;
                                    if (num > ((pageIndex + 1) * pageSize))
                                    {
                                        break;
                                    }
                                    if (num > (pageIndex * pageSize))
                                    {
                                        MembershipUser u = this.GetUserByReader(reader);
                                        users.Add(u);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                this.Log(e.Message, MethodBase.GetCurrentMethod().Name);
                throw new ProviderException(e.Message);
            }

            return(users);
        }
예제 #15
0
        public static List <XenDesktopInventoryItem> GetActiveDirectoryUsers(string query)
        {
            var users      = new List <XenDesktopInventoryItem>();
            var grps       = new List <XenDesktopInventoryItem>();
            var usersFinal = new List <XenDesktopInventoryItem>();

            LoginViewModel clientId =
                LoginViewModel.JsonDeserialize(((FormsIdentity)HttpContext.Current.User.Identity).Ticket);

            logger.Debug("Find users and groups in domain of " + clientId.UserName);

            string searchDomain = clientId.DomainName;

            try
            {
                PrincipalContext adController = new PrincipalContext(ContextType.Domain, searchDomain, clientId.UserName, clientId.Password);

                UserPrincipal user = new UserPrincipal(adController);
                user.SamAccountName = query;
                PrincipalSearcher usrSrch = new PrincipalSearcher(user);
                PrincipalSearchResult <Principal> userSearchResult = usrSrch.FindAll();
                logger.Debug("Search for users netted " + userSearchResult.Count() + " results.");

                GroupPrincipal grp = new GroupPrincipal(adController);
                grp.SamAccountName = query;
                PrincipalSearcher grpSrch = new PrincipalSearcher(grp);
                PrincipalSearchResult <Principal> grpSearchResult = grpSrch.FindAll();
                logger.Debug("Search for groups netted " + grpSearchResult.Count() + " results.");

                int grpCount = 20;
                foreach (var currGrp in grpSearchResult)
                {
                    if (UsersSkipList.Contains(currGrp.SamAccountName))
                    {
                        continue;
                    }

                    var userRsrc = new XenDesktopInventoryItem
                    {
                        Id   = searchDomain + "\\" + currGrp.SamAccountName,
                        Name = searchDomain + "\\" + currGrp.SamAccountName + "(group)"
                    };

                    grps.Add(userRsrc);

                    grpCount--;
                    if (grpCount < 0)
                    {
                        break;
                    }
                }
                grps.Sort(new Comparison <XenDesktopInventoryItem>(XenDesktopInventoryItem.Compare));

                int userCount = 100;
                foreach (var currUser in userSearchResult)
                {
                    if (UsersSkipList.Contains(currUser.SamAccountName))
                    {
                        continue;
                    }

                    var userRsrc = new XenDesktopInventoryItem
                    {
                        Id   = searchDomain + "\\" + currUser.SamAccountName,
                        Name = searchDomain + "\\" + currUser.SamAccountName
                    };

                    users.Add(userRsrc);

                    userCount--;
                    if (userCount < 0)
                    {
                        break;
                    }
                }

                users.Sort(new Comparison <XenDesktopInventoryItem>(XenDesktopInventoryItem.Compare));
                usersFinal = grps.Concat(users).ToList();
            }
            catch (System.Exception ex)
            {
                var errmsg = "Problem searching for users in " + searchDomain + "  Details: " + ex.Message;
                logger.Error(errmsg);
                logger.Error(ex);
            }
            return(usersFinal);
        }
예제 #16
0
        public static bool CheckGroupMembership(string userID, string groupName, string Domain)
        {
#if TRACE
            long startTicks = VNC.AppLog.Trace5("Start", LOG_APPNAME);
#endif

            bool isMember = false;

            PrincipalSearchResult <Principal> groups = GetAuthorizationGroupsMembership(userID, Domain);

#if TRACE
            VNC.AppLog.Trace5("After GetAuthorizationGroupsMembership", LOG_APPNAME, startTicks);
#endif


#if TRACE
            VNC.AppLog.Trace5(string.Format("After GetAuthorizationGroupsMembership {0}", groups.Count()), LOG_APPNAME, startTicks);
#endif
            Principal foo = groups.First(g => g.Name == groupName);

#if TRACE
            VNC.AppLog.Trace5("After First", LOG_APPNAME, startTicks);
#endif

            if (foo != null)
            {
                isMember = true;
            }
            int count = groups.Where(g => g.Name == groupName).Count();

#if TRACE
            VNC.AppLog.Trace5(string.Format("After Where {0}", count), LOG_APPNAME, startTicks);
#endif

            using (PrincipalContext ADDomain = new PrincipalContext(ContextType.Domain, Domain))
            {
#if TRACE
                VNC.AppLog.Trace5("After new Principal", LOG_APPNAME, startTicks);
#endif

                using (UserPrincipal user = UserPrincipal.FindByIdentity(ADDomain, userID))
                {
#if TRACE
                    VNC.AppLog.Trace5("After FindByIdentity", LOG_APPNAME, startTicks);
#endif

                    if (count > 0)
                    {
                        isMember = true;
                    }
                }
            }

#if TRACE
            VNC.AppLog.Trace5("End", LOG_APPNAME, startTicks);
#endif

            return(isMember);
        }