Пример #1
0
        // GET api/EmployeeAPI
        //Returns employee information from AD
        public IHttpActionResult GetEmployees()
        {
            var employee = new Employee();

            var empList = new List <Employee>();

            //Get AD groups from AD - this will therefore be used mostly for filtering purposes and other operations
            var ADGroupList = new ADUsers().GetAdGroupsForUser(Generic.GetCurrentLogonUserName(), new ADUsers().DomanName);

            //Loop through AD group information and get employees that have access to each group
            for (int i = 0; i < ADGroupList.Count(); i++)
            {
                //This calls a method to get employees from ADUsers method and add them to a list
                var ADEmployees = new ADUsers().GetUserPerByAdGroup(ADGroupList[i]);

                foreach (var empName in ADEmployees)
                {
                    empList = new List <Employee>()
                    {
                        new Employee()
                        {
                            EmployeeFirstName = empName.EmployeeFirstName, Department = ADGroupList[i]
                        }
                    };
                }
            }
            //Serializing employee list so that it can be transported as an object back to client
            var data = JsonConvert.SerializeObject(empList);

            return(Ok(empList));
        }
        //Returns a list of all the employees
        public void GetEmployeeInformation()
        {
            var raterObject = new List <Rater>();

            var list = new ADUsers().GetAdGroupsForUser(Generic.GetCurrentLogonUserName(), new ADUsers().DomanName);

            var raterList = new List <Rater>();

            for (int i = 0; i < list.Count; i++)

            {
                //Pass a group name to return all the employee
                var empGroupList = new ADUsers().GetUserPerByAdGroup("DG-Futuregrowth");

                for (int j = 0; j < empGroupList.Count; j++)
                {
                    //Ensure that THE employee first name and last name are not null prior adding them into the list
                    if (!string.IsNullOrWhiteSpace(empGroupList[j].EmployeeFirstName) && !string.IsNullOrWhiteSpace(empGroupList[j].EmployeeSurname))
                    {
                        raterList.Add(new Rater()
                        {
                            Name = empGroupList[j].EmployeeFirstName + " " + empGroupList[j].EmployeeSurname
                        });
                    }
                }

                break;
            }

            //Store employee list in the viewBag - this is then called from  a view to populate employee (or raters) dropdown list(s)
            ViewBag.RaterList = raterList;
        }
        private List <ADUsers> GetadUsers()
        {
            var Userlist = new List <ADUsers>();

            using (var context = new PrincipalContext(ContextType.Domain, "FITZROY", "OU=FITZROY,DC=private,DC=fitzroy,DC=co,DC=nz"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        var user = new ADUsers();


                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        user.FirstName = de.Properties["givenName"].Value.ToString();
                        user.LastName  = de.Properties["sn"]?.Value?.ToString() ?? "";
                        user.Email     = de.Properties["userPrincipalName"].Value.ToString();

                        Userlist.Add(user);

                        //de.Properties["samAccountName"].Value
                        //de.Properties["userPrincipalName"].Value
                        //Console.WriteLine();
                    }
                }
            }

            return(Userlist);
        }
Пример #4
0
 public Task <List <ADUser> > GetDomainUsers()
 {
     return(Task.Run(() =>
     {
         return ADUsers.ToList();
     }));
 }
Пример #5
0
 public Task <ADUser> GetADUser(Guid guid)
 {
     return(Task.Run(() =>
     {
         return ADUsers.FirstOrDefault(x => guid.Equals(x.Guid.Value));
     }));
 }
Пример #6
0
 public Task <ADUser> GetADUser(string samAccountName)
 {
     return(Task.Run(() =>
     {
         return ADUsers.FirstOrDefault(x => x.SamAccountName.ToLower().Equals(samAccountName.ToLower()));
     }));
 }
        //Generate a survey template
        //Get column names from a webConfig file and generate a spreadsheet to be completed and uploaded into the database
        public void GenerateTemplate()
        {
            //Get current loggedin user name from AD
            var username = Generic.GetCurrentLogonUserName();

            //Pass a group name and return a list of users that have access to this group
            var employeeList = new ADUsers().GetUserPerByAdGroup("DG-Futuregrowth");

            //Return loggedin employee full by username from AD employee list
            var employeeFullName = employeeList.Where(c => c.UserName == username).First().DisplayName;


            //creating a worksheet
            using (XLWorkbook wb = new XLWorkbook())
            {
                DataTable dt = new DataTable();

                dt.TableName = employeeFullName;

                var list = Config.SurveyTemplateHeadings.Split(',');

                //Adding columns to a list
                for (int i = 0; i < list.Count(); i++)
                {
                    dt.Columns.Add(list[i]);
                }

                //Adding a datatable to a worksheet
                wb.Worksheets.Add(dt);

                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                wb.Style.Font.Bold = true;

                context.Current.Response.Clear();

                context.Current.Response.Buffer = true;

                context.Current.Response.Charset = "";

                context.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                context.Current.Response.AddHeader("content-disposition", "attachment;filename= " + employeeFullName + " - Survey" + ".xlsx");

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);

                    MyMemoryStream.WriteTo(context.Current.Response.OutputStream);

                    context.Current.Response.Flush();

                    context.Current.Response.End();
                }
            }

            //Setting employee ViewBag for populating employee and raters dropdown
            GetEmployeeInformation();
        }
Пример #8
0
        string GetEmail(string userName)
        {
            User user;

            if (ADUsers.TryGetValue(userName, out user))
            {
                return(user.Email);
            }
            return(DefaultMail);
        }
        // GET: Users
        public ActionResult Search(string text)
        {
            ActionExecutingContext filterContext = new ActionExecutingContext();

            filterContext.Result = new JsonResult
            {
                Data                = ADUsers.Search(text),
                ContentEncoding     = System.Text.Encoding.UTF8,
                ContentType         = "application/json",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            return(filterContext.Result);
        }
Пример #10
0
        public Task <List <ADUser> > FindDomainUser(string search)
        {
            return(Task.Run(() =>
            {
                var users = ADUsers
                            .Where(
                    x => x.SamAccountName.ToLower().Contains(search.ToLower()) ||
                    x.UserPrincipalName.ToLower().Contains(search.ToLower()) ||
                    x.DisplayName.ToLower().Contains(search.ToLower())
                    )
                            .OrderBy(x => x.Surname)
                            .ToList();

                return users;
            }));
        }
        public IHttpActionResult ManagerVerifyAllQuestions(SurveyComplete survey)
        {
            var empSurveyObject = GetSurveyObject(survey.Survey_For);

            empSurveyObject.Survey_For = survey.Survey_For;

            var surveyForList = new Surveys().getSurveyForVerifyAllRaters(empSurveyObject);

            survey.Type = empSurveyObject.Type;

            survey.Period = empSurveyObject.Period;

            foreach (var surveyObject in surveyForList)
            {
                try
                {
                    survey.Rater = surveyObject.Rater;

                    survey.User = survey.User = Generic.GetCurrentLogonUserName();

                    var saveReviewQuestion = new SurveyUpdate().SurveyManagerVerifyAll(survey);
                }
                catch (Exception)
                {
                    throw;
                }
            }

            var adminFullName = ConfigurationManager.AppSettings["adminFullName"];

            var adminEmaillAddress = ConfigurationManager.AppSettings["adminEmailAddress"];

            var manager = new Surveys().getSurveyTeamEmployeeList().Where(c => c.Employee.ToLower() == survey.Survey_For.ToLower()).First().Manager_Name;

            var emailBody = GetEmailBodyVerification(adminFullName, survey.Survey_For, manager);

            var adUser = new ADUsers();

            //Testing - to be removed later
            //adminEmaillAddress = new ADUsers().GetEmailAddress(new Surveys().getSurveyTeamEmployeeList().Where(c => c.AD_User_Name.ToLower() == survey.User.ToLower()).First().Employee);

            EmailSurveyVerificationNotification(emailBody, adminEmaillAddress);

            return(Ok());
        }
Пример #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string editUsers = string.Empty,
                paramValue,
                currentUser = HttpContext.Current.User.Identity.Name.ToString();

            #region Gets User Information

            ADUsers users = new ADUsers();
            users = users.GetUsersByGroup("TDocsEditUser");
            users = users.GetUsersByGroup("CorporateBusinessSystems");
            if (users != null)
            {
                foreach (ADUsersItem u in users)
                    editUsers = editUsers + u.UserId + ";";
            }

            #endregion

            paramValue = "Params=" + currentUser + "|" + editUsers;
            paramSilverLight.Attributes.Add("value", paramValue);
        }
Пример #13
0
        private User FindAndRegisterUser(string name)
        {
            var userInfo = VcsUsers.FirstOrDefault(x => x.Name == name);

            if (string.IsNullOrEmpty(userInfo.Name) || userInfo.Logins == null || userInfo.Logins.Length == 0)
            {
                return(null);
            }
            string loginCandidate = userInfo.Logins.FirstOrDefault(x => {
                var check = CalcLogin(x);
                if (string.IsNullOrEmpty(check))
                {
                    Log.Message($"Login {x} has incorrect structure.");
                    return(false);
                }
                User checkUser;
                return(ADUsers.TryGetValue(check, out checkUser));
            });

            if (string.IsNullOrEmpty(loginCandidate))
            {
                return(null);
            }
            string login = CalcLogin(loginCandidate);
            User   gitlabUser;

            if (Users.TryGetValue(login, out gitlabUser))
            {
                return(gitlabUser);
            }
            User adUser     = ADUsers[login];
            User gitLabUser = new User(userInfo.Name, adUser.Email, adUser.DisplayName, true);

            this.gitLabWrapper.RegisterUser(gitLabUser.UserName, gitLabUser.DisplayName, gitLabUser.Email);
            Users.Add(gitLabUser.UserName, gitLabUser);
            return(gitLabUser);
        }
        public IHttpActionResult GetEmployeeInformation(string adGroupName)
        {
            var employeeObject = new Employee();

            var employeeList = new List <Employee>();

            employeeObject.EmployeeList = !string.IsNullOrWhiteSpace(adGroupName) ? new ADUsers().GetUserPerByAdGroup(adGroupName) : new List <Employee>();

            var ADGroupList = new ADUsers().GetAdGroupsForUser(new ADUsers().ServiceUSer, new ADUsers().DomanName);

            var matchingList = new List <Employee>();

            foreach (var item in employeeObject.EmployeeList)
            {
                if (!ADGroupList.Contains(item.DisplayName))
                {
                    matchingList.Add(item);
                }
            }
            //Serialize raters' list
            string data = JsonConvert.SerializeObject(matchingList);

            return(Ok(data));
        }
Пример #15
0
        /// <summary>
        /// Gets the user information for displaying
        /// </summary>
        /// <param name="userPrincipalName"></param>
        private void GetUser(string userPrincipalName)
        {
            ADUsers user = null;

            try
            {
                user = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);
                
                // Get User Details
                ADUser u = user.GetUser(userPrincipalName, CPContext.SelectedCompanyCode);

                // Set values
                txtEditLoginName.Text = userPrincipalName;
                txtEditFirstName.Text = u.Firstname;
                txtEditMiddleName.Text = u.Middlename;
                txtEditLastName.Text = u.Lastname;
                txtEditDisplayName.Text = u.DisplayName;
                txtEditDepartment.Text = u.Department;
                txtEditSamAccountName.Text = u.SamAccountName;
                cbEnableUser.Checked = u.IsEnabled;
                cbEditCompanyAdmin.Checked = u.IsCompanyAdmin;
                cbEditPwdNeverExpires.Checked = u.PasswordNeverExpires;

                // Check if the account is locked out
                if (u.IsLockedOut)
                {
                    cbUserLockedOut.Checked = true;
                    lnkUnlockAccount.Visible = true;
                }
                else
                {
                    cbUserLockedOut.Checked = false;
                    lnkUnlockAccount.Visible = false;
                }

                // Get extra details from SQL
                ADUser sqlUser = DbSql.Get_User(userPrincipalName);

                // Uncheck the checkboxes
                foreach (ListItem item in cbEditCompanyAdminPermissions.Items)
                        item.Selected = false;

                if (sqlUser.IsCompanyAdmin)
                {
                    editCompanyAdminPermissions.Style.Remove("display");

                    cbEditCompanyAdminPermissions.Items[0].Selected = sqlUser.EnableExchangePermission;
                    cbEditCompanyAdminPermissions.Items[1].Selected = sqlUser.DisableExchangePermission;
                    cbEditCompanyAdminPermissions.Items[2].Selected = sqlUser.AddDomainPermission;
                    cbEditCompanyAdminPermissions.Items[3].Selected = sqlUser.DeleteDomainPermission;
                    cbEditCompanyAdminPermissions.Items[4].Selected = sqlUser.ModifyAcceptedDomainPermission;
                    cbEditCompanyAdminPermissions.Items[5].Selected = sqlUser.ImportUsersPermission;
                }
                else
                    editCompanyAdminPermissions.Style.Add("display", "none");

                // Show the correct panels
                panelEditUser.Visible = true;
                panelCreateUser.Visible = false;
                panelDeleteUser.Visible = false;
                panelUsers.Visible = false;

                // Enable save user button
                btnEditSaveUser.Enabled = true;

                // Set default button
                this.Form.DefaultButton = this.btnEditSaveUser.UniqueID;
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);

                // Disable save user button
                btnSaveUser.Enabled = false;
            }
            finally
            {
                if (user != null)
                    user.Dispose();
            }
        }
Пример #16
0
        /// <summary>
        /// Begins creating the group
        /// </summary>
        private void StartCreatingNewGroup()
        {
            ExchCmds powershell = null;
            ADUsers users = null;

            try
            {
                users = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                // User input minus the spaces
                string emailInput = txtEmailAddress.Text.Replace(" ", string.Empty);

                ExchangeGroup group = new ExchangeGroup();
                group.DisplayName = txtDisplayName.Text;
                group.PrimarySmtpAddress = string.Format("{0}@{1}", emailInput, ddlDomains.SelectedItem.Value);
                group.SamAccountName = emailInput;
                group.CompanyCode = CPContext.SelectedCompanyCode;
                group.ModerationEnabled = cbMustBeApprovedByAModerator.Checked;
                group.Hidden = cbGroupHidden.Checked;

                // Check the length of the sAMAccountName (cannot exceed 19 characters)
                if (group.SamAccountName.Length > 19)
                {
                        group.SamAccountName = group.SamAccountName.Substring(0, 18);
                        this.logger.Debug("User's sAMAccountName was to long and had to be shortened to: " + group.SamAccountName);
                }

                // Compile the sAMAccountName
                string finalSamAccountName = emailInput;
                for (int i = 1; i < 999; i++)
                {
                    if (users.DoesSamAccountNameExist(finalSamAccountName))
                    {
                        this.logger.Debug("SamAccountName " + finalSamAccountName + " is already in use. Trying to find another account name...");
                        finalSamAccountName = group.SamAccountName + i.ToString(); // We found a match so we need to increment the number

                        // Make sure the SamAccountName is less than 19 characters
                        if (finalSamAccountName.Length > 19)
                        {
                            finalSamAccountName = finalSamAccountName.Substring(0, 18 - i.ToString().Length) + i.ToString(); // Make sure it isn't above 19 characters
                            this.logger.Debug("New SamAccountName was too long and was trimmed to " + finalSamAccountName);
                        }
                    }
                    else
                    {
                        // No match was found which means we can continue and break out of the loop
                        group.SamAccountName = finalSamAccountName;
                        this.logger.Debug("Found SamAccountName not in use: " + group.SamAccountName);
                        break;
                    }
                }

                // Make sure to remove any spaces
                string ownersString = hfModifiedOwners.Value.Trim();
                string membersString = hfModifiedMembership.Value.Trim();

                // Our string seperator to split the owners and members information
                string[] separators = { "||" };

                // Collection of owners
                group.ManagedBy = ownersString.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                if (group.ManagedBy == null || group.ManagedBy.Length < 1)
                    throw new Exception("You did not select a group owner. There must be at least one group owner to create a distribution group.");
               
                // Collection of members
                group.MembersArray = membersString.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                if (group.MembersArray == null || group.MembersArray.Length < 1)
                    throw new Exception("You did not select a member. There must be at least one group member to create a distribution group.");
                                
                // Go through membership approval settings
                group.JoinRestriction = "Open";
                if (rbMembershipApprovalJoinClosed.Checked)
                    group.JoinRestriction = "Closed";
                else if (rbMembershipApprovalJoinApproval.Checked)
                    group.JoinRestriction = "ApprovalRequired";

                group.DepartRestriction = "Open";
                if (rbMembershipApprovalLeaveClosed.Checked)
                    group.DepartRestriction = "Closed";

                //
                // Go through delivery management settings
                //
                group.RequireSenderAuthentication = true;
                if (rbDeliveryManagementInsideOutside.Checked)
                    group.RequireSenderAuthentication = false;

                // Compile the list of "Allowed senders" (if any)
                List<string> allowedSenders = new List<string>();
                foreach (ListItem li in lstDeliveryManagementRestrict.Items)
                {
                    if (li.Selected)
                        allowedSenders.Add(li.Value);
                }
                if (allowedSenders.Count > 0)
                    group.WhoCanSendToGroup = allowedSenders.ToArray();


                //
                // Go through message approval settings
                //
                group.SendModerationNotifications = "Never";
                if (rbMessageApprovalNotifyAll.Checked)
                    group.SendModerationNotifications = "Always";
                else if (rbMessageApprovalNotifyInternal.Checked)
                    group.SendModerationNotifications = "Internal";

                // Compile the list of "Group Moderators" (if any)
                List<string> groupModerators = new List<string>();
                foreach (ListItem li in lstGroupModerators.Items)
                {
                    if (li.Selected)
                        groupModerators.Add(li.Value);
                }
                if (groupModerators.Count > 0)
                    group.GroupModerators = groupModerators.ToArray();


                // Compile the list of senders that don't require approval
                List<string> bypassModerationSenders = new List<string>();
                foreach (ListItem li in lstSendersDontRequireApproval.Items)
                {
                    if (li.Selected)
                        bypassModerationSenders.Add(li.Value);
                }
                if (bypassModerationSenders.Count > 0)
                    group.SendersNotRequiringApproval = bypassModerationSenders.ToArray();

                // Create group
                powershell.New_DistributionGroup(group, Retrieve.GetCompanyExchangeOU);

                // Add group to SQL
                SQLExchange.AddDistributionGroup("CN=" + group.PrimarySmtpAddress + "," + Retrieve.GetCompanyExchangeOU, CPContext.SelectedCompanyCode, group.DisplayName, group.PrimarySmtpAddress, cbGroupHidden.Checked);
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                // Refresh the distribution group view
                GetDistributionGroups();
            }
        }
        /// <summary>
        /// Gets all users for this company from active directory
        /// and removes the ones that are already in CloudPanel
        /// </summary>
        private void GetAllMissingUsers()
        {
            ADUsers users = null;

            try
            {
                // Clear datasource
                repeater.DataSource = null;
                repeater.DataBind();

                // Get a list of current users so we do not show those
                List<BaseUser> currentUsers = SQLUsers.GetUsers(CPContext.SelectedCompanyCode);

                // Filter out the list of current users to get the UserPrincipalNames only
                var upns = new List<string>(currentUsers.Select(x => x.UserPrincipalName));

                // Initialize our users class
                users = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);

                // Find all users from the OU but exclude the existing ones
                List<ADUser> foundUsers = users.GetAllUsers(Retrieve.GetCompanyUsersOU, upns, false);
                if (foundUsers != null && foundUsers.Count > 0)
                {
                    // Bind to our repeater
                    repeater.DataSource = foundUsers;
                    repeater.DataBind();
                }
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Error getting users: " + ex.ToString() + "|" + Retrieve.GetCompanyUsersOU);
            }
            finally
            {
                if (users != null)
                    users.Dispose();
            }
        }
Пример #18
0
 bool CalcIsKnownUser(NGitLab.Models.User gitLabUser)
 {
     return(ADUsers.ContainsKey(gitLabUser.Username));
 }
Пример #19
0
        /// <summary>
        /// Unlocks the user account
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkUnlockAccount_Click(object sender, EventArgs e)
        {
            ADUsers user = null;
            try
            {
                // Initialize object
                user = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);

                // Unlock the account
                user.UnlockAccount(txtEditLoginName.Text);

                // Change the checkbox and link
                cbUserLockedOut.Checked = false;
                lnkUnlockAccount.Visible = false;

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, "Successfully unlocked account " + txtEditLoginName.Text);
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Error unlocking account: " + ex.Message);
            }
            finally
            {
                if (user != null)
                    user.Dispose();
            }
        }
Пример #20
0
        /// <summary>
        /// Deletes a user from Active Directory and SQL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeleteYes_Click(object sender, EventArgs e)
        {
            // Proceed with deleting the user
            ADUsers user = null;

            try
            {
                // Delete from AD
                user = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);
                user.Delete(hfDeleteUserPrincipalName.Value);

                // Delete from SQL
                SQLUsers.DeleteUser(hfDeleteUserPrincipalName.Value, CPContext.SelectedCompanyCode);

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessDeleteUser + lbDeleteDisplayName.Text);
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (user != null)
                    user.Dispose();

                // Change back to users view
                GetUsers();
            }
        }
Пример #21
0
        /// <summary>
        /// Updates an existing user
        /// </summary>
        protected void btnEditSaveUser_Click(object sender, EventArgs e)
        {
            ADUsers users = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);

            try
            {
                // Create our user object
                ADUser user = new ADUser();
                user.UserPrincipalName = txtEditLoginName.Text;
                user.SamAccountName = txtEditSamAccountName.Text;
                user.CompanyCode = CPContext.SelectedCompanyCode;
                user.Firstname = txtEditFirstName.Text;
                user.Middlename = txtEditMiddleName.Text;
                user.Lastname = txtEditLastName.Text;
                user.DisplayName = txtEditDisplayName.Text;
                user.Department = txtEditDepartment.Text;
                user.IsCompanyAdmin = cbEditCompanyAdmin.Checked;
                user.IsResellerAdmin = cbEditResellerAdmin.Checked;
                user.IsEnabled = cbEnableUser.Checked;
                user.PasswordNeverExpires = cbEditPwdNeverExpires.Checked;

                if (!string.IsNullOrEmpty(txtEditPwd1.Text))
                    user.Password = txtEditPwd1.Text;

                // Update our user in Active Directory
                users.Edit(user);

                // Update SQL
                DbSql.Update_User(user);

                // Do not save if they are a super admin or reseller admin or company admin permissions were removed
                if (Master.IsSuperAdmin || Master.IsResellerAdmin || !cbEditCompanyAdmin.Checked)
                {
                    // Modify the users permissions if they are a company admin
                    ModifyAdminPermissions(user.UserPrincipalName, cbEditCompanyAdmin.Checked, false);
                }

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessUpdateUser + user.DisplayName + "!");

                // Refresh View
                GetUsers();
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);

                // Log Error //
                this.logger.Error("There was an error updating a user for company " + CPContext.SelectedCompanyName, ex);
            }
            finally
            {
                if (users != null)
                    users.Dispose();
            }
        }
        /// <summary>
        /// Starts the import process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImportSave_Click(object sender, EventArgs e)
        {
            ADUsers adUsers = null;
            ADGroups adGroups = null;

            try
            {
                string companyCode = CPContext.SelectedCompanyCode; // Get the current company code that is selected

                string[] selectedUsers = GetSelectedUsers();
                if (selectedUsers != null && selectedUsers.Length > 0)
                {
                    // Check the limits
                    if (CheckUserLimit(selectedUsers.Length))
                        throw new Exception("You have selected too many users and it would have caused you to go over the user limit set for your company. Please select fewer users and try again.");

                    // Check mailbox limits if checkbox is checked
                    if (cbUsersAlreadyEnabledExchange.Checked && CheckMailboxLimit(selectedUsers.Length))
                        throw new Exception("You have selected too many users that have mailboxes and it would have caused you to go over the mailbox limit set for your company. Please select fewer users and try again.");

                    // Initialize our Active Directory object
                    adUsers = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);
                    adGroups = new ADGroups(Config.Username, Config.Password, Config.PrimaryDC);

                    // Pull detailed information from ActiveDirectory on the selected users
                    List<ADUser> adUsersInfo = adUsers.GetAllUsers(Retrieve.GetCompanyOU, selectedUsers.ToList(), true);

                    // Validate the domains for the users login matches a domain in this company
                    ValidateDomains(adUsersInfo);

                    // Now insert into SQL
                    foreach (ADUser u in adUsersInfo)
                    {
                        // Set the company code of the user because it won't have it
                        u.CompanyCode = companyCode;

                        // Make sure the user belongs to the AllUsers@ group
                        adGroups.ModifyMembership("AllUsers@" + companyCode.Replace(" ", string.Empty), u.UserPrincipalName, 
                            System.DirectoryServices.AccountManagement.IdentityType.Name, System.DirectoryServices.AccountManagement.IdentityType.UserPrincipalName, 
                            false, false);

                        SQLUsers.AddUser(u);
                    }

                    // Now check if we are doing mailboxes
                    if (cbUsersAlreadyEnabledExchange.Checked)
                    {
                        ImportExchangeUsers(adUsersInfo);
                    }
                }

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, "Successfully imported users.");
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Error importing users: " + ex.Message);
            }
            finally
            {
                if (adGroups != null)
                    adGroups.Dispose();

                if (adUsers != null)
                    adUsers.Dispose();
            }

            // Retrieve a new list of useres
            GetAllMissingUsers();
        }
Пример #23
0
        /// <summary>
        /// Create new user
        /// </summary>
        protected void btnSaveUser_Click(object sender, EventArgs e)
        {
            ADUsers users = new ADUsers(Config.Username, Config.Password, Config.PrimaryDC);

            try
            {
                // Create our user object
                ADUser user = new ADUser();
                user.CompanyCode = CPContext.SelectedCompanyCode;
                user.Firstname = txtFirstName.Text.Trim();
                user.Middlename = txtMiddleName.Text.Trim();
                user.Lastname = txtLastName.Text.Trim();
                user.DisplayName = txtDisplayName.Text.Trim();
                user.Department = txtDepartment.Text.Trim();
                user.UserPrincipalName = txtLoginName.Text.Replace(" ", string.Empty) + "@" + ddlLoginDomain.SelectedValue;
                user.IsCompanyAdmin = cbIsCompanyAdministrator.Checked;
                user.IsResellerAdmin = cbIsResellerAdministrator.Checked;
                user.PasswordNeverExpires = cbPasswordNeverExpires.Checked;
                
                // Check if we are using custom name attribute
                if (Config.CustomNameAttribute)
                    user.Name = txtFullName.Text.Trim();
                else
                    user.Name = string.Empty; // Set to empty so our class knows to use UPN instead 

                // Create our user
                ADUser returnedUser = users.Create(user, Retrieve.GetCompanyUsersOU, txtPassword1.Text);
            
                // Insert into SQL
                SQLUsers.AddUser(returnedUser);

                // Modify the users permissions if they are a company admin
                ModifyAdminPermissions(user.UserPrincipalName, cbIsCompanyAdministrator.Checked, true);

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessCreateUser + " " + user.DisplayName + "!");

                // Refresh View
                GetUsers();
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);

                // Log Error //
                this.logger.Error("There was an error creating an new user for company " + CPContext.SelectedCompanyName, ex);
            }
            finally
            {
                users.Dispose();
            }
        }