/// <summary>
        /// Stores the DL invalid members info in a local file.
        /// </summary>
        /// <param name="distributionList">Existing distribution list model.</param>
        /// <param name="actionName">Name of the flow attempting to write a failure list</param>
        /// <param name="errorDetails">Add Members details to be written</param>
        /// <returns></returns>
        internal string StoreDistributionListFailures(DistributionList distributionList, string actionName, AddMembersErrorDetails errorDetails)
        {
            string path;

            try
            {
                var directory = Directory.CreateDirectory(AppPath);

                var serializer = new XmlSerializer(typeof(AddMembersErrorDetails));
                path = Path.Combine(directory.FullName, distributionList.Name + "_" + actionName + "_Failures.xmldl");

                using (var writer = new StreamWriter(path))
                {
                    serializer.Serialize(writer, errorDetails);
                }

                LoggingViewModel.Instance.Logger.Write(string.Concat("StoreDistributionListInvalidMembers:OK ", path,
                    Environment.NewLine,
                    distributionList.Name));
            }
            catch (Exception exception)
            {
                LoggingViewModel.Instance.Logger.Write(string.Concat("StoreDistributionListInvalidMembers:Error ",
                    exception.Message, Environment.NewLine,
                    exception.StackTrace,
                    Environment.NewLine,
                    distributionList.Name));

                path = string.Empty;
            }

            return path;
        }
        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;
        }