private void Find()
        {
            var searchString = txtFind.Text;

            if (string.IsNullOrEmpty(searchString))
            {
                return;
            }

            //var sw = System.Diagnostics.Stopwatch.StartNew();

            _users = LocalCache.Get <List <Principal> >("PeoplePicker:" + searchString, () => getResults(searchString));

            lstUsers.DisplayMember = "displayName";
            lstUsers.ValueMember   = "displayName";
            lstUsers.DataSource    = _users;
            //if only 1 row returned=> auto select it
            if (_users.Count == 1)
            {
                SelectedUser = (UserPrincipalEx)_users.FirstOrDefault();
            }

            //sw.Stop();
            //ErrorLog.TraceLog("PeoplePicker.FindOld time taken {0}ms, searched for {1}", sw.ElapsedMilliseconds, txtFind.Text);
            //ErrorLog.TraceLog("PeoplePicker.FindOld user retrieved: {0}", string.Join(";", _users.Select(x => x.DisplayName).ToList()));
        }
Exemple #2
0
        public static User ToUser(this UserPrincipalEx p)
        {
            if (p == null)
            {
                return(null);
            }

            var user = new User
            {
                AltRecipient      = p.AltRecipient,
                BadLogonCount     = p.BadLogonCount,
                Description       = p.Description,
                DisabledBy        = null,
                DisabledDate      = null,
                DisplayName       = p.DisplayName,
                DistinguishedName = p.DistinguishedName,
                Enabled           = p.Enabled,
                EmailAddress      = p.EmailAddress,
                Groups            = null,
                Guid                       = p.Guid,
                IpPhone                    = p.IpPhone,
                IsAccountLockedOut         = p.IsAccountLockedOut(),
                LastBadPasswordAttempt     = p.LastBadPasswordAttempt,
                LastLogon                  = p.LastLogon,
                LastPasswordSet            = p.LastPasswordSet,
                MsExchHideFromAddressLists = p.MsExchHideFromAddressLists,
                Name                       = p.Name,
                SamAccountName             = p.SamAccountName,
                PrimaryGroupId             = p.PrimaryGroupId
            };

            return(user);
        }
Exemple #3
0
        public JsonResult AddAccount(string pid, string name, string displayName)
        {
            var ctx = new PrincipalContext(ContextType.Domain, "ad.balkangraph.com", "OU=TestOU,DC=ad,DC=balkangraph,DC=com");
            var up  = new UserPrincipal(ctx, name, "tempP@ssword", true);

            up.DisplayName = displayName;
            up.Name        = displayName;
            up.Save();

            UserPrincipal userPrin = new UserPrincipal(ctx);

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

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

            UserPrincipalEx extpsdf = null;

            foreach (Principal p in results)
            {
                UserPrincipalEx extp = UserPrincipalEx.FindByIdentity(ctx, IdentityType.DistinguishedName, p.DistinguishedName);

                if (extp.SamAccountName == name)
                {
                    extp.Manager = pid;

                    extp.Save();

                    extpsdf = extp;
                }
            }

            return(Json(new { id = extpsdf.DistinguishedName, displayName = extpsdf.DisplayName }));
        }
        public static void LoadUsersIntoCache()
        {
            TaskScheduler uiScheduler = TaskScheduler.Default;

            Task.Factory.StartNew(() =>
            {
                if (_cachedUsers == null)
                {
                    using (var context = new PrincipalContext(ContextType.Domain))
                    {
                        using (var userPrincipal = new UserPrincipalEx(context)
                        {
                            Enabled = true
                        })
                        {
                            using (var searcher = new PrincipalSearcher(userPrincipal))
                            {
                                _searcher            = searcher;
                                searcher.QueryFilter = userPrincipal;

                                List <Principal> breakpoint = _searcher.FindAll().ToList();
                                _cachedUsers = breakpoint;
                            }
                        }
                    }
                }
            }, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
        }
            public static string GetJobTitle(Staff staff)
            {
                string foundYou = "";

                using (var pc = new PrincipalContext(ContextType.Domain, "MILSTED-LANGDON"))
                {
                    UserPrincipalEx user = UserPrincipalEx.FindByIdentity(pc, IdentityType.SamAccountName, "MILSTED-LANGDON\\" + staff.username);
                    foundYou = user.Title;
                }
                return(foundYou);
            }
Exemple #6
0
        /// <summary>
        /// Sets the primary group for the specified User principal to "Domain Guests".
        /// </summary>
        /// <param name="userPrincipal">The principal of the account in Active Directory that you'd like to set the primary group for.</param>
        public static bool ToDomainGuests(this UserPrincipalEx userPrincipal)
        {
            bool wasSuccessful = false;

            if (userPrincipal != null)
            {
                userPrincipal.PrimaryGroupId = (int)PrimaryGroupId.DomainGuests;
                userPrincipal.Save();
                wasSuccessful = true;
            }

            return(wasSuccessful);
        }
Exemple #7
0
        //if you want to get Groups of Specific OU you have to add OU Name in Context
        public static List <User> GetallAdUsers()
        {
            List <User> AdUsers = new List <User>();

            var ctx = new PrincipalContext(ContextType.Domain, "ad.balkangraph.com", "OU=TestOU,DC=ad,DC=balkangraph,DC=com");

            UserPrincipal userPrin = new UserPrincipal(ctx);

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

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

            foreach (Principal p in results)
            {
                UserPrincipalEx extp = UserPrincipalEx.FindByIdentity(ctx, IdentityType.DistinguishedName, p.DistinguishedName);

                var      managerCN = extp.Manager;
                var      mgr       = "";
                string[] list      = managerCN.Split(',');

                if (managerCN.Length > 0)
                {
                    mgr = list[0].Substring(3);
                }

                string picture = "";

                if (extp.ThumbnailPhoto != null)
                {
                    picture = Convert.ToBase64String(extp.ThumbnailPhoto);
                }

                AdUsers.Add(new User
                {
                    Id             = extp.DistinguishedName,
                    Pid            = extp.Manager,
                    DisplayName    = extp.DisplayName,
                    SamAccountName = extp.SamAccountName,
                    Manager        = mgr,
                    Image          = "data:image/jpeg;base64," + picture,
                    JobTitle       = extp.Title,
                    Company        = extp.Company,
                    Phone          = extp.TelephoneNumber,
                    Disabled       = (extp.Enabled == false) ? "disabled" : "enabled"
                });
            }

            return(AdUsers);
        }
        private void FindOld()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (Owner != null)
                {
                    Owner.Cursor = Cursors.WaitCursor;
                }

                using (var context = new PrincipalContext(ContextType.Domain))
                {
                    using (var userPrincipal = new UserPrincipalEx(context)
                    {
                        Enabled = true
                    })
                    {
                        if (!String.IsNullOrEmpty(txtFind.Text))
                        {
                            userPrincipal.DisplayName = "*" + txtFind.Text + "*";
                        }
                        using (var searcher = new PrincipalSearcher(userPrincipal))
                        {
                            searcher.QueryFilter = userPrincipal;
                            _users = searcher.FindAll().ToList();
                            lstUsers.DataSource    = _users;
                            lstUsers.DisplayMember = "displayName";
                            lstUsers.ValueMember   = "displayName";
                            //if only 1 row returned=> auto select it
                            if (_users.Count == 1)
                            {
                                SelectedUser = (UserPrincipalEx)_users.FirstOrDefault();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
                if (Owner != null)
                {
                    Owner.Cursor = Cursors.Default;
                }
            }
        }
        //Check User input in active directory domain
        public ActionResult checkUserAD(string userName)
        {
            string domain = userName.Substring(0, userName.IndexOf("\\"));
            string userId = userName.Substring(userName.IndexOf("\\") + 1, userName.Length - (userName.IndexOf("\\") + 1));

            string UserDomain = "Domain : " + domain + " UserId : " + userId;

            string FullDomainName      = "Yes".Equals(ConfigurationManager.AppSettings["IsProduction"].ToString()) ? ConfigurationManager.AppSettings["FullDomainName"].ToString() : ConfigurationManager.AppSettings["FullDomainName_dev"].ToString();
            string ContainerDomainName = "Yes".Equals(ConfigurationManager.AppSettings["IsProduction"].ToString()) ? ConfigurationManager.AppSettings["ContainerDomainName"].ToString() : ConfigurationManager.AppSettings["ContainerDomainName_dev"].ToString();

            try
            {
                using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, FullDomainName, ContainerDomainName, ContextOptions.Negotiate))
                {
                    string message = "";

                    using (UserPrincipalEx foundUser = UserPrincipalEx.FindByIdentity(domainContext, IdentityType.SamAccountName, userId))
                    {
                        if (foundUser == null)
                        {
                            message = Resources.NotifResource.DomainNameNotFoundAD;
                            return(Json(new { isExist = 0, message = message }, JsonRequestBehavior.AllowGet));
                        }
                        else
                        {
                            var    adId   = foundUser.Guid;
                            string objSid = foundUser.Sid.ToString();
                            if (foundUser.GivenName == null)
                            {
                                foundUser.GivenName = "";
                            }
                            if (foundUser.Surname == null)
                            {
                                foundUser.Surname = "";
                            }
                            return(Json(new { isExist = 1, fname = foundUser.GivenName, lname = foundUser.Surname, objSid = objSid, message = message, adId = adId, email = foundUser.EmailAddress, title = foundUser.Title, phone = foundUser.homePhone }, JsonRequestBehavior.AllowGet));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger log     = NLog.LogManager.GetCurrentClassLogger();
                string message = "Incorrect Domain Server";
                log.Error(ex.StackTrace + "====Inner==== :" + ex.InnerException.ToString() + " ====Message :" + ex.Message);
                return(Json(new { isExist = 0, message = message }, JsonRequestBehavior.AllowGet));
            }
        }
        public static bool RemoveUser(this GroupPrincipal groupPrincipal, UserPrincipalEx userPrincipal)
        {
            bool wasSuccessful = false;

            if (userPrincipal == null)
            {
                return(wasSuccessful);
            }

            if (groupPrincipal != null)
            {
                groupPrincipal.Members.Remove(userPrincipal);
                groupPrincipal.Save();
                wasSuccessful = true;
            }

            return(wasSuccessful);
        }
Exemple #11
0
        public EmptyResult UpdateUser(User user)
        {
            var             ctx      = new PrincipalContext(ContextType.Domain, "ad.balkangraph.com", "OU=TestOU,DC=ad,DC=balkangraph,DC=com");
            UserPrincipalEx userPrin = UserPrincipalEx.FindByIdentity(ctx, IdentityType.DistinguishedName, user.Id);

            if (user.SamAccountName != null)
            {
                userPrin.SamAccountName = user.SamAccountName;
            }

            //  userPrin.DisplayName = user.DisplayName;
            userPrin.Title           = user.JobTitle;
            userPrin.TelephoneNumber = user.Phone;
            userPrin.Company         = user.Company;

            userPrin.Save();

            return(new EmptyResult());
        }
        private List <Principal> getResults(string searchString)
        {
            var users = new List <Principal>();

            try
            {
                Cursor = Cursors.WaitCursor;
                if (Owner != null)
                {
                    Owner.Cursor = Cursors.WaitCursor;
                }

                using (var context = new PrincipalContext(ContextType.Domain, Settings.Default.PeoplePickerSearchDomain, Settings.Default.PeoplePickerSearchOU))
                {
                    using (var userPrincipal = new UserPrincipalEx(context)
                    {
                        Enabled = true
                    })
                    {
                        userPrincipal.DisplayName = "*" + searchString + "*";
                        using (var searcher = new PrincipalSearcher(userPrincipal))
                        {
                            searcher.QueryFilter = userPrincipal;
                            users = searcher.FindAll().ToList();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
                if (Owner != null)
                {
                    Owner.Cursor = Cursors.Default;
                }
            }
            return(users);
        }
Exemple #13
0
        public static bool MoveUser(this UserPrincipalEx userPrincipal, string newContainer)
        {
            var wasSuccessful = false;

            if (newContainer == null)
            {
                return(wasSuccessful);
            }

            if (userPrincipal != null)
            {
                var termUser = new DirectoryEntry(userPrincipal.DistinguishedName);

                termUser.MoveTo(new DirectoryEntry(newContainer));
                termUser.CommitChanges();
                termUser.Close();
                wasSuccessful = true;
            }

            return(wasSuccessful);
        }
Exemple #14
0
 private void FindOld()
 {
     using (var context = new PrincipalContext(ContextType.Domain))
     {
         using (var userPrincipal = new UserPrincipalEx(context)
         {
             Enabled = true
         })
         {
             if (!String.IsNullOrEmpty(txtFind.Text))
             {
                 userPrincipal.DisplayName = "*" + txtFind.Text + "*";
             }
             using (var searcher = new PrincipalSearcher(userPrincipal))
             {
                 searcher.QueryFilter = userPrincipal;
                 _users = searcher.FindAll().ToList();
                 lstUsers.DataSource    = _users;
                 lstUsers.DisplayMember = "displayName";
                 lstUsers.ValueMember   = "displayName";
             }
         }
     }
 }
Exemple #15
0
        public static bool Update(this UserPrincipalEx userPrincipal, UpdateUserRequest request)
        {
            var wasSuccessful = false;

            if (request == null)
            {
                return(wasSuccessful);
            }
            if (userPrincipal == null)
            {
                return(wasSuccessful);
            }

            //userPrincipal.AltRecipient = null;
            userPrincipal.Description = request.Description;
            userPrincipal.Enabled     = request.Enabled;
            userPrincipal.IpPhone     = request.IpPhone;
            //userPrincipal.MsExchHideFromAddressLists = request.MsExchHideFromAddressLists;
            userPrincipal.Save();

            wasSuccessful = true;

            return(wasSuccessful);
        }
        private static UserPrincipalEx FindCurrentUserInAd()
        {
            using (var context = new PrincipalContext(ContextType.Domain))
            {
                using (var userPrincipal = new UserPrincipalEx(context)
                {
                    Enabled = true
                })
                {
                    userPrincipal.SamAccountName = Environment.UserName;
                    using (var searcher = new PrincipalSearcher(userPrincipal))
                    {
                        searcher.QueryFilter = userPrincipal;
                        var users = searcher.FindAll().ToList();

                        if (users.Count == 1)
                        {
                            return((UserPrincipalEx)users.FirstOrDefault());
                        }
                    }
                }
            }
            return(null);
        }
Exemple #17
0
        private UserPrincipalEx GetUser(string samAccountName)
        {
            var userPrincipal = UserPrincipalEx.FindByIdentity(_ctx, IdentityType.SamAccountName, samAccountName);

            return(userPrincipal);
        }
        public void LogUsage(IBaseTemplate template, Enums.UsageTrackingType trackingType)
        {
            try
            {
                var list      = new SharePointList(Settings.Default.SharePointContextUrl, Settings.Default.UsageReportingListName);
                var presenter = new SharePointListPresenter(list, this);

                string segment           = string.Empty;
                string wholesaleOrRetail = string.Empty;
                string title             = "Unknown";
                string userDep           = "Unable to locate";
                string userOffice        = "Unable to locate";

                string type = GetType().Name;

                switch (type)
                {
                case "InsuranceRenewalReportWizard":
                {
                    var form = ((InsuranceRenewalReportWizard)this);
                    segment           = ConvertSegementToNumberical(form.SelectedSegment);
                    wholesaleOrRetail = form.SelectedStatutory.ToString();
                    title             = Constants.TemplateNames.InsuranceRenewalReport;
                    break;
                }

                case "ClientDiscoveryWizard":
                {
                    //var form = ((ClientDiscoveryWizard) this);
                    title = Constants.TemplateNames.ClientDiscovery;
                    break;
                }

                case "PreRenewalAgendaWizard":
                {
                    //var form = ((PreRenewalAgendaWizard) this);
                    title = Constants.TemplateNames.PreRenewalAgenda;
                    break;
                }

                case "RenewalLetterWizard":
                {
                    //var form = ((RenewalLetterWizard) this);
                    title = Constants.TemplateNames.RenewalLetter;
                    break;
                }

                case "SummaryOfDiscussionWizard":
                {
                    //var form = ((SummaryOfDiscussionWizard) this);
                    title = Constants.TemplateNames.FileNote;
                    break;
                }


                case "GenericLetterWizard":
                {
                    //var form = ((GenericLetterWizard)this);
                    title = Constants.TemplateNames.GenericLetter;
                    break;
                }

                case "PreRenewalQuestionareWizard":
                {
                    title = "Fact Finder";         //todo: need to move this to constants once we can update value in ShaerPoint. (currently Pre Renewal Questionaire and cannot be changed until new wizard is released)
                    break;
                }

                case "FactFinderWizard":
                {
                    title = "Fact Finder";         //todo: need to move this to constants once we can update value in ShaerPoint. (currently Pre Renewal Questionaire and cannot be changed until new wizard is released)
                    break;
                }

                case "QuoteSlipWizard":
                {
                    title = Constants.TemplateNames.QuoteSlip;
                    break;
                }

                case "InsuranceManualWizard":
                {
                    title = Constants.TemplateNames.InsuranceManual;
                    break;
                }

                case "ShortFormProposalWizard":
                {
                    title = Constants.TemplateNames.ShortFormProposal + " - " + template.DocumentTitle;
                    break;
                }

                case "PlacementSlip":
                {
                    title = "Placement Slip";
                    break;
                }

                default:
                {
                    title = template.DocumentTitle;
                    break;
                }
                }

                Task.Factory.StartNew(() =>
                {
                    UserPrincipalEx user = FindCurrentUserInAd();
                    if (user != null)
                    {
                        userDep    = user.Branch;
                        userOffice = user.Suburb;
                    }
                    presenter.LogUsage(trackingType.ToString(), title, template.ExecutiveName, userDep, userOffice, template.ClientName, segment, wholesaleOrRetail, DateTime.Now.ToShortDateString(), DateTime.Now.TimeOfDay.ToString());
                }, CancellationToken.None).ContinueWith((task =>
                {
                    if (task.IsFaulted)
                    {
                        OnError(task.Exception);
                    }
                }));
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
 private void ReturnSelectedUser()
 {
     SelectedUser = (UserPrincipalEx)lstUsers.SelectedItem;
     Close();
 }
Exemple #20
0
 public static bool IsGroupMember(this UserPrincipalEx userPrincipal, string groupName)
 {
     return(userPrincipal.GetGroups().Any(g => g.Name.ToLower() == groupName.ToLower()));
 }