/// <summary>
        /// Enables Exchange and updates the database
        /// </summary>
        private void EnableExchange()
        {
            ExchCmds cmds = null;

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

                // Create Exchange objects for company
                cmds.Enable_Company(CPContext.SelectedCompanyCode, "AllUsers@" + CPContext.SelectedCompanyCode, Retrieve.GetCompanyExchangeOU);

                // Update SQL
                SQLExchange.SetCompanyExchangeEnabled(CPContext.SelectedCompanyCode, true);

                // Update Status Message
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessEnableExchange);

                // Change panel
                enableExchange.Visible = false;
                disableExchange.Visible = true;

                // Set Random string
                lbDeleteLabel.Text = Retrieve.RandomString;
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (cmds != null)
                    cmds.Dispose();
            }
        }
        /// <summary>
        /// Gets the public folder hierarchy
        /// </summary>
        private void GetPublicFolders()
        {
            ExchCmds powershell = null;

            try
            {
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);
                
                // Get public folders
                List<BasePublicFolder> pf = powershell.Get_PublicFolderHierarchy(CPContext.SelectedCompanyCode, Config.ExchangeVersion);

                this.logger.Debug("Sorting public folder hierarchy for " + CPContext.SelectedCompanyCode);
                pf.Sort((pf1, pf2) => pf1.ParentPath.CompareTo(pf2.ParentPath));

                foreach (BasePublicFolder p in pf)
                {
                    this.logger.Debug("Processing public folder " + p.Path);

                    if (p.ParentPath.Equals(@"\"))
                    {
                        TreeNode tmp = new TreeNode();
                        tmp.Text = " - " + p.Name;
                        tmp.Value = p.Path;
                        tmp.ImageUrl = "~/img/icons/16/folder.png";

                        treePublicFolders.Nodes.Add(tmp);
                    }
                    else
                    {
                        // It isn't a parent node so we need to find its parent then add it
                        FindNode(treePublicFolders.Nodes, p);
                    }
                }

            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();
            }
        }
        /// <summary>
        /// Updates the group
        /// </summary>
        private void StartUpdatingNewGroup()
        {
            ExchCmds powershell = null;

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

                string displayName = txtDisplayName.Text;
                string emailAddress = txtEmailAddress.Text.Replace(" ", string.Empty) + "@" + ddlDomains.SelectedItem.Value;

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

                // Compile a list of owners
                List<string> newOwners = hfOriginalOwners.Value.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();
                List<string> ownerAdded = hfModifiedOwners.Value.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();
                List<string> ownerRemoved = hfRemovedOwners.Value.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();
                
                // Now lets see who was added or removed from the owners section
                newOwners.RemoveAll(ownerRemoved.Contains);  // removes everything from original owners that was in the removed list
                newOwners.AddRange(ownerAdded); // Adds everything that was in the ownerAdded list (except duplicates)
               

                // Compile a list of members
                List<string> newMembers = hfModifiedMembership.Value.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();
                List<string> removedMembers = hfRemovedMembership.Value.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();

                // Go through membership approval settings
                string memberJoinRestriction = "Open";
                if (rbMembershipApprovalJoinClosed.Checked)
                    memberJoinRestriction = "Closed";
                else if (rbMembershipApprovalJoinApproval.Checked)
                    memberJoinRestriction = "ApprovalRequired";

                string memberDepartRestriction = "Open";
                if (rbMembershipApprovalLeaveClosed.Checked)
                    memberDepartRestriction = "Closed";

                //
                // Go through delivery management settings
                //
                bool requireSenderAuthentication = true;
                if (rbDeliveryManagementInsideOutside.Checked)
                    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 < 1)
                    allowedSenders = null; // Clear (null) the list if it is empty

                //
                // Go through message approval settings
                //
                string notify = "Never";
                if (rbMessageApprovalNotifyAll.Checked)
                    notify = "Always";
                else if (rbMessageApprovalNotifyInternal.Checked)
                    notify = "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 < 1)
                    groupModerators = null; // Clear (null) the list if it is empty

                // 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 < 1)
                    bypassModerationSenders = null; // Clear (null) the list if it is empty

                // Update Group
                powershell.Set_DistributionGroup(displayName, CPContext.SelectedCompanyCode, hfCurrentEmailAddress.Value, emailAddress, memberJoinRestriction, memberDepartRestriction, 
                    cbMustBeApprovedByAModerator.Checked, notify, newOwners, groupModerators, allowedSenders, bypassModerationSenders, cbGroupHidden.Checked, requireSenderAuthentication);

                // Update SQL
                SQLExchange.UpdateDistributionGroup("CN=" + emailAddress + "," + Retrieve.GetCompanyExchangeOU, hfCurrentEmailAddress.Value, emailAddress, displayName, cbGroupHidden.Checked);

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Warning, Resources.LocalizedText.NotificationWarningUpdateGroup);

                // Add the new members
                foreach (string added in newMembers)
                {
                    powershell.Add_DistributionGroupMember(emailAddress, added);
                }

                // Remove members that are no longer part of the group
                foreach (string removed in removedMembers)
                {
                    powershell.Remove_DistributionGroupMember(emailAddress, removed);
                }


                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessUpdateGroup);
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.ToString());
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                // Refresh the distribution group view
                GetDistributionGroups();
            }
        }
        /// <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>
        /// Saves public folder information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPFSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hfPublicFolderPath.Value))
                notification1.SetMessage(controls.notification.MessageType.Warning, "You must first select a public folder before trying to save properties.");
            else
            {
                ExchCmds powershell = null;

                try
                {
                    // Initialize the powershell module
                    powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                    // Set the public folder
                    int warningSize, prohibitSize, maxItemSize, ageLimit, keepDeletedItems = 0;

                    // Parse the values
                    int.TryParse(txtWarningSizeMB.Text, out warningSize);
                    int.TryParse(txtProhibitPostMB.Text, out prohibitSize);
                    int.TryParse(txtMaxItemSize.Text, out maxItemSize);
                    int.TryParse(txtAgeLimit.Text, out ageLimit);
                    int.TryParse(txtKeepDeletedItems.Text, out keepDeletedItems);

                    powershell.Set_PublicFolder(hfPublicFolderPath.Value, warningSize, prohibitSize, maxItemSize, ageLimit, keepDeletedItems, Config.ExchangeVersion);

                    // Show saved message
                    notification1.SetMessage(controls.notification.MessageType.Warning, "Successfully saved public folder information but was unable to modify the email settings.");

                    // Now continue to the mail section
                    if (!cbPFCurrentEmailEnabled.Checked && cbPFEnableEmail.Checked)
                    {
                        // User is enabling email on the public folder
                        if (string.IsNullOrEmpty(txtDisplayName.Text) || string.IsNullOrEmpty(txtPrimaryEmail.Text))
                            throw new Exception("You must fill out the display name and email address if you want to mail enable a public folder.");

                        powershell.Enable_MailPublicFolder(hfPublicFolderPath.Value, cbPFHiddenFromAddressLists.Checked, CPContext.SelectedCompanyCode, txtDisplayName.Text, string.Format("{0}@{1}", txtPrimaryEmail.Text.Replace(" ", string.Empty), ddlEmailDomains.SelectedValue));
                    }
                    else if (cbPFCurrentEmailEnabled.Checked && !cbPFEnableEmail.Checked)
                    {
                        // User is disabling email on the public folder
                        powershell.Disable_MailPublicFolder(hfPublicFolderPath.Value);
                    }
                    else if (cbPFCurrentEmailEnabled.Checked && cbPFEnableEmail.Checked)
                    {
                        // User is just modifing settings on the mail public folder
                        if (string.IsNullOrEmpty(txtDisplayName.Text) || string.IsNullOrEmpty(txtPrimaryEmail.Text))
                            throw new Exception("You must fill out the display name and email address if you want to change a mail enabled public folder.");

                        powershell.Set_MailPublicFolder(hfPublicFolderPath.Value, cbPFHiddenFromAddressLists.Checked, CPContext.SelectedCompanyCode, txtDisplayName.Text, string.Format("{0}@{1}", txtPrimaryEmail.Text.Replace(" ", string.Empty), ddlEmailDomains.SelectedValue));
                    }

                    // Show success message
                    notification1.SetMessage(controls.notification.MessageType.Success, "Successfully updated all public folder information.");
                }
                catch (Exception ex)
                {
                    notification1.SetMessage(controls.notification.MessageType.Error, "Error saving public folder information: " + ex.Message);
                }
                finally
                {
                    if (powershell != null)
                        powershell.Dispose();

                    // Refresh the current public folder
                    GetPublicFolder(hfPublicFolderPath.Value);
                }
            }
        }
        /// <summary>
        /// Gets a specific public folder from Exchange and displays the information
        /// </summary>
        /// <param name="path"></param>
        private void GetPublicFolder(string path)
        {
            ExchCmds powershell = null;

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

                BasePublicFolder pf = powershell.Get_PublicFolder(path);
                txtPublicFolderName.Text = pf.Name;
                txtMaxItemSize.Text = pf.MaxItemSize;
                txtWarningSizeMB.Text = pf.IssueWarningQuota;
                txtProhibitPostMB.Text = pf.ProhibitPostQuota;
                txtAgeLimit.Text = pf.AgeLimit;
                txtKeepDeletedItems.Text = pf.RetainDeletedItemsFor;

                // Set our hidden field for the selected public folder
                hfPublicFolderPath.Value = pf.Path;

                if (pf.MailFolderInfo == null)
                {
                    // Set that the public folder currently isn't enabled for email
                    cbPFCurrentEmailEnabled.Checked = false;

                    txtDisplayName.Text = string.Empty;
                    txtPrimaryEmail.Text = string.Empty;
                    cbPFEnableEmail.Checked = false;
                }
                else
                {
                    // Set the the public folder IS currently enabled for email
                    cbPFCurrentEmailEnabled.Checked = true;

                    cbPFEnableEmail.Checked = true;
                    txtDisplayName.Text = pf.MailFolderInfo.DisplayName;
                    cbPFHiddenFromAddressLists.Checked = pf.MailFolderInfo.Hidden;

                    string[] emailSplit = pf.MailFolderInfo.EmailAddress.Split('@');
                    txtPrimaryEmail.Text = emailSplit[0];

                    ListItem item = ddlEmailDomains.Items.FindByValue(emailSplit[1]);
                    if (item != null)
                        ddlEmailDomains.SelectedValue = item.Value;
                }

                // Check if the user is a super admin or reseller admin.
                // If they are not we need to diasble the fields
                if (Master.IsSuperAdmin || Master.IsResellerAdmin)
                {
                    txtMaxItemSize.ReadOnly = false;
                    txtWarningSizeMB.ReadOnly = false;
                    txtProhibitPostMB.ReadOnly = false;
                    txtAgeLimit.ReadOnly = false;
                    txtKeepDeletedItems.ReadOnly = false;
                }
                else
                {
                    txtMaxItemSize.ReadOnly = true;
                    txtWarningSizeMB.ReadOnly = true;
                    txtProhibitPostMB.ReadOnly = true;
                    txtAgeLimit.ReadOnly = true;
                    txtKeepDeletedItems.ReadOnly = true;
                }
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();
            }
        }
        /// <summary>
        /// Removes a public folder from a company
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDisableYes_Click(object sender, EventArgs e)
        {
            ExchCmds powershell = null;

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

                // Remove public folder
                powershell.Remove_PublicFolder(CPContext.SelectedCompanyCode);

                // Remove from SQL
                SQLPublicFolders.Update_PublicFolderForCompany(CPContext.SelectedCompanyCode, false);

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, "Successfully disabled public folders for your company");

                // Change view
                panelDisablePublicFolders.Visible = false;
                panelEditPublicFolders.Visible = false;
                panelEnablePublicFolders.Visible = true;
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Failed to remove public folders. Please contact support: " + ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();
            }
        }
        protected void btnDisableYes_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(hfDisableUserPrincipalName.Value))
            {
                ExchCmds powershell = null;

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

                    // Disable the mailbox
                    powershell.Disable_Mailbox(hfDisableUserPrincipalName.Value);

                    // Delete from SQL
                    SQLMailboxes.DisableMailbox(hfDisableUserPrincipalName.Value, CPContext.SelectedCompanyCode);

                    // Notify
                    notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessMailboxDisable + hfDisableUserPrincipalName.Value);

                    // Wipe
                    hfDisableUserPrincipalName.Value = null;
                }
                catch (Exception ex)
                {
                    notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
                }
                finally
                {
                    if (powershell != null)
                        powershell.Dispose();

                    // Go back to mailbox user view
                    GetMailboxUsers();
                }
            }
        }
        /// <summary>
        /// Sets the user Exchange information
        /// </summary>
        /// <param name="adUsersInfo"></param>
        private void ImportExchangeUsers(List<ADUser> adUsersInfo)
        {
            ExchCmds powershell = null;

            try
            {
                // Get the plan that was selected
                MailboxPlan selectedPlan = SQLPlans.GetMailboxPlan(int.Parse(ddlMailboxPlans.SelectedValue));

                // Get the selected mailbox size based on the slider
                int selectedSize = int.Parse(hfMailboxSizeMB.Value);
                selectedPlan.SetSizeInMB = selectedSize;

                // Calculate the additional MB that was added
                int totalAdded = selectedSize - selectedPlan.SizeInMB;

                // Initialize our powershell object
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                // Now we need to loop through and set the mailbox information
                foreach (ADUser u in adUsersInfo)
                {
                    // Set the mailbox information
                    powershell.Set_Mailbox(u.UserPrincipalName, CPContext.SelectedCompanyCode, selectedPlan);

                    // Update SQL
                    SQLUsers.UpdateUserMailbox(u, selectedPlan);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdatePlan_Click(object sender, EventArgs e)
        {
            BaseActivesyncPolicy policy = new BaseActivesyncPolicy();

            ExchCmds powershell = null;
            try
            {
                // Fill in custom object
                policy.CompanyCode = "";
                policy.DisplayName = txtDisplayName.Text;
                policy.Description = txtDescription.Text;
                policy.AllowNonProvisionableDevice = cbAllowNonProvisionableDevices.Checked;

                if (!string.IsNullOrEmpty(txtRefreshInterval.Text))
                    policy.DevicePolicyRefreshInterval = int.Parse(txtRefreshInterval.Text);
                else
                    policy.DevicePolicyRefreshInterval = 0;

                //
                // PASSWORD TAB
                //
                policy.DevicePasswordEnabled = cbRequirePassword.Checked;
                if (policy.DevicePasswordEnabled)
                {
                    policy.AlphanumericDevicePasswordRequired = cbRequireAlphaNumericPassword.Checked;

                    if (!string.IsNullOrEmpty(txtMinimumNumberOfCharacterSets.Text))
                        policy.MinDevicePasswordComplexCharacters = int.Parse(txtMinimumNumberOfCharacterSets.Text);
                    else
                        policy.MinDevicePasswordComplexCharacters = 0;

                    policy.PasswordRecoveryEnabled = cbEnablePasswordRecovery.Checked;
                    policy.RequireDeviceEncryption = cbRequireEncryption.Checked;
                    policy.RequireStorageCardEncryption = cbRequireEncryptionOnStorageCard.Checked;
                    policy.AllowSimpleDevicePassword = cbAllowSimplePassword.Checked;

                    if (!string.IsNullOrEmpty(txtNumberOfFailedAttemptsAllowed.Text))
                        policy.MaxDevicePasswordFailedAttempts = int.Parse(txtNumberOfFailedAttemptsAllowed.Text);
                    else
                        policy.MaxDevicePasswordFailedAttempts = 0;

                    if (!string.IsNullOrEmpty(txtMinimumPasswordLength.Text))
                        policy.MinDevicePasswordLength = int.Parse(txtMinimumPasswordLength.Text);
                    else
                        policy.MinDevicePasswordLength = 0;

                    if (!string.IsNullOrEmpty(txtInactivityTimeout.Text))
                        policy.MaxInactivityTimeDeviceLock = int.Parse(txtInactivityTimeout.Text);
                    else
                        policy.MaxInactivityTimeDeviceLock = 0;

                    if (!string.IsNullOrEmpty(txtPasswordExpiration.Text))
                        policy.DevicePasswordExpiration = int.Parse(txtPasswordExpiration.Text);
                    else
                        policy.DevicePasswordExpiration = 0;

                    if (!string.IsNullOrEmpty(txtEnforcePasswordHistory.Text))
                        policy.DevicePasswordHistory = int.Parse(txtEnforcePasswordHistory.Text);
                    else
                        policy.DevicePasswordHistory = 0;
                }


                //
                // SYNC SETTINGS
                //
                policy.MaxCalendarAgeFilter = ddlPastCalendarItems.SelectedValue;
                policy.MaxEmailAgeFilter = ddlPastEmailItems.SelectedValue;

                if (!string.IsNullOrEmpty(txtLimitEmailSize.Text))
                    policy.MaxEmailBodyTruncationSize = int.Parse(txtLimitEmailSize.Text);
                else
                    policy.MaxEmailBodyTruncationSize = 0;

                policy.RequireManualSyncWhenRoaming = cbAllowDirectPushWhenRoaming.Checked;
                policy.AllowHTMLEmail = cbAllowHTMLEmail.Checked;
                policy.AttachmentsEnabled = cbAllowAttachmentDownload.Checked;

                if (policy.AttachmentsEnabled)
                {
                    if (!string.IsNullOrEmpty(txtMaximumAttachmentSize.Text))
                        policy.MaxAttachmentSize = int.Parse(txtMaximumAttachmentSize.Text);
                    else
                        policy.MaxAttachmentSize = 0;
                }

                //
                // DEVICE
                //
                policy.AllowStorageCard = cbAllowRemovableStorage.Checked;
                policy.AllowCamera = cbAllowCamera.Checked;
                policy.AllowWiFi = cbAllowWiFi.Checked;
                policy.AllowIrDA = cbAllowInfrared.Checked;
                policy.AllowInternetSharing = cbAllowInternetSharing.Checked;
                policy.AllowRemoteDesktop = cbAllowRemoteDesktop.Checked;
                policy.AllowDesktopSync = cbAllowDesktopSync.Checked;
                policy.AllowBluetooth = ddlAllowBluetooth.SelectedValue;
                policy.AllowTextMessaging = cbAllowTextMessaging.Checked;

                //
                // DEVICE APPLICATIONS
                //
                policy.AllowBrowser = cbAllowBrowser.Checked;
                policy.AllowConsumerEmail = cbAllowConsumerMail.Checked;
                policy.AllowUnsignedApplications = cbAllowUnsignedApplications.Checked;
                policy.AllowUnsignedInstallationPackages = cbAllowUnsignedInstallPackages.Checked;
                


                // Initialize powershell
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                // Check if we are creating a new policy or updating existing
                if (ddlActiveSyncPlan.SelectedIndex > 0)
                {
                    policy.ASID = int.Parse(ddlActiveSyncPlan.SelectedValue);

                    // Update Exchange
                    powershell.Update_ActiveSyncPolicy(policy, Config.ExchangeVersion);

                    // Update SQL database
                    SQLExchange.UpdateExchangeActiveSyncPolicy(policy);

                    // Update notification
                    notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessUpdateAS + policy.DisplayName);
                }
                else
                {
                    // Create new policy
                    powershell.New_ActiveSyncPolicy(policy, Config.ExchangeVersion);

                    // Add to SQL database
                    SQLExchange.AddExchangeActiveSyncPolicy(policy);

                    // Update notification
                    notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessCreatedAS + policy.DisplayName);
                }

            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                // Refresh view
                GetPolicies();
            }
        }
        /// <summary>
        /// Disables Exchange and updates the database
        /// </summary>
        private void DisableExchange()
        {
            ExchCmds cmds = null;

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

                // Get a list of accepted domains
                var convertedDomains = new List<string>();
                List<Domain> domains = SQLExchange.GetAcceptedDomains(CPContext.SelectedCompanyCode);
                if (domains != null && domains.Count > 0)
                {
                    // Extracts just the domain name from the list
                    convertedDomains = (from d in domains select d.DomainName as string).ToList();
                }

                // Delete from Exchange
                cmds.Disable_Company(CPContext.SelectedCompanyCode, convertedDomains);

                // Delete from SQL
                SQLExchange.DisableExchange(CPContext.SelectedCompanyCode);

                // Update Status Message
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessDisableExchange);

                // Change panel
                enableExchange.Visible = true;
                disableExchange.Visible = false;
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (cmds != null)
                    cmds.Dispose();
            }
        }
        /// <summary>
        /// Begins the process of creating the mailboxes
        /// </summary>
        private void EnableNewMailboxes(string companyCode)
        {
            ExchCmds powershell = null;

            try
            {
                // Initialize powershell and sql
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                //
                // Get all the users and validate they selected a user and it won't put the company over their allowed limit
                //
                List<MailboxUser> usersToEnable = GetUsersToEnable();
                if (usersToEnable.Count < 1)
                    throw new Exception("You must select at least one user to enable for a mailbox. You selected zero users.");
                if (SQLLimits.IsCompanyAtMailboxLimit(companyCode, usersToEnable.Count))
                    throw new Exception("You have selected too many users that would have caused your company to have more mailboxes that your company is allowed to have. Selected fewer users and try again.");

                //
                // Get the mailbox plan
                //
                int planId = int.Parse(ddlEnableMailboxPlans.SelectedValue);
                int setSizeInMB = int.Parse(hfMailboxSizeMB.Value);
                                
                MailboxPlan plan = DbSql.Get_MailboxPlan(planId);
                plan.SetSizeInMB = setSizeInMB; // set the size that the user selected



                //
                // Format all the users email addresses based on what they selected
                //
                FormatAllUsersEmail(usersToEnable, ddlDomains.SelectedValue);


                // A string of all our problem email accounts that gave an error when enabling
                string errorEnabling = string.Empty;


                // Now loop through each user
                foreach (MailboxUser user in usersToEnable)
                {
                    if (string.IsNullOrEmpty(user.PrimarySmtpAddress.Split('@')[0]))
                        errorEnabling += user.DisplayName + ", ";
                    else
                    {
                        user.CompanyCode             = companyCode;
                        user.ActiveSyncMailboxPolicy = ddlActiveSyncPlan.SelectedIndex > 0 ? ddlActiveSyncPlan.SelectedItem.Text : null;
                        user.Database                = ddlExchangeDatabases.SelectedIndex > 0 ? ddlExchangeDatabases.SelectedValue : string.Empty;
                        

                        // Enabling the mailbox
                        powershell.Enable_Mailbox(user, plan);

                        //
                        // Insert into SQL
                        //
                        DbSql.Update_UserMailboxInfo(user.UserPrincipalName, plan.PlanID, user.PrimarySmtpAddress, (setSizeInMB - plan.SizeInMB), user.ActiveSyncMailboxPolicy);
                        
                        //
                        // Add to the queue to modify the calendar permissions 10 minutes after it has been enabled
                        //
                        DbSql.Add_DatabaseQueue(Enumerations.TaskType.MailboxCalendarPermissions, user.UserPrincipalName, user.CompanyCode, 10, Enumerations.TaskSuccess.NotStarted);
                        
                    }
                }

                // Update the notification
                if (!string.IsNullOrEmpty(errorEnabling))
                    notification1.SetMessage(controls.notification.MessageType.Warning, "Error enabling the following users because of missing data (normally first or last name): " + errorEnabling);
                else
                    notification1.SetMessage(controls.notification.MessageType.Success, "Successfully enabled " + usersToEnable.Count.ToString() + " user(s).");

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

                // Refresh back to the main screen
                GetMailboxUsers();
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                // Refresh the view even if there is an error
                GetMailboxUsers();
            }
        }
        /// <summary>
        /// Saves a mailbox after it has been edited
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEditMailboxSave_Click(object sender, EventArgs e)
        {
            ExchCmds powershell = null;

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

                // Get mailbox plan
                MailboxPlan selectedPlan = SQLPlans.GetMailboxPlan(int.Parse(ddlEditMailboxPlan.SelectedValue));

                // Initialize our collection
                MailboxUser user = new MailboxUser();
                user.UserPrincipalName = hfUserPrincipalName.Value;
                user.DistinguishedName = hfDistinguishedName.Value;
                user.PrimarySmtpAddress = string.Format("{0}@{1}", txtEditPrimaryEmail.Text.Replace(" ", string.Empty), ddlEditPrimaryEmailDomain.SelectedValue);
                user.DeliverToMailboxAndForward = cbDeliverToMailboxAndFoward.Checked;
                user.ActiveSyncMailboxPolicy = ddlActiveSyncPlanEditMailbox.SelectedIndex == 0 ? null : ddlActiveSyncPlanEditMailbox.SelectedItem.Text;

                // Get our forwrading address
                if (ddlForwardTo.SelectedIndex > 0)
                    user.ForwardingAddress = ddlForwardTo.SelectedValue;

                // Get our list of email aliases
                user.EmailAliases = new List<string>();
                if (emailAliases != null && emailAliases.Count > 0)
                {
                    foreach (BaseEmailAliases email in emailAliases)
                    {
                        user.EmailAliases.Add(email.emailAddress);
                    }
                }

                // Get the selected mailbox size based on the slider
                int selectedSize = int.Parse(hfEditMailboxSize.Value);
                int totalAdded = selectedSize - selectedPlan.SizeInMB;
                selectedPlan.SetSizeInMB = selectedSize;

                // Get the permissions and see if anything has changed or not
                GetChangedMailboxPermissions(ref user);


                //
                // Check plan features or if the plan was overridden
                //
                user.ActiveSyncEnabled = cbOverrideOptions.Checked ? cbEnableActiveSync.Checked : selectedPlan.ActiveSyncEnabled;
                user.ECPEnabled = cbOverrideOptions.Checked ? cbEnableECP.Checked : selectedPlan.ECPEnabled;
                user.IMAPEnabled = cbOverrideOptions.Checked ? cbEnableIMAP.Checked : selectedPlan.IMAPEnabled;
                user.MAPIEnabled = cbOverrideOptions.Checked ? cbEnableMAPI.Checked : selectedPlan.MAPIEnabled;
                user.OWAEnabled = cbOverrideOptions.Checked ? cbEnableOWA.Checked : selectedPlan.OWAEnabled;
                user.POP3Enabled = cbOverrideOptions.Checked ? cbEnablePOP3.Checked : selectedPlan.POP3Enabled;

                // Update the mailbox
                powershell.Set_Mailbox(user, selectedPlan);

                // Update mailbox in SQL
                SQLUsers.UpdateUserMailbox(user, selectedPlan);

                // Set notification
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessMailboxUpdate + user.UserPrincipalName);
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                // Revert to main screen
                GetMailboxUsers();
            }
        }
        private void EditMailbox(string userPrincipalName, string mailboxPlanName)
        {
            // Hide all panels except edit panel
            panelDisableMailbox.Visible = false;
            panelEnableUsers.Visible = false;
            panelMailboxes.Visible = false;

            // Show edit panel
            panelEditMailbox.Visible = true;

            // Now get the mailbox information
            ExchCmds powershell = null;
            try
            {
                // Refresh plans again otherwise the jQuery won't work
                GetMailboxPlans();

                // Get list of forwarding addresses
                GetForwardingAddresses();

                // Initilize 
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                // Get user object
                MailboxUser user = powershell.Get_Mailbox(userPrincipalName);

                // Set plan information
                logger.DebugFormat("Setting mailbox plan...");
                ddlEditMailboxPlan.SelectedIndex = ddlEditMailboxPlan.Items.IndexOf(ddlEditMailboxPlan.Items.FindByText(mailboxPlanName));

                // Populate information
                logger.DebugFormat("Setting mailbox plan...");
                hfUserPrincipalName.Value = userPrincipalName;
                hfDistinguishedName.Value = user.DistinguishedName;
                txtDisplayName.Text = user.DisplayName;
                txtEditPrimaryEmail.Text = user.PrimarySmtpAddress.Split('@')[0];
                ddlEditPrimaryEmailDomain.SelectedValue = user.PrimarySmtpAddress.Split('@')[1];
                cbDeliverToMailboxAndFoward.Checked = user.DeliverToMailboxAndForward;

                // Get activesync policy
                logger.DebugFormat("Checking for activesync policy");
                if (string.IsNullOrEmpty(user.ActiveSyncMailboxPolicy))
                    ddlActiveSyncPlanEditMailbox.SelectedIndex = 0;
                else
                {
                    ListItem item = ddlActiveSyncPlanEditMailbox.Items.FindByText(user.ActiveSyncMailboxPolicy);
                    if (item != null)
                        ddlActiveSyncPlanEditMailbox.SelectedIndex = ddlActiveSyncPlanEditMailbox.Items.IndexOf(item);
                    else
                        ddlActiveSyncPlanEditMailbox.SelectedIndex = 0;
                }

                //
                // Populate any forwarding address
                //
                logger.DebugFormat("Checking for forwarding address");
                if (!string.IsNullOrEmpty(user.ForwardingAddress))
                {
                    logger.DebugFormat("Forwarding address is {0}", user.ForwardingAddress);
                    string upper = user.ForwardingAddress.ToUpper();

                    var item = ddlForwardTo.Items.Cast<ListItem>().Where(i => i.Value.ToUpper() == upper).FirstOrDefault();
                    if (item != null)
                        ddlForwardTo.SelectedValue = item.Value;
                }
                else
                    ddlForwardTo.SelectedIndex = 0;

                // Set current mailbox size
                currentMailboxSize = user.MailboxSizeInMB;

                //
                // Set the email aliases
                //
                txtAddEmailAlias.Text = string.Empty;
                emailAliases = new List<BaseEmailAliases>();
                if (user.EmailAliases != null)
                {
                    foreach (string email in user.EmailAliases)
                    {
                        emailAliases.Add(new BaseEmailAliases() { emailAddress = email });
                    }
                }

                // Add to ViewState
                ViewState["CPEmailAliases"] = emailAliases;


                //
                // Populate the mailbox permissions for FullAccess
                //
                hfFullAccessOriginal.Value = string.Empty;
                foreach (MailboxPermissions m in user.FullAccessPermissions)
                {
                    ListItem item = lstFullAccessPermissions.Items.FindByValue(m.SamAccountName);
                    if (item != null)
                    {
                        int index = lstFullAccessPermissions.Items.IndexOf(item);
                        lstFullAccessPermissions.Items[index].Selected = true;

                        // Add to our hidden value field for a list of original values
                        hfFullAccessOriginal.Value += m.SamAccountName + ",";
                    }
                }
                this.logger.Debug("Full access permissions for " + user.UserPrincipalName + " when loaded is: " + hfFullAccessOriginal.Value);

                //
                // Populate the mailbox permissions for SendAs
                //
                hfSendAsOriginal.Value = string.Empty;
                foreach (MailboxPermissions m in user.SendAsPermissions)
                {
                    ListItem item = lstSendAsPermissions.Items.FindByValue(m.SamAccountName);
                    if (item != null)
                    {
                        int index = lstSendAsPermissions.Items.IndexOf(item);
                        lstSendAsPermissions.Items[index].Selected = true;

                        // Add to our hidden value field for a list of original values
                        hfSendAsOriginal.Value += m.SamAccountName + ",";
                    }
                }
                this.logger.Debug("Send-As permissions for " + user.UserPrincipalName + " when loaded is: " + hfSendAsOriginal.Value);

                // Bind gridview
                gridEmailAliases.DataSource = emailAliases;
                gridEmailAliases.DataBind();
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.ToString());

                // Reset view
                GetMailboxUsers();
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();
            }
        }
        /// <summary>
        /// Retrieves detailed information about a particular distribution group
        /// </summary>
        /// <param name="groupEmailAddress"></param>
        private void GetDistributionGroup(string groupEmailAddress)
        {
            ExchCmds powershell = null;

            try
            {
                // Initialize powershell session
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                // Get the distribution group
                ExchangeGroup group = powershell.Get_DistributionGroup(groupEmailAddress);

                // Clear fields
                hfModifiedOwners.Value = string.Empty;
                hfModifiedMembership.Value = string.Empty;
                hfRemovedOwners.Value = string.Empty;
                hfRemovedMembership.Value = string.Empty;

                // Populate fields
                GetDomains();
                GetMailObjects();

                // Populate information
                txtDisplayName.Text = group.DisplayName;
                txtEmailAddress.Text = group.PrimarySmtpAddress.Split('@')[0];
                ddlDomains.SelectedValue = group.PrimarySmtpAddress.Split('@')[1];
                cbGroupHidden.Checked = group.Hidden;
                hfCurrentEmailAddress.Value = group.PrimarySmtpAddress;


                //
                // Get the list of users, contacts, and groups that can be added
                //
                List<MailboxUser> groupOwners = SQLMailboxes.GetMailboxUsers(CPContext.SelectedCompanyCode);

                //
                // Find the owners
                //
                hfOriginalOwners.Value = String.Join("||", group.ManagedBy);

                if (groupOwners != null)
                {
                    List<RepeaterOwnership> owners = new List<RepeaterOwnership>();
                    foreach (string s in group.ManagedBy)
                    {
                        MailboxUser tmp = groupOwners.FirstOrDefault(m => m.CanonicalName.Equals(s, StringComparison.CurrentCultureIgnoreCase));
                        if (tmp != null)
                        {
                            owners.Add(new RepeaterOwnership()
                            {
                                DisplayName = tmp.DisplayName,
                                DistinguishedName = tmp.DistinguishedName,
                                ImageUrl = "~/img/icons/16/user.png"
                            });
                        }
                    }

                    // Order list
                    owners.OrderBy(x => x.ImageUrl).ThenBy(x => x.DisplayName);

                    repeaterOwners.DataSource = owners;
                    repeaterOwners.DataBind();
                }

                //
                // Find the members
                //
                hfOriginalMembership.Value = String.Join("||", group.Members);

                List<RepeaterOwnership> members = new List<RepeaterOwnership>();
                foreach (MailObject member in group.Members)
                {
                    if (member.ObjectType == Enumerations.ObjectType.User)
                    {
                        members.Add(new RepeaterOwnership()
                        {
                            DisplayName = member.DisplayName,
                            DistinguishedName = member.DistinguishedName,
                            ImageUrl = "~/img/icons/16/user.png"
                        });
                    }
                    else if (member.ObjectType == Enumerations.ObjectType.Group)
                    {
                        members.Add(new RepeaterOwnership()
                        {
                            DisplayName = member.DisplayName,
                            DistinguishedName = member.DistinguishedName,
                            ImageUrl = "~/img/icons/16/people.png"
                        });
                    }
                    else if (member.ObjectType == Enumerations.ObjectType.Contact)
                    {
                        members.Add(new RepeaterOwnership()
                        {
                            DisplayName = member.DisplayName,
                            DistinguishedName = member.DistinguishedName,
                            ImageUrl = "~/img/icons/16/web.png"
                        });
                    }
                }

                // Order list
                members.OrderBy(x => x.ImageUrl).ThenBy(x => x.DisplayName);

                repeaterMembers.DataSource = members;
                repeaterMembers.DataBind();

                //
                // Membership approval
                //
                switch (group.JoinRestriction.ToLower())
                {
                    case "approvalrequired":
                        rbMembershipApprovalJoinApproval.Checked = true;
                        break;
                    case "closed":
                        rbMembershipApprovalJoinClosed.Checked = true;
                        break;
                    default:
                        rbMembershipApprovalJoinOpen.Checked = true;
                        break;
                }

                switch (group.DepartRestriction.ToLower())
                {
                    case "closed":
                        rbMembershipApprovalLeaveClosed.Checked = true;
                        break;
                    default:
                        rbMembershipApprovalLeaveOpen.Checked = true;
                        break;
                }

                //
                // Delivery Management
                //
                if (group.RequireSenderAuthentication)
                    rbDeliveryManagementInsideOnly.Checked = true;
                else
                    rbDeliveryManagementInsideOutside.Checked = true;

                if (group.WhoCanSendToGroup != null)
                {
                    foreach (ListItem item in lstDeliveryManagementRestrict.Items)
                    {
                        foreach (string s in group.WhoCanSendToGroup)
                        {
                            if (s.IndexOf(item.Value, StringComparison.CurrentCultureIgnoreCase) >= 0)
                                item.Selected = true;
                        }
                    }
                }

                //
                // Message Approval
                //
                if (group.ModerationEnabled)
                    cbMustBeApprovedByAModerator.Checked = true;
                else
                    cbMustBeApprovedByAModerator.Checked = false;

                if (group.GroupModerators != null)
                {
                    foreach (ListItem item in lstGroupModerators.Items)
                    {
                        foreach (string s in group.GroupModerators)
                        {
                            if (s.IndexOf(item.Value, StringComparison.CurrentCultureIgnoreCase) >= 0)
                                item.Selected = true;
                        }
                    }
                }

                if (group.SendersNotRequiringApproval != null)
                {
                    foreach (ListItem item in lstSendersDontRequireApproval.Items)
                    {
                        foreach (string s in group.SendersNotRequiringApproval)
                        {
                            if (s.IndexOf(item.Value, StringComparison.CurrentCultureIgnoreCase) >= 0)
                                item.Selected = true;
                        }
                    }
                }

                //
                // Last section
                //
                switch (group.SendModerationNotifications.ToLower())
                {
                    case "always":
                        rbMessageApprovalNotifyAll.Checked = true;
                        break;
                    case "internal":
                        rbMessageApprovalNotifyInternal.Checked = true;
                        break;
                    default:
                        rbMessageApprovalNotifyNone.Checked = true;
                        break;
                }

                // Show and hide correct panels
                panelGroupDelete.Visible = false;
                panelGroupList.Visible = false;
                panelNewEditGroup.Visible = true;
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Error getting distribution group: " + ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();
            }
        }
        /// <summary>
        /// Enables public folders for a company
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEnablePublicFolders_Click(object sender, EventArgs e)
        {
            ADGroups groups = null;
            ExchCmds powershell = null;

            try
            {
                // Initialize
                groups = new ADGroups(Config.Username, Config.Password, Config.PrimaryDC);
                powershell = new ExchCmds(Config.ExchangeURI, Config.Username, Config.Password, Config.ExchangeConnectionType, Config.PrimaryDC);

                // Get company code
                string companyCodeWithSpaces = CPContext.SelectedCompanyCode;
                string companyCodeWithoutSpaces = companyCodeWithSpaces.Replace(" ", string.Empty);

                // Create groups
                groups.Create(Retrieve.GetCompanyExchangeOU, "PublicFolderAdmins@" + companyCodeWithoutSpaces, "Public Folder Administrators", true, ADGroups.GroupType.Universal, false);
                groups.Create(Retrieve.GetCompanyExchangeOU, "PublicFolderUsers@" + companyCodeWithoutSpaces, "Public Folder Users", true, ADGroups.GroupType.Universal, false);

                // Modify membership
                groups.ModifyMembership("PublicFolderAdmins@" + companyCodeWithoutSpaces, "Admins@" + companyCodeWithoutSpaces, System.DirectoryServices.AccountManagement.IdentityType.Name,
                     System.DirectoryServices.AccountManagement.IdentityType.Name, false, false);
                groups.ModifyMembership("PublicFolderUsers@" + companyCodeWithoutSpaces, "AllUsers@" + companyCodeWithoutSpaces, System.DirectoryServices.AccountManagement.IdentityType.Name,
                     System.DirectoryServices.AccountManagement.IdentityType.Name, false, false);

                // Enable security groups as distribution groups so we can add to public folders
                powershell.Enable_DistributionGroup(companyCodeWithoutSpaces, "PublicFolderAdmins@" + companyCodeWithoutSpaces, true);
                powershell.Enable_DistributionGroup(companyCodeWithoutSpaces, "PublicFolderUsers@" + companyCodeWithoutSpaces, true);

                // Create public folder
                powershell.New_PublicFolder(companyCodeWithSpaces);

                // Remove the default permissions
                powershell.Remove_PublicFolderDefaultPermissions(companyCodeWithSpaces, Config.ExchangeVersion);

                // Add permissions
                powershell.Add_PublicFolderClientPermission(companyCodeWithSpaces);

                // Update the database
                SQLPublicFolders.Update_PublicFolderForCompany(companyCodeWithSpaces, true);

                // Set new view
                panelDisablePublicFolders.Visible = false;
                panelEnablePublicFolders.Visible = false;
                panelEditPublicFolders.Visible = true;

                // Get public folders
                GetPublicFolders();
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Could not enable public folders: " + ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                if (groups != null)
                    groups.Dispose();
            }
        }
        /// <summary>
        /// Deletes the group from Exchange and SQL where from the panel that asks the user if they are sure they want to delete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeleteYes_Click(object sender, EventArgs e)
        {
            ExchCmds powershell = null;

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

                // Delete group from Exchange
                powershell.Remove_DistributionGroup(hfDeleteDistributionGroup.Value);

                // Remove from SQL
                SQLExchange.RemoveGroup(hfDeleteDistributionGroup.Value);

                // Update notification
                notification1.SetMessage(controls.notification.MessageType.Success, Resources.LocalizedText.NotificationSuccessDeleteGroup);
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, ex.Message);
            }
            finally
            {
                // Refresh to the main distribution group list panel
                GetDistributionGroups();
            }
        }
        private void CreateNewPolicy()
        {
            ExchCmds powershell = null;

            try
            {
                BaseActivesyncPolicy policy = new BaseActivesyncPolicy();

                // Compile list of general settings
                policy.DisplayName = txtDisplayName.Text;
                policy.Description = txtDescription.Text;

                // Compile list of basic settings
                policy.AllowBluetooth = ddlAllowBluetooth.SelectedValue;
                policy.AllowBrowser = cbAllowBrowser.Checked;
                policy.AllowCamera = cbAllowCamera.Checked;
                policy.AllowConsumerEmail = cbAllowConsumerMail.Checked;
                policy.AllowDesktopSync = cbAllowDesktopSync.Checked;
                policy.AllowInternetSharing = cbAllowInternetSharing.Checked;
                policy.AllowSimpleDevicePassword = cbAllowSimplePassword.Checked;
                policy.AllowTextMessaging = cbAllowTextMessaging.Checked;
                policy.AllowWiFi = cbAllowWIFI.Checked;
                policy.DevicePasswordEnabled = cbPasswordEnabled.Checked;
                policy.AlphanumericDevicePasswordRequired = cbAlphanumericPwdRequired.Checked;
                policy.MaxDevicePasswordFailedAttempts = ddlMaxFailedPasswordAttempts.SelectedValue;
                policy.AllowHTMLEmail = cbAllowHTMLEmail.Checked;
                policy.AllowIrDA = cbAllowInfrared.Checked;
                policy.AllowNonProvisionableDevice = cbAllowNonProvisionable.Checked;
                policy.AllowPOPIMAPEmail = cbAllowPOPIMAP.Checked;
                policy.AllowRemoteDesktop = cbAllowRemoteDesktop.Checked;
                policy.AllowSMIMEEncryptionAlgorithmNegotiation = ddlAllowSMIMEEncryptionAlgorithmNeg.SelectedValue;
                policy.AllowSMIMESoftCerts = cbAllowSMIME.Checked;
                policy.AllowStorageCard = cbAllowStorageCard.Checked;
                policy.AllowUnsignedApplications = cbAllowUnsignedApps.Checked;
                policy.AllowUnsignedInstallationPackages = cbAllowUnsignedInstallPackages.Checked;
                policy.AttachmentsEnabled = cbAttachmentsEnabled.Checked;
                policy.DeviceEncryptionEnabled = cbDeviceEncryptionEnabled.Checked;
                policy.DevicePasswordExpiration = txtPasswordExpiration.Text;
                policy.DevicePolicyRefreshInterval = txtPolicyRefreshInterval.Text;
                policy.MaxAttachmentSize = txtMaxAttachmentSize.Text;
                policy.MaxCalendarAgeFilter = ddlMaxCalendarAgeFilter.SelectedValue;
                policy.MaxEmailAgeFilter = ddlMaxEmailAgeFilter.SelectedValue;
                policy.PasswordRecoveryEnabled = cbPasswordRecovery.Checked;
                policy.RequireDeviceEncryption = cbRequireDeviceEncryption.Checked;
                policy.RequireEncryptedSMIMEMessages = cbRequireEncryptedSMIMEMsg.Checked;
                policy.RequireEncryptionSMIMEAlgorithm = ddlRequireEncryptedSMIMEAlgorithm.SelectedValue;
                policy.RequireSignedSMIMEMessages = cbRequireSignedSMIMEMsg.Checked;
                policy.RequireSignedSMIMEAlgorithm = ddlRequireSignedSMIMEMsg.SelectedValue;
                policy.RequireManualSyncWhenRoaming = cbRequireManualSyncRoaming.Checked;
                policy.RequireStorageCardEncryption = cbRequireStorageCardEncryption.Checked;

                policy.MaxEmailHTMLBodyTruncationSize = txtMaxHTMLBodyTruncSize.Text;
                policy.MaxEmailBodyTruncationSize = txtMaxEmailBodyTruncSize.Text;

                int minComplexChar = 0;
                int.TryParse(txtMinPwdComplexChar.Text, out minComplexChar);
                policy.MinDevicePasswordComplexCharacters = minComplexChar;
                
                int inactivityLock = 0;
                int.TryParse(txtMaxInactivityLock.Text, out inactivityLock);
                policy.MaxInactivityTimeDeviceLock = inactivityLock;

                int passwordHistory = 0;
                int.TryParse(txtPasswordHistory.Text, out passwordHistory);
                policy.DevicePasswordHistory = passwordHistory;

                int minPwdLength = 0;
                int.TryParse(txtMinPwdLength.Text, out minPwdLength);
                policy.MinDevicePasswordLength = minPwdLength;

                // Exchange 2013
                policy.AllowApplePushNotifications = cbAllowApplePushNotifications.Checked;

                // Initilaze powershell
                powershell = new ExchCmds(Retrieve.ExchangeUri, Retrieve.Username, Retrieve.Password, Retrieve.ExchangeKerberos, Retrieve.PrimaryDC);

                // Insert into Exchange
                powershell.New_ActiveSyncPolicy(policy, CPContext.SelectedCompanyCode, Retrieve.ExchangeVersion);

                // Insert into SQL
                SQLExchange.AddExchangeActiveSyncPolicy(CPContext.SelectedCompanyCode, txtDisplayName.Text, txtDescription.Text);

                // Notify
                notification1.SetMessage(controls.notification.MessageType.Success, "Successfully added new activesync policy");
            }
            catch (Exception ex)
            {
                notification1.SetMessage(controls.notification.MessageType.Error, "Error creating activesync policy: " + ex.Message);
            }
            finally
            {
                if (powershell != null)
                    powershell.Dispose();

                // Refresh view
                GetPolicies();
            }
        }