private async void _timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop();

            DlGroupMigrationViewModel.Instance.IsAliasValid = false;

            if (string.IsNullOrWhiteSpace(TxtGroupAlias.Text)) return;

            var credManager = new CredentialManager();
            var credentials = credManager.GetUserCredentials();

            if (credentials != null)
            {
                var aliasIsValid = await ValidateAlias(credentials, TxtGroupAlias.Text);

                if (aliasIsValid)
                {
                    DlGroupMigrationViewModel.Instance.IsAliasValid = true;
                }
            }
            else
            {
                ModernDialog.ShowMessage(
                    "There are no user credentials provided. Open SETTINGS and add your credentials.", "Hummingbird",
                    MessageBoxButton.OK);
            }
        }
        protected override void OnInitialized(EventArgs e)
        {
            var credManager = new CredentialManager();
            var credentials = credManager.GetUserCredentials();

            if (credentials != null)
            {
                TxtUsername.Text = credentials.Username;
                TxtPassword.Password = credentials.Password;
            }

            base.OnInitialized(e);
        }
        private void btnSaveCredentials_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TxtUsername.Text) && !string.IsNullOrWhiteSpace(TxtPassword.Password))
            {
                var credManager = new CredentialManager();
                var credentialsStored = credManager.StoreUserCredentials(TxtUsername.Text, TxtPassword.Password);

                ModernDialog.ShowMessage(
                    !credentialsStored
                        ? "We couldn't store your credentials at this time."
                        : "Credentials stored successfully.", "Hummingbird", MessageBoxButton.OK);
            }
            else
            {
                ModernDialog.ShowMessage("Both the username and the password are required.", "Hummingbird",
                    MessageBoxButton.OK);
            }
        }
        private async void btnCreateBackup_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TxtDlAlias.Text))
            {
                var credManager = new CredentialManager();
                var userCredentials = credManager.GetUserCredentials();

                if (userCredentials != null)
                {
                    // Disabling pieces of UI that might interfere.
                    DlGroupMigrationViewModel.Instance.BackupControlsEnabled = false;
                    DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = false;

                    TxtBackupStatus.Text = "Identifying alias...";

                    var adConnector = new ActiveDirectoryConnector();
                    var dl = new DistributionList {Name = TxtDlAlias.Text};
                    var owner = string.Empty;
                    bool isValidDl;
                    if (!AccountSettingsViewModel.Instance.IsInternal)
                    {
                        // The user is external.
                        var connector = new ExchangeConnector();
                        owner = connector.GetExternalDistributionListOwner(TxtDlAlias.Text, userCredentials, out isValidDl);
                    }
                    else
                    {
                        // The user is internal
                        var dlDetails = await adConnector.GetDistributionListOwner(TxtDlAlias.Text);
                        owner = dlDetails.Item1;
                        isValidDl = dlDetails.Item2;
                    }

                    bool resolveMembers = !string.IsNullOrWhiteSpace(owner);

                    if (!isValidDl)
                    {
                        var result =
                            ModernDialog.ShowMessage(
                                "The alias you provided doesn't map to a valid DL.",
                                "Hummingbird", MessageBoxButton.OK);
                        resolveMembers = false;
                    }
                    else if (!resolveMembers)
                    {
                        var result =
                            ModernDialog.ShowMessage(
                                "The group owner couldn't be found. If you attempt to retrieve members for the group, the backup will be missing the Owner property. Continue?",
                                "Hummingbird", MessageBoxButton.YesNo);
                        resolveMembers = result == MessageBoxResult.Yes;
                    }

                    if (resolveMembers)
                    {
                        dl.Owner = owner;

                        TxtBackupStatus.Text = "getting members...";

                        var members = await adConnector.GetDistributionListMembers(TxtDlAlias.Text);
                        if (members != null)
                        {
                            dl.Members = members;

                            var fsOperator = new FileSystemOperator();
                            var filePath = fsOperator.StoreDistributionListInformation(dl);

                            if (!string.IsNullOrWhiteSpace(filePath))
                            {
                                var result =
                                    ModernDialog.ShowMessage(
                                        "A backup was created for the distribution list. Do you want to open File Explorer to find its location?",
                                        "Hummingbird", MessageBoxButton.YesNo);

                                if (result == MessageBoxResult.Yes)
                                {
                                    Process.Start("explorer.exe", string.Concat("/select, ", filePath));
                                }
                            }
                            else
                            {
                                ModernDialog.ShowMessage(
                                    "We couldn't create a backup file for this distribution list. Please try again.", "Hummingbird",
                                    MessageBoxButton.OK);
                            }
                        }
                        else
                        {
                            ModernDialog.ShowMessage(
                                "We couldn't retrieve members of the distribution list. Check your credentials and try again.", "Hummingbird",
                                MessageBoxButton.OK);
                        }
                    }

                    // Re-enable the pieces of UI that might interfere.
                    DlGroupMigrationViewModel.Instance.BackupControlsEnabled = true;
                    DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = true;
                }
                else
                {
                    ModernDialog.ShowMessage(
                        "No credentials were provided. Open Settings and add your credentials.", "Hummingbird",
                        MessageBoxButton.OK);
                }
            }
            else
            {
                ModernDialog.ShowMessage("You must include an alias.", "Hummingbird", MessageBoxButton.OK);
            }
        }
        private async void BtnTest_Click(object sender, RoutedEventArgs e)
        {
            var credManager = new CredentialManager();
            var creds = credManager.GetUserCredentials();

            IExchangeResponse result = null;

            await Task.Run(() =>
            {
                var connector = new ExchangeConnector();

                result = connector.PerformExchangeRequest(creds,
                    AccountSettingsViewModel.Instance.ServerUrl, string.Empty, ExchangeRequestType.DeleteGroup, null);
            });
        }
        private async void BtnCreateGroup_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TxtGroupAlias.Text))
            {
                if (DlGroupMigrationViewModel.Instance.IsAliasValid)
                {
                    var credManager = new CredentialManager();
                    var credentials = credManager.GetUserCredentials();

                    if (credentials != null)
                    {
                        if (DlGroupMigrationViewModel.Instance.CurrentlyActiveDl == null ||
                            DlGroupMigrationViewModel.Instance.CurrentlyActiveDl.Members.Count == 0)
                        {
                            var dialogResult =
                                ModernDialog.ShowMessage("This will just create a group with no members. Proceed?",
                                    "Hummingbird", MessageBoxButton.YesNo);

                            if (dialogResult == MessageBoxResult.Yes)
                            {
                                DlGroupMigrationViewModel.Instance.BackupControlsEnabled = false;
                                DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = false;
                                TxtBackupStatus.Text = "creating group...";

                                var groupCreated = await CreateGroup(credentials, TxtGroupAlias.Text, DlGroupMigrationViewModel.Instance.CurrentlyActiveDl.Owner);

                                if (!string.IsNullOrWhiteSpace(groupCreated))
                                {
                                    ModernDialog.ShowMessage(string.Format("Your group was created successfully. SMTP address: {0}", groupCreated), "Hummingbird",
                                        MessageBoxButton.OK);
                                }

                                DlGroupMigrationViewModel.Instance.BackupControlsEnabled = true;
                                DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = true;
                            }
                        }
                        else
                        {
                            DlGroupMigrationViewModel.Instance.BackupControlsEnabled = false;
                            DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = false;
                            TxtBackupStatus.Text = "creating group...";
                            bool operationFailed = false;
                            List<string> invalidMembers = new List<string>();

                            var groupCreated = await CreateGroup(credentials, TxtGroupAlias.Text, DlGroupMigrationViewModel.Instance.CurrentlyActiveDl.Owner);

                            if (string.IsNullOrEmpty(groupCreated))
                            {
                                operationFailed = true;
                                ModernDialog.ShowMessage(string.Format("The group couldn't be created. Please try migrating again later."), "Hummingbird",
                                                MessageBoxButton.OK);
                            }
                            else
                            {
                                TxtBackupStatus.Text = "adding members...";
                                Collection<string> members = DlGroupMigrationViewModel.Instance.CurrentlyActiveDl.Members;

                                for (int i = 0; i < members.Count; i += DlGroupMigrationMain.MemberAddBatchSize)
                                {
                                    IEnumerable<string> membersToAddInABatch = members.Skip(i).Take(DlGroupMigrationMain.MemberAddBatchSize);
                                    var membersAddedResponse = await AddMembersToGroup(credentials, groupCreated, membersToAddInABatch);

                                    if (membersAddedResponse != null && membersAddedResponse.Body.SetUnifiedGroupMembershipResponseMessage != null)
                                    {
                                        if (membersAddedResponse.Body.SetUnifiedGroupMembershipResponseMessage.ResponseCode.ToLower() == "noerror")
                                        {
                                            continue;
                                        }
                                        else if (membersAddedResponse.Body.SetUnifiedGroupMembershipResponseMessage.ResponseCode.ToLower() == "errorinvalidid" &&
                                            membersAddedResponse.Body.SetUnifiedGroupMembershipResponseMessage.FailedMembers.Count == 0)
                                        {
                                            invalidMembers.AddRange(membersAddedResponse.Body.SetUnifiedGroupMembershipResponseMessage.InvalidMembers);
                                            continue;
                                        }
                                        else
                                        {
                                            operationFailed = true;
                                        }
                                    }
                                    else
                                    {
                                        operationFailed = true;
                                    }

                                    if (operationFailed)
                                    {
                                        ModernDialog.ShowMessage(string.Format(@"The group was created, but not all the members were added. Please go to 'bulk add' to add the missing members using the original backup and the following group address {0}.", groupCreated), "Hummingbird",
                                            MessageBoxButton.OK);
                                        break;
                                    }
                                }
                            }

                            if (!operationFailed)
                            {
                                if (invalidMembers.Count == 0)
                                {
                                    ModernDialog.ShowMessage(string.Format("Your group was created successfully. SMTP address: {0}.", groupCreated), "Hummingbird",
                                                MessageBoxButton.OK);
                                }
                                else
                                {
                                    ModernDialog.ShowMessage("The group was created but invalid members weren't added.", "Hummingbird",
                                                MessageBoxButton.OK);

                                    var fsOperator = new FileSystemOperator();
                                    AddMembersErrorDetails error = new AddMembersErrorDetails();
                                    error.InvalidMembers = invalidMembers;
                                    var filePath = fsOperator.StoreDistributionListFailures(DlGroupMigrationViewModel.Instance.CurrentlyActiveDl, "Create", error);

                                    if (!string.IsNullOrWhiteSpace(filePath))
                                    {
                                        var result =
                                            ModernDialog.ShowMessage(
                                                "The list of invalid members was created. Do you want to open File Explorer to find its location?",
                                                "Hummingbird", MessageBoxButton.YesNo);

                                        if (result == MessageBoxResult.Yes)
                                        {
                                            Process.Start("explorer.exe", string.Concat("/select, ", filePath));
                                        }
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(groupCreated))
                            {
                                var fsOperator = new FileSystemOperator();
                                DlToGroupMapping mapping = new DlToGroupMapping();
                                mapping.GroupSMTPAddress = groupCreated;
                                mapping.DlAlias = this.aliasOfSelectedDl;
                                fsOperator.StoreGroupDetails(mapping);
                            }

                            DlGroupMigrationViewModel.Instance.BackupControlsEnabled = true;
                            DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = true;
                        }
                    }
                    else
                    {
                        ModernDialog.ShowMessage("No credentials were provided. Open Settings and add your credentials.", "Hummingbird",
                            MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("The group couldn't be created from the backup file. The alias may be invalid or there might be a problem connecting to the server. Please try again later.",
                        "Hummingbird",
                         MessageBoxButton.OK);
                }
            }
            else
            {
                ModernDialog.ShowMessage("You must include an alias.", "Hummingbird", MessageBoxButton.OK);
            }

            DlGroupMigrationViewModel.Instance.CurrentlyActiveDl = null;
            DlGroupMigrationViewModel.Instance.IsAliasValid = false;
            TxtPath.Text = string.Empty;
        }
        private async void BtnAddMembers_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TxtPath.Text) && !string.IsNullOrWhiteSpace(TxtGroupAddress.Text))
            {
                DlGroupMigrationViewModel.Instance.BulkAddControlsEnabled = false;

                try
                {
                    var credManager = new CredentialManager();
                    var credentials = credManager.GetUserCredentials();

                    BulkAddMembersResult[] addMembersResults = await AddMembersToGroup(credentials, TxtGroupAddress.Text,
                        DlGroupMigrationViewModel.Instance.BulkAddDistributionList.Members.ToList());
                    DlGroupMigrationViewModel.Instance.BulkAddDistributionList.Name = TxtGroupAddress.Text;

                    int totalMembersCount = DlGroupMigrationViewModel.Instance.BulkAddDistributionList.Members.Count;
                    int failedMemberCount = addMembersResults.Where(r => r.FailedMembers != null).Sum(r => r.FailedMembers.Count);
                    int invalidMemberCount = addMembersResults.Where(r => r.InvalidMembers != null).Sum(r => r.InvalidMembers.Count);
                    int successfulMembersCount = totalMembersCount - (invalidMemberCount + failedMemberCount);

                    if (addMembersResults.All(x => x.StatusCode.ToLower() == "noerror"))
                    {
                        string message = string.Format("The bulk add was successful. {0} members were added.", totalMembersCount);

                        ModernDialog.ShowMessage(
                            message,
                            "Hummingbird",
                            MessageBoxButton.OK);

                        TxtGroupAddress.Text = string.Empty;
                        TxtPath.Text = string.Empty;
                        DlGroupMigrationViewModel.Instance.BulkAddDistributionList = new DistributionList();
                    }
                    else
                    {
                        StringBuilder message = new StringBuilder();

                        if (successfulMembersCount > 0)
                        {
                            message.Append("The bulk add was partially successful.");
                            message.Append(string.Format("\nNumber of members added successfully: {0}.", successfulMembersCount));
                        }

                        if (failedMemberCount > 0)
                        {
                            message.Append(string.Format("\nNumber of members not added: {0}.", failedMemberCount));
                        }

                        if (invalidMemberCount > 0)
                        {
                            message.Append(string.Format("\nNumber of invalid members: {0}.", invalidMemberCount));
                        }

                        ModernDialog.ShowMessage(
                            message.ToString(),
                            "Hummingbird",
                            MessageBoxButton.OK);

                        var fsOperator = new FileSystemOperator();
                        AddMembersErrorDetails error = new AddMembersErrorDetails
                        {
                            FailedMembers = new List<string>(),
                            InvalidMembers = new List<string>()
                        };
                        foreach (var list in addMembersResults)
                        {
                            if (list.FailedMembers != null) { error.FailedMembers.AddRange(list.FailedMembers); }
                            if (list.InvalidMembers != null) { error.InvalidMembers.AddRange(list.InvalidMembers); }
                        }

                        var filePath = fsOperator.StoreDistributionListFailures(DlGroupMigrationViewModel.Instance.BulkAddDistributionList, "BulkAdd", error);

                        if (!string.IsNullOrWhiteSpace(filePath))
                        {
                            var result =
                                ModernDialog.ShowMessage(
                                    "A list of failures was created. Do you want to open File Explorer to find its location?",
                                    "Hummingbird", MessageBoxButton.YesNo);

                            if (result == MessageBoxResult.Yes)
                            {
                                Process.Start("explorer.exe", string.Concat("/select, ", filePath));
                            }
                        }

                    }

                }
                catch (Exception)
                {
                    ModernDialog.ShowMessage(
                        "Members couldn't be added from the backup file. The alias may be invalid or there might be a problem connecting to the server. Please try again later.",
                        "Hummingbird",
                        MessageBoxButton.OK);
                }
            }
            else
            {
                ModernDialog.ShowMessage(
                    "Make sure you've added both the DL backup file name and the group address (SMTP address).",
                    "Hummingbird", MessageBoxButton.OK);
            }

            DlGroupMigrationViewModel.Instance.BulkAddControlsEnabled = true;
        }
        private async void BtnPerformGroupGrab_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TxtBackupGroupBox.Text))
            {
                DlGroupMigrationViewModel.Instance.BulkAddControlsEnabled = false;

                try
                {
                    var credManager = new CredentialManager();
                    var credentials = credManager.GetUserCredentials();

                    var gugResults = await GetGroupInformation(credentials, TxtBackupGroupBox.Text);

                    GetUnifiedGroupEnvelope gugEnvelope = (GetUnifiedGroupEnvelope) gugResults;

                    GroupSimplifier simplifier = new GroupSimplifier();
                    var dl =
                        simplifier.SimplifyGroup(gugEnvelope.Body.GetUnifiedGroupMembersResponseMessage.MembersInfo.Members,
                            TxtBackupGroupBox.Text);

                    var fsOperator = new FileSystemOperator();
                    var filePath = fsOperator.StoreDistributionListInformation(dl);

                    if (!string.IsNullOrWhiteSpace(filePath))
                    {
                        var result =
                            ModernDialog.ShowMessage(
                                "Group backup created. Open Windows Explorer for its location?",
                                "Hummingbird", MessageBoxButton.YesNo);

                        if (result == MessageBoxResult.Yes)
                        {
                            Process.Start("explorer.exe", string.Concat("/select, ", filePath));
                        }
                    }
                    else
                    {
                        ModernDialog.ShowMessage(
                            "We couldn't create the backup file for this group.", "Hummingbird",
                            MessageBoxButton.OK);
                    }
                    //if (membersAdded.ToLower() == "noerror")
                    //{
                    //    ModernDialog.ShowMessage("Bulk add complete!", "Hummingbird",
                    //        MessageBoxButton.OK);

                    //    TxtGroupAddress.Text = string.Empty;
                    //    TxtPath.Text = string.Empty;
                    //    DlGroupMigrationViewModel.Instance.BulkAddDistributionList = new DistributionList();
                    //}
                }
                catch (Exception ex)
                {
                    ModernDialog.ShowMessage(
                        "An error occured and we couldn't complete the request. Please contact the developer.",
                        "Hummingbird",
                        MessageBoxButton.OK);
                }
            }
            else
            {
                ModernDialog.ShowMessage(
                    "Missing key pieces of information. Check that you have both the members and group address entered.",
                    "Hummingbird", MessageBoxButton.OK);
            }

            DlGroupMigrationViewModel.Instance.BulkAddControlsEnabled = true;
        }