Exemplo n.º 1
0
        public static void SetFolderPermissions(string mailbox, string folder, string user, string accessRights)
        {
            PSCommand commands = new PSCommand();

            if (folder == "\\Top of Information Store")
            {
                folder = "\\";
            }
            string folderPath = mailbox + ":" + folder;

            commands.AddCommand("Set-MailboxFolderPermission");
            commands.AddParameter("Identity", folderPath);
            commands.AddParameter("User", user);
            commands.AddParameter("AccessRights", accessRights);
            Collection <PSObject> result1 = runPowershellCommands(commands);

            if (result1.Count == 0)
            {
                commands.Clear();
                commands.AddCommand("Add-MailboxFolderPermission");
                commands.AddParameter("Identity", folderPath);
                commands.AddParameter("User", user);
                commands.AddParameter("AccessRights", accessRights);
                Collection <PSObject> result2 = runPowershellCommands(commands);
            }
        }
Exemplo n.º 2
0
        public static void RemoveAllFolderPermissions(string mailbox, string folder)
        {
            PSCommand commands = new PSCommand();

            if (folder == "\\Top of Information Store")
            {
                folder = "\\";
            }
            string                folderPath         = mailbox + ":" + folder;
            SwitchParameter       noConfirm          = new SwitchParameter();
            Collection <PSObject> currentPermissions = GetFolderPermissions(mailbox, folder);

            foreach (PSObject permission in currentPermissions)
            {
                if (permission.Properties["User"].Value.ToString() != "Default" && permission.Properties["User"].Value.ToString() != "Anonymous")
                {
                    commands.Clear();
                    commands.AddCommand("Remove-MailboxFolderPermission");
                    commands.AddParameter("Identity", folderPath);
                    commands.AddParameter("User", permission.Properties["User"].Value.ToString());
                    commands.AddParameter("Confirm", noConfirm);
                    runPowershellCommands(commands);
                }
            }
        }
Exemplo n.º 3
0
        // Token: 0x06000F17 RID: 3863 RVA: 0x0005A154 File Offset: 0x00058354
        public static Unlimited <ByteQuantifiedSize> GetMailboxQuota(IPublicFolderMailboxLoggerBase logger, IAssistantRunspaceFactory powershellFactory, Guid mailboxGuid, OrganizationId organizationId, ISplitOperationState splitOperationState)
        {
            ADObjectId mailboxDatabase                  = null;
            bool       useDatabaseQuotaDefaults         = false;
            Unlimited <ByteQuantifiedSize> mailboxQuota = Unlimited <ByteQuantifiedSize> .UnlimitedValue;
            string    value     = string.Format("{0}\\{1}", organizationId.OrganizationalUnit.Name, mailboxGuid.ToString());
            PSCommand psCommand = new PSCommand();

            psCommand.AddCommand("Get-Mailbox");
            psCommand.AddParameter("PublicFolder");
            psCommand.AddParameter("Identity", value);
            Mailbox publicFolderMailbox = null;

            PublicFolderSplitHelper.PowerShellExceptionHandler(delegate(out string originOfException, out ErrorRecord error)
            {
                error             = null;
                originOfException = "GetMailboxQuota - RunPSCommand: Get-Mailbox -PublicFolder";
                IAssistantRunspaceProxy assistantRunspaceProxy = powershellFactory.CreateRunspaceForDatacenterAdmin(organizationId);
                publicFolderMailbox = assistantRunspaceProxy.RunPSCommand <Mailbox>(psCommand, out error, logger);
                if (error == null)
                {
                    mailboxQuota                    = publicFolderMailbox.ProhibitSendQuota;
                    useDatabaseQuotaDefaults        = (publicFolderMailbox.UseDatabaseQuotaDefaults ?? false);
                    MailboxDatabase mailboxDatabase = publicFolderMailbox.Database;
                    if (useDatabaseQuotaDefaults && mailboxDatabase != null)
                    {
                        psCommand.Clear();
                        psCommand.AddCommand("Get-MailboxDatabase");
                        psCommand.AddParameter("Identity", mailboxDatabase.Name);
                        originOfException = "GetMailboxQuota - RunPSCommand: Get-MailboxDatabase";
                        mailboxDatabase   = assistantRunspaceProxy.RunPSCommand <MailboxDatabase>(psCommand, out error, logger);
                        if (error == null)
                        {
                            mailboxQuota = mailboxDatabase.ProhibitSendQuota;
                        }
                    }
                }
            }, splitOperationState);
            return(mailboxQuota);
        }
Exemplo n.º 4
0
        public async Task Start(List <KeyValuePair <string, object> > inputParameters)
        {
            IsActiveDebugging = true;

            if (_cachedScriptPath == null)
            {
                CacheRunbook();
            }

            // Set the breakpoints
            var command = new PSCommand();

            if (_setBreakpoints != null)
            {
                command.AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint");
                command.AddCommand(@"Microsoft.PowerShell.Utility\Remove-PSBreakpoint");

                await ExecuteCommand <object>(command);

                command.Clear();
            }

            if (_breakpoints.Count > 0)
            {
                foreach (var bp in _breakpoints)
                {
                    command.AddCommand("Set-PSBreakpoint")
                    .AddParameter("Script", _cachedScriptPath)
                    .AddParameter("Line", bp.Line + 2);
                }
            }

            if (command.Commands.Count > 0)
            {
                _setBreakpoints = await ExecuteCommand <Breakpoint>(command);

                command.Clear();
            }

            var inputArgs = string.Empty;

            foreach (var input in inputParameters)
            {
                if (input.Key.StartsWith("-"))
                {
                    inputArgs += " " + input.Key;
                }
                else
                {
                    inputArgs += " -" + input.Key;
                }

                if (input.Value is string)
                {
                    inputArgs += " \"" + input.Value + "\"";
                }
                else if (input.Value is bool)
                {
                    if (((bool)input.Value) == true)
                    {
                        inputArgs += " $true";
                    }
                    else
                    {
                        inputArgs += " $false";
                    }
                }
                else
                {
                    inputArgs += " " + input.Value;
                }
            }

            command.AddScript(_cachedScriptPath + inputArgs);
            await ExecuteCommand <object>(command, true);

            if (_cachedScriptPath != null)
            {
                File.Delete(_cachedScriptPath);
                _cachedScriptPath = null;
            }

            IsActiveDebugging = false;
            DebuggerFinished?.Invoke(this, new EventArgs());

            Stop();
        }
Exemplo n.º 5
0
        // Нажата кнопка установки автоответа и пересылки сообщений
        private void btSetAutoreplyAndForwarding_Click(object sender, RoutedEventArgs e)
        {
            #region Проверка и инициализация входных данных
            if (!_userIsSelected)
            {
                MessageBox.Show("Не выбран пользователь!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            bool     scheduled = false;
            bool     forward   = false;
            bool     autoreply = false;
            bool     withOutExternalAutoreply = false;
            string   errorMesg             = "";
            string   loginUser             = loginUserForChange.Text;
            DateTime startDateTime         = new DateTime();
            DateTime endDateTime           = new DateTime();
            string   mailAddressForwarding = "";
            string   internalMessageData   = "";
            string   externalMessageData   = "";
            if (setScheduled.IsChecked == true)
            {
                scheduled     = true;
                startDateTime = new DateTime(
                    startDate.SelectedDate.Value.Year,
                    startDate.SelectedDate.Value.Month,
                    startDate.SelectedDate.Value.Day,
                    TimeSpan.Parse(startTime.SelectedItem.ToString() + ":00").Hours,
                    TimeSpan.Parse(startTime.SelectedItem.ToString() + ":00").Minutes,
                    TimeSpan.Parse(startTime.SelectedItem.ToString() + ":00").Seconds);
                endDateTime = new DateTime(
                    endDate.SelectedDate.Value.Year,
                    endDate.SelectedDate.Value.Month,
                    endDate.SelectedDate.Value.Day,
                    TimeSpan.Parse(endTime.SelectedItem.ToString() + ":00").Hours,
                    TimeSpan.Parse(endTime.SelectedItem.ToString() + ":00").Minutes,
                    TimeSpan.Parse(endTime.SelectedItem.ToString() + ":00").Seconds);
                if (startDateTime >= endDateTime)
                {
                    MessageBox.Show("Дата и время начала периода автоответа не могут быть больше или равны конечной дате и времени!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
            if (!string.IsNullOrWhiteSpace(internalMessage.Text))
            {
                internalMessageData = internalMessage.Text.Trim().Replace("\r\n", "<br>");
                externalMessageData = externalMessage.Text.Trim().Replace("\r\n", "<br>");
                autoreply           = true;
                if (string.IsNullOrWhiteSpace(externalMessage.Text))
                {
                    withOutExternalAutoreply = true;
                }
            }
            if (setForward.IsChecked == true)
            {
                forward = true;
                if (!_forwardingMailIsSelected)
                {
                    MessageBox.Show("Не указан эл.адрес для пересылки сообщений!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                mailAddressForwarding = mailForwarding.Text;
            }
            if (string.IsNullOrWhiteSpace(_pathToConfig))
            {
                MessageBox.Show("Отсутствует конфигурационный файл плагина!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (!autoreply && !forward)
            {
                MessageBox.Show("Не указаны параметры для установки автоответа или пересылки!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            #endregion

            if (autoreply || forward)
            {
                Thread t = new Thread(() =>
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _processRun.Clear();
                        _processRun.Add(new ProcessRunData {
                            Text = "---- Установка автоответа и переадресации пользователю " + loginUser + " ----"
                        });
                        isEnableForm(false);
                    }));

                    #region Чтение конфигурационного файла плагина
                    ProcessRunData itemProcess = new ProcessRunData {
                        Text = "Чтение конфигурационного файла плагина..."
                    };
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _processRun.Add(new ProcessRunData {
                            Text = "Чтение конфигурационного файла плагина..."
                        });
                        itemProcess = _processRun[_processRun.Count - 1];
                    }));
                    configData = GetConfigData(_pathToConfig, ref errorMesg);
                    if (!string.IsNullOrWhiteSpace(errorMesg))
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text  = "Ошибка чтения конфигурационного файла:\r\n" + errorMesg;
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (!configData.ContainsKey("mailserver"))
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text  = "Отсутсвуют требуемые параметры в конфигурационном файле!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Чтение конфигурационного файла плагина";
                    }));
                    #endregion

                    //============================================================
                    PSCredential credential                = new PSCredential(_login, _password);
                    WSManConnectionInfo connectionInfo     = new WSManConnectionInfo((new Uri(configData["mailserver"])), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                    Runspace runspace     = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                    PowerShell powershell = PowerShell.Create();
                    PSCommand command     = new PSCommand();
                    //============================================================

                    #region Внесение изменений

                    #region Подключение к Exchange Server
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _processRun.Add(new ProcessRunData {
                            Text = "Подключение к Exchange Server..."
                        });
                        itemProcess = _processRun[_processRun.Count - 1];
                    }));
                    try
                    {
                        runspace.Open();
                        powershell.Runspace = runspace;
                    }
                    catch (Exception exp)
                    {
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text  = "Ошибка подключения к Exchange Server:\r\n" + exp.Message;
                            isEnableForm(true);
                        }));
                        return;
                    }
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Подключение к Exchange Server";
                    }));
                    #endregion

                    if (autoreply)
                    {
                        #region Установка автоответа
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            _processRun.Add(new ProcessRunData {
                                Text = "Установка автоответа..."
                            });
                            itemProcess = _processRun[_processRun.Count - 1];
                        }));
                        try
                        {
                            command.AddCommand("Set-MailboxAutoReplyConfiguration");
                            command.AddParameter("Identity", loginUser);
                            if (scheduled)
                            {
                                command.AddParameter("AutoReplyState", "Scheduled");
                                command.AddParameter("StartTime", startDateTime.ToString("M/dd/yyyy HH:mm:ss").Replace('.', '/'));
                                command.AddParameter("EndTime", endDateTime.ToString("M/dd/yyyy HH:mm:ss").Replace('.', '/'));
                            }
                            else
                            {
                                command.AddParameter("AutoReplyState", "Enabled");
                            }
                            if (withOutExternalAutoreply)
                            {
                                command.AddParameter("ExternalAudience", "None");
                            }
                            else
                            {
                                command.AddParameter("ExternalAudience", "All");
                            }
                            command.AddParameter("ExternalMessage", externalMessageData);
                            command.AddParameter("InternalMessage", internalMessageData);
                            powershell.Commands = command;
                            powershell.Invoke();
                            command.Clear();
                            if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                            {
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    itemProcess.Text = "";
                                }));
                                for (int i = 0; i < powershell.Streams.Error.Count; i++)
                                {
                                    string errorMsg = "Ошибка установки автоответа:\r\n" + powershell.Streams.Error[i].ToString();
                                    Dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                        itemProcess.Text += errorMsg;
                                    }));
                                }
                                runspace.Dispose();
                                runspace = null;
                                powershell.Dispose();
                                powershell = null;
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    isEnableForm(true);
                                }));
                                return;
                            }
                        }
                        catch (Exception exp)
                        {
                            runspace.Dispose();
                            runspace = null;
                            powershell.Dispose();
                            powershell = null;
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text  = "Ошибка установки автоответа:\r\n" + exp.Message;
                                isEnableForm(true);
                            }));
                            return;
                        }
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text  = "Установка автоответа";
                        }));
                        #endregion
                    }

                    if (forward)
                    {
                        #region Проверка адреса пересылки сообщений
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            _processRun.Add(new ProcessRunData {
                                Text = "Проверка адреса пересылки сообщений..."
                            });
                            itemProcess = _processRun[_processRun.Count - 1];
                        }));
                        try
                        {
                            command.AddCommand("Get-Mailbox");
                            command.AddParameter("Identity", mailAddressForwarding);
                            powershell.Commands = command;
                            var result          = powershell.Invoke();
                            command.Clear();
                            if (result.Count <= 0)
                            {
                                runspace.Dispose();
                                runspace = null;
                                powershell.Dispose();
                                powershell = null;
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                    itemProcess.Text += "Ошибка проверки адреса пересылки сообщений:\r\nАдрес пересылки не найден на сервере Exchange!!!";
                                }));
                                return;
                            }
                        }
                        catch (Exception exp)
                        {
                            runspace.Dispose();
                            runspace = null;
                            powershell.Dispose();
                            powershell = null;
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text  = "Ошибка проверки адреса пересылки сообщений:\r\n" + exp.Message;
                                isEnableForm(true);
                            }));
                            return;
                        }
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text  = "Проверка адреса пересылки сообщений";
                        }));
                        #endregion

                        #region Установка пересылки входящих сообщений
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            _processRun.Add(new ProcessRunData {
                                Text = "Установка пересылки входящих сообщений..."
                            });
                            itemProcess = _processRun[_processRun.Count - 1];
                        }));
                        try
                        {
                            command.AddCommand("Set-Mailbox");
                            command.AddParameter("Identity", loginUser);
                            command.AddParameter("DeliverToMailboxAndForward", true);
                            command.AddParameter("ForwardingAddress", mailAddressForwarding);
                            powershell.Commands = command;
                            powershell.Invoke();
                            command.Clear();
                            if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                            {
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    itemProcess.Text = "";
                                }));
                                for (int i = 0; i < powershell.Streams.Error.Count; i++)
                                {
                                    string errorMsg = "Ошибка установки пересылки входящих сообщений:\r\n" + powershell.Streams.Error[i].ToString();
                                    Dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                        itemProcess.Text += errorMsg;
                                    }));
                                }
                                runspace.Dispose();
                                runspace = null;
                                powershell.Dispose();
                                powershell = null;
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    isEnableForm(true);
                                }));
                                return;
                            }
                        }
                        catch (Exception exp)
                        {
                            runspace.Dispose();
                            runspace = null;
                            powershell.Dispose();
                            powershell = null;
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text  = "Ошибка установки пересылки входящих сообщений:\r\n" + exp.Message;
                                isEnableForm(true);
                            }));
                            return;
                        }
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image = new BitmapImage(new Uri(@"/AutoReplyAndForwarding;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text  = "Установка пересылки входящих сообщений";
                        }));
                        #endregion
                    }

                    #endregion

                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    command.Clear();
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _processRun.Add(new ProcessRunData {
                            Text = "---- Процесс завершён! ----"
                        });
                        loginUserForChange.Text            = "";
                        _userIsSelected                    = false;
                        loginUserForChange.FontWeight      = FontWeights.Normal;
                        loginUserForChange.TextDecorations = null;
                        startDate.SelectedDate             = DateTime.Today;
                        endDate.SelectedDate               = DateTime.Today.AddDays(1);
                        startTime.SelectedIndex            = 0;
                        endTime.SelectedIndex              = 0;
                        internalMessage.Text               = "";
                        externalMessage.Text               = "";
                        mailForwarding.Text                = "";
                        _forwardingMailIsSelected          = false;
                        mailForwarding.FontWeight          = FontWeights.Normal;
                        mailForwarding.TextDecorations     = null;
                        setForward.IsChecked               = false;
                        isEnableForm(true);
                    }));
                });
                t.IsBackground = true;
                t.Start();
            }
            else
            {
                if (scheduled)
                {
                    MessageBox.Show("Не указаны сообщения для отправки в пределах и за пределы организации!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show("Не указаны значения для установки!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Exemplo n.º 6
0
        List <TenantOrganizationPresentationObjectWrapper> IOrganizationOperation.GetAllOrganizations(bool checkAllPartitions)
        {
            List <TenantOrganizationPresentationObjectWrapper> result;

            using (AnchorRunspaceProxy anchorRunspaceProxy = AnchorRunspaceProxy.CreateRunspaceForDatacenterAdmin(this.Context, "upgradehandlers"))
            {
                PSCommand pscommand = new PSCommand();
                pscommand.AddCommand("Get-AccountPartition");
                Collection <AccountPartition> collection = null;
                try
                {
                    collection = anchorRunspaceProxy.RunPSCommand <AccountPartition>(pscommand);
                }
                catch (MigrationPermanentException ex)
                {
                    this.Context.Logger.Log(MigrationEventType.Error, "Get-AccountPartition failed: {0}", new object[]
                    {
                        ex
                    });
                    throw;
                }
                pscommand.Clear();
                List <TenantOrganizationPresentationObject> list = new List <TenantOrganizationPresentationObject>();
                if (collection == null || collection.Count == 0)
                {
                    result = null;
                }
                else
                {
                    Collection <AccountPartition> collection2 = new Collection <AccountPartition>();
                    if (!checkAllPartitions)
                    {
                        AccountPartition accountPartition = collection.FirstOrDefault((AccountPartition p) => p.IsLocalForest);
                        if (accountPartition == null)
                        {
                            this.Context.Logger.Log(MigrationEventType.Information, "No LocalForest partitions found", new object[0]);
                            return(null);
                        }
                        collection2.Add(accountPartition);
                        this.Context.Logger.Log(MigrationEventType.Information, "Get-Organization will run on partition: {0} IsLocalPartition: {1}", new object[]
                        {
                            collection2.ElementAt(0).Name,
                            collection2.ElementAt(0).IsLocalForest
                        });
                    }
                    else
                    {
                        collection2 = collection;
                    }
                    foreach (AccountPartition accountPartition2 in collection2)
                    {
                        pscommand.AddCommand("Get-Organization");
                        pscommand.AddParameter("AccountPartition", accountPartition2);
                        pscommand.AddParameter("Filter", "OrganizationStatus -eq 1");
                        Stopwatch stopwatch = Stopwatch.StartNew();
                        Collection <TenantOrganizationPresentationObject> collection3 = new Collection <TenantOrganizationPresentationObject>();
                        try
                        {
                            collection3 = anchorRunspaceProxy.RunPSCommand <TenantOrganizationPresentationObject>(pscommand);
                            this.Context.Logger.Log(MigrationEventType.Information, "Get-Organization ran for partition {0} in: {1}, found {2} orgs.", new object[]
                            {
                                accountPartition2.Name,
                                stopwatch.Elapsed.TotalSeconds,
                                collection3.Count
                            });
                        }
                        catch (MigrationPermanentException ex2)
                        {
                            this.Context.Logger.Log(MigrationEventType.Error, "Get-Organization failed for Partition {0} : {1}", new object[]
                            {
                                accountPartition2.Name,
                                ex2
                            });
                            throw;
                        }
                        List <TenantOrganizationPresentationObject> collection4 = CommonUtils.RandomizeSequence <TenantOrganizationPresentationObject>(collection3.ToList <TenantOrganizationPresentationObject>());
                        list.AddRange(collection4);
                    }
                    List <TenantOrganizationPresentationObjectWrapper> list2 = new List <TenantOrganizationPresentationObjectWrapper>();
                    foreach (TenantOrganizationPresentationObject tenant in list)
                    {
                        list2.Add(new TenantOrganizationPresentationObjectWrapper(tenant));
                    }
                    result = list2;
                }
            }
            return(result);
        }
        // Token: 0x06000B3F RID: 2879 RVA: 0x000316FC File Offset: 0x0002F8FC
        internal void AddWindowsFeature(OsComponent componentId)
        {
            if (componentId >= OsComponent.ComponentMax)
            {
                throw new ArgumentOutOfRangeException();
            }
            string text = OsComponentManager.m_OsComponents[(int)componentId];

            OsComponentManager.Tracer.TraceDebug <string>((long)this.GetHashCode(), "AddWindowsFeature(): Adding the following Windows Feature: {0}.", text);
            Exception ex = null;

            try
            {
                using (PowerShell powerShell = PowerShell.Create())
                {
                    PSCommand pscommand = new PSCommand();
                    if (OsComponentManager.Tracer.IsTraceEnabled(TraceType.DebugTrace))
                    {
                        OsComponentManager.Tracer.TraceDebug((long)this.GetHashCode(), "AddWindowsFeature() Running: PS> Invoke-Expression $env:PSModulePath");
                        this.m_output.WriteVerbose(new LocalizedString("Running PS> Invoke-Expression $env:PSModulePath"));
                        pscommand.Clear();
                        pscommand.AddCommand("Invoke-Expression").AddArgument("$env:PSModulePath");
                        this.RunPSCommand(powerShell, pscommand, true);
                        OsComponentManager.Tracer.TraceDebug((long)this.GetHashCode(), "AddWindowsFeature() Running: PS> Get-Module -ListAvailable -All");
                        this.m_output.WriteVerbose(new LocalizedString("Running PS> Get-Module -ListAvailable -All"));
                        pscommand.Clear();
                        pscommand.AddCommand("Get-Module").AddParameter("ListAvailable", true).AddParameter("All", true);
                        this.RunPSCommand(powerShell, pscommand, true);
                    }
                    OsComponentManager.Tracer.TraceDebug((long)this.GetHashCode(), "AddWindowsFeature() Running: PS> Import-Module -Name ServerManager");
                    this.m_output.WriteVerbose(new LocalizedString("Running PS> Import-Module -Name ServerManager"));
                    pscommand.Clear();
                    pscommand.AddCommand("Import-Module").AddParameter("Name", "ServerManager");
                    this.RunPSCommand(powerShell, pscommand, false);
                    OsComponentManager.Tracer.TraceDebug <string>((long)this.GetHashCode(), "AddWindowsFeature() Running: PS> Add-WindowsFeature -Name {0} -IncludeAllSubFeature", text);
                    this.m_output.WriteVerbose(new LocalizedString(string.Format("Running PS> Add-WindowsFeature -Name {0} -IncludeAllSubFeature", text)));
                    pscommand.Clear();
                    pscommand.AddCommand("Add-WindowsFeature").AddParameter("Name", text).AddParameter("IncludeAllSubFeature", true);
                    Collection <PSObject> collection = this.RunPSCommand(powerShell, pscommand, false);
                    PSObject     psobject            = collection[0];
                    PSMemberInfo psmemberInfo        = psobject.Members["Success"];
                    if (psmemberInfo == null || !(bool)psmemberInfo.Value)
                    {
                        throw new DagTaskComponentManagerServerManagerPSFailure(ReplayStrings.AmBcsNoneSpecified);
                    }
                    PSMemberInfo psmemberInfo2 = psobject.Members["RestartNeeded"];
                    if (psmemberInfo2 == null)
                    {
                        throw new DagTaskComponentManagerServerManagerPSFailure(ReplayStrings.AmBcsNoneSpecified);
                    }
                    if ((int)psmemberInfo2.Value == 0 || (int)psmemberInfo2.Value == 2)
                    {
                        OsComponentManager.Tracer.TraceError((long)this.GetHashCode(), "AddWindowsFeature(): A server reboot may be required!");
                        this.m_output.WriteWarning(ReplayStrings.DagTaskComponentManagerWantsToRebootException);
                    }
                }
            }
            catch (InvalidOperationException ex2)
            {
                ex = ex2;
            }
            catch (ScriptCallDepthException ex3)
            {
                ex = ex3;
            }
            catch (ParameterBindingException ex4)
            {
                ex = ex4;
            }
            catch (CmdletProviderInvocationException ex5)
            {
                ex = ex5;
            }
            catch (CmdletInvocationException ex6)
            {
                ex = ex6;
            }
            catch (ActionPreferenceStopException ex7)
            {
                ex = ex7;
            }
            catch (PipelineStoppedException ex8)
            {
                ex = ex8;
            }
            catch (MetadataException ex9)
            {
                ex = ex9;
            }
            catch (RuntimeException ex10)
            {
                ex = ex10;
            }
            catch (SecurityException ex11)
            {
                ex = ex11;
            }
            if (ex != null)
            {
                throw new DagTaskComponentManagerServerManagerPSFailure(ex.Message, ex);
            }
        }
Exemplo n.º 8
0
        // Нажата кнопка загрузки информации
        private void btLoadInfo_Click(object sender, RoutedEventArgs e)
        {
            #region Проверка и инициализация входных данных
            if (!_userIsSelected)
            {
                MessageBox.Show("Не выбран пользователь!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            loadedData.User = loginUser.Text;
            string errorMesg = "";
            #endregion

            Thread t = new Thread(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    isEnableForm(false);
                }));

                #region Чтение конфигурационного файла плагина
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Чтение конфигурационного файла плагина...";
                }));
                configData = GetConfigData(_pathToConfig, ref errorMesg);
                if (!string.IsNullOrWhiteSpace(errorMesg))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка чтения конфигурационного файла:\r\n" + errorMesg);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                if (!configData.ContainsKey("mailserver"))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Отсутсвуют требуемые параметры в конфигурационном файле!!!");
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                //============================================================
                PSCredential credential                = new PSCredential(_login, _password);
                WSManConnectionInfo connectionInfo     = new WSManConnectionInfo((new Uri(configData["mailserver"])), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                Runspace runspace     = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                PowerShell powershell = PowerShell.Create();
                PSCommand command     = new PSCommand();
                //============================================================

                #region Подключение к Exchange Server
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Подключение к Exchange Server...";
                }));
                try
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка подключения к Exchange Server:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка функций почтового ящика
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка функций почтового ящика...";
                }));
                try
                {
                    string[] loadParam = new string[] { "ActiveSyncEnabled", "ActiveSyncMailboxPolicy", "OWAEnabled", "OwaMailboxPolicy", "MAPIEnabled", "PopEnabled", "ImapEnabled" };
                    command.AddCommand("Get-CASMailbox");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);

                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки функций почтового ящика:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        var cmd = result[0];
                        if (cmd.Properties["ActiveSyncEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableActiveSync = true;
                        }
                        else
                        {
                            loadedData.IsEnableActiveSync = false;
                        }
                        if (cmd.Properties["ActiveSyncMailboxPolicy"].Value != null)
                        {
                            loadedData.PolicyActiveSync = cmd.Properties["ActiveSyncMailboxPolicy"].Value.ToString();
                        }
                        else
                        {
                            loadedData.PolicyActiveSync = "";
                        }
                        if (cmd.Properties["OWAEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableWebApp = true;
                        }
                        else
                        {
                            loadedData.IsEnableWebApp = false;
                        }
                        if (cmd.Properties["OwaMailboxPolicy"].Value != null)
                        {
                            loadedData.PolicyWebApp = cmd.Properties["OwaMailboxPolicy"].Value.ToString();
                        }
                        else
                        {
                            loadedData.PolicyWebApp = "";
                        }
                        if (cmd.Properties["MAPIEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableMAPI = true;
                        }
                        else
                        {
                            loadedData.IsEnableMAPI = false;
                        }
                        if (cmd.Properties["PopEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnablePOP = true;
                        }
                        else
                        {
                            loadedData.IsEnablePOP = false;
                        }
                        if (cmd.Properties["ImapEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableIMAP = true;
                        }
                        else
                        {
                            loadedData.IsEnableIMAP = false;
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки функций почтового ящика:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка переадресации
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка переадресации...";
                }));
                try
                {
                    string[] loadParam = new string[] { "ForwardingAddress", "ForwardingSmtpAddress" };
                    command.AddCommand("Get-Mailbox");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);

                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки переадресации:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        var cmd = result[0];

                        if (cmd.Properties["ForwardingAddress"].Value != null)
                        {
                            loadedData.ForwardingAddress = cmd.Properties["ForwardingAddress"].Value.ToString();
                        }
                        else
                        {
                            loadedData.ForwardingAddress = "";
                        }

                        if (cmd.Properties["ForwardingSmtpAddress"].Value != null)
                        {
                            loadedData.ForwardingSmtpAddress = cmd.Properties["ForwardingSmtpAddress"].Value.ToString();
                        }
                        else
                        {
                            loadedData.ForwardingSmtpAddress = "";
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки переадресации:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка электронных адресов
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка электронных адресов...";
                }));
                try
                {
                    command.AddCommand("Get-Mailbox");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("ExpandProperty", "EmailAddresses");
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки электронных адресов:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        loadedData.EmailAddress = "";
                        for (int i = 0; i < result.Count; i++)
                        {
                            loadedData.EmailAddress += result[i].Properties["ProxyAddressString"].Value.ToString() + "\r\n";
                            if (result[i].Properties["ProxyAddressString"].Value.ToString().StartsWith("SMTP"))
                            {
                                loadedData.PrimaryEmailAddres = result[i].Properties["ProxyAddressString"].Value.ToString().Split(':')[1];
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки электронных адресов:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка правил входящих сообщений
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка правил входящих сообщений...";
                }));
                try
                {
                    string[] loadParam          = new string[] { "Enabled", "Priority", "Name", "Description" };
                    loadedData.IndoxMessageRule = new List <InboxMessageRuleInfo>();
                    command.AddCommand("Get-InboxRule");
                    command.AddParameter("Mailbox", loadedData.PrimaryEmailAddres);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки правил входящих сообщений:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        for (int i = 0; i < result.Count; i++)
                        {
                            var cmd = result[i];
                            loadedData.IndoxMessageRule.Add(new InboxMessageRuleInfo {
                                IsEnabled   = cmd.Properties["Enabled"].Value.ToString().ToUpper() == "TRUE" ? true : false,
                                Priority    = Int32.Parse(cmd.Properties["Priority"].Value.ToString()),
                                Name        = cmd.Properties["Name"].Value.ToString(),
                                Description = cmd.Properties["Description"].Value.ToString()
                            });
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки правил входящих сообщений:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка информации по установленному автоответу
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка информации по установленному автоответу...";
                }));
                try
                {
                    string[] loadParam    = new string[] { "AutoReplyState", "StartTime", "EndTime", "InternalMessage", "ExternalMessage" };
                    loadedData.AutoReplay = new UserAutoReplayInfo();
                    command.AddCommand("Get-MailboxAutoReplyConfiguration");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки информации по установленному автоответу:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        loadedData.AutoReplay = new UserAutoReplayInfo()
                        {
                            State               = result[0].Properties["AutoReplyState"].Value.ToString(),
                            StartDateTime       = DateTime.ParseExact(result[0].Properties["StartTime"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture),
                            EndDateTime         = DateTime.ParseExact(result[0].Properties["EndTime"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture),
                            InternalMessageText = result[0].Properties["InternalMessage"].Value != null ? result[0].Properties["InternalMessage"].Value.ToString() : "",
                            ExternalMessageText = result[0].Properties["ExternalMessage"].Value != null ? result[0].Properties["ExternalMessage"].Value.ToString() : ""
                        };
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки информации по установленному автоответу:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка информации по мобильным устройствам
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка информации по мобильным устройствам...";
                }));
                try
                {
                    string[] loadParam      = new string[] { "DeviceType", "DeviceFriendlyName", "DeviceModel", "DeviceUserAgent", "LastSyncAttemptTime", "LastSuccessSync" };
                    loadedData.MobileDevice = new List <MobileDeviceInfo>();
                    command.AddCommand("Get-ActiveSyncDeviceStatistics");
                    command.AddParameter("Mailbox", loadedData.PrimaryEmailAddres);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки информации по мобильным устройствам:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        for (int i = 0; i < result.Count; i++)
                        {
                            var cmd = result[i];
                            loadedData.MobileDevice.Add(new MobileDeviceInfo
                            {
                                DeviceType          = cmd.Properties["DeviceType"].Value != null ? cmd.Properties["DeviceType"].Value.ToString() : "",
                                DeviceName          = cmd.Properties["DeviceFriendlyName"].Value != null ? cmd.Properties["DeviceFriendlyName"].Value.ToString() : "",
                                DeviceModel         = cmd.Properties["DeviceModel"].Value != null ? cmd.Properties["DeviceModel"].Value.ToString() : "",
                                DeviceUserAgent     = cmd.Properties["DeviceUserAgent"].Value != null ? cmd.Properties["DeviceUserAgent"].Value.ToString() : "",
                                LastSuccessSyncTime = cmd.Properties["LastSyncAttemptTime"].Value != null ? DateTime.ParseExact(cmd.Properties["LastSyncAttemptTime"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture) : (DateTime?)null,
                                LastSyncTime        = cmd.Properties["LastSuccessSync"].Value != null ? DateTime.ParseExact(cmd.Properties["LastSuccessSync"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture) : (DateTime?)null
                            });
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка информации по мобильным устройствам:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
                command.Clear();
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    setLoadedData(loadedData);
                    isEnableForm(true);
                }));
            });
            t.IsBackground = true;
            t.Start();
        }
Exemplo n.º 9
0
        // Нажата кнопка изменения фамилии
        private void btChangeSurname_Click(object sender, RoutedEventArgs e)
        {
            if (!_userIsSelected)
            {
                MessageBox.Show("Не выбран пользователь!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(newSurname.Text))
            {
                MessageBox.Show("Не указана новая фамилия сотрудника!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(_pathToConfig))
            {
                MessageBox.Show("Отсутствует конфигурационный файл плагина!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string errorMesg             = "";
            string dnUserToChangeSurname = dnUserForChange.Text;
            string newUserSurname        = newSurname.Text.Trim();

            Thread t = new Thread(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Clear();
                    _processRun.Add(new ProcessRunData {
                        Text = "---- Изменение фамилии сотрудника " + dnUserToChangeSurname.Split(',')[0].Substring(3) + "на " + newUserSurname + " ----"
                    });
                    btSelectUser.IsEnabled    = false;
                    btChangeSurname.IsEnabled = false;
                }));

                #region Чтение конфигурационного файла плагина
                ProcessRunData itemProcess = new ProcessRunData {
                    Text = "Чтение конфигурационного файла плагина..."
                };
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Чтение конфигурационного файла плагина..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                configData = GetConfigData(_pathToConfig, ref errorMesg);
                if (!string.IsNullOrWhiteSpace(errorMesg))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text          = "Ошибка чтения конфигурационного файла:\r\n" + errorMesg;
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                if (!configData.ContainsKey("mailserver") || !configData.ContainsKey("maildomain") || !configData.ContainsKey("mailprimarydomain") || !configData.ContainsKey("lyncserver") || !configData.ContainsKey("lyncpool"))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text          = "Отсутсвуют требуемые параметры в конфигурационном файле!!!";
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Чтение конфигурационного файла плагина";
                }));
                #endregion

                //============================================================
                DirectorySearcher dirSearcher = new DirectorySearcher(_ADSession);
                dirSearcher.SearchScope       = SearchScope.Subtree;
                dirSearcher.PropertiesToLoad.Add("cn");
                string newUserLogin        = "";
                UserPrincipal userToModify = UserPrincipal.FindByIdentity(_principalContext, IdentityType.DistinguishedName, dnUserToChangeSurname);
                if (userToModify == null)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _processRun.Add(new ProcessRunData {
                            Text  = "Не удалось получить информацию по текущему пользователю в АД!!!",
                            Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute))
                        });
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                //============================================================

                #region Проверка нового логина в домене
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Проверка нового логина пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в домене..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));

                newUserLogin = translit(userToModify.GivenName + "." + newUserSurname);
                if (newUserLogin.Length > 20)
                {
                    newUserLogin = translit(userToModify.GivenName.Substring(0, 1) + "." + newUserSurname);
                }
                if (newUserLogin.Length > 20)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text          = "Ошибка:\r\nНе удалось сократить логин пользователя до 20 символов!!!";
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                for (int i = 1; i <= userToModify.GivenName.Length; i++)
                {
                    dirSearcher.Filter         = string.Format("(&(objectClass=user)(sAMAccountName={0}))", newUserLogin);
                    SearchResult searchResults = dirSearcher.FindOne();
                    if (searchResults != null)
                    {
                        newUserLogin = translit(userToModify.GivenName.Substring(0, i) + "." + newUserSurname);
                        if (newUserLogin.Length > 20)
                        {
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text          = "Ошибка:\r\nНе удалось сократить логин пользователя до 20 символов!!!";
                                btSelectUser.IsEnabled    = true;
                                btChangeSurname.IsEnabled = true;
                            }));
                            return;
                        }
                    }
                    else
                    {
                        break;
                    }
                    if (i == userToModify.GivenName.Length)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                            itemProcess.Text          = "Ошибка:\r\nНе удалось сформировать новый логин пользователя!!!";
                            btSelectUser.IsEnabled    = true;
                            btChangeSurname.IsEnabled = true;
                        }));
                        return;
                    }
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Проверка нового логина пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в домене";
                }));
                #endregion

                #region Внесение изменений в учетную запись пользователя в АД
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Изменение фамилии пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в АД..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    if (userToModify.Surname != newUserSurname)
                    {
                        userToModify.DisplayName    = translit(newUserSurname + " " + userToModify.GivenName);
                        userToModify.Surname        = newUserSurname;
                        userToModify.SamAccountName = newUserLogin;
                        string[] upn = userToModify.UserPrincipalName.Split('@');
                        userToModify.UserPrincipalName = newUserLogin + "@" + upn[1];
                        userToModify.Save();
                        dirSearcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userToModify.SamAccountName);
                        dirSearcher.PropertiesToLoad.Add("name");
                        SearchResult searchResults = dirSearcher.FindOne();
                        if (searchResults != null)
                        {
                            DirectoryEntry entryToUpdate = searchResults.GetDirectoryEntry();
                            if (entryToUpdate != null)
                            {
                                entryToUpdate.Rename("CN=" + translit(userToModify.GivenName + " " + newUserSurname));
                                entryToUpdate.CommitChanges();
                            }
                            else
                            {
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                    itemProcess.Text          = "Ошибка внесения изменений в учетную запись пользователя в АД:\r\nНе удалось получить запись пользователя в АД!!!";
                                    btSelectUser.IsEnabled    = true;
                                    btChangeSurname.IsEnabled = true;
                                }));
                                return;
                            }
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text          = "Ошибка внесения изменений в учетную запись пользователя в АД:\r\nНе удалось найти пользователя в АД!!!";
                                btSelectUser.IsEnabled    = true;
                                btChangeSurname.IsEnabled = true;
                            }));
                            return;
                        }
                        Thread.Sleep(15000);
                    }
                }
                catch (Exception exc)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text          = "Ошибка внесения изменений в учетную запись пользователя в АД:\r\n" + exc.Message;
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Изменение фамилии пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в АД";
                }));
                #endregion

                //============================================================
                PSCredential credential                = new PSCredential(_login, _password);
                WSManConnectionInfo connectionInfo     = new WSManConnectionInfo((new Uri(configData["mailserver"])), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                Runspace runspace       = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                PowerShell powershell   = PowerShell.Create();
                PSCommand command       = new PSCommand();
                string[] arrMailDomains = configData["maildomain"].Split(',');
                string newMailUserLogin = "";
                string[] userLoginArr   = newUserLogin.Split('.');
                //============================================================

                #region Внесение изменений в Exchange

                #region Подключение к Exchange Server
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Подключение к Exchange Server..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                }
                catch (Exception exp)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text          = "Ошибка подключения к Exchange Server:\r\n" + exp.Message;
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Подключение к Exchange Server";
                }));
                #endregion

                #region Проверка нового электронного адреса
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Проверка нового электронного адреса пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + "..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    for (int i = 1; i <= userLoginArr[0].Length; i++)
                    {
                        newMailUserLogin = userLoginArr[0].Substring(0, i) + userLoginArr[1];
                        command.AddCommand("Get-Mailbox");
                        command.AddParameter("Identity", newMailUserLogin + "@" + configData["mailprimarydomain"].Trim());
                        command.AddCommand("Select-Object");
                        command.AddParameter("Property", "SamAccountName");
                        powershell.Commands = command;
                        var result          = powershell.Invoke();
                        command.Clear();
                        if (result.Count <= 0)
                        {
                            powershell.Streams.Error.Clear();
                            break;
                        }
                        else
                        {
                            if (result[0].Properties["SamAccountName"].Value.ToString() == userToModify.SamAccountName)
                            {
                                powershell.Streams.Error.Clear();
                                break;
                            }
                        }
                        if (i == userLoginArr[0].Length)
                        {
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text  = "Ошибка:\r\nНе удалось сформировать эл.адресс пользователя!!!";
                            }));
                            runspace.Dispose();
                            runspace = null;
                            powershell.Dispose();
                            powershell = null;
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                btSelectUser.IsEnabled    = true;
                                btChangeSurname.IsEnabled = true;
                            }));
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Ошибка проверки нового электронного адреса пользователя:\r\n" + ex.Message;
                    }));
                    command.Clear();
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Проверка нового электронного адреса пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3);
                }));
                #endregion

                #region Изменение псевдонима пользователя в Exchange
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Изменение псевдонима пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в Exchange..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    command.AddCommand("Set-Mailbox");
                    command.AddParameter("Identity", userToModify.SamAccountName);
                    command.AddParameter("Alias", userToModify.SamAccountName);
                    powershell.Commands = command;
                    powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Text = "";
                        }));
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка изменения псевдонима пользователя в Exchange:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text += errorMsg;
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            btSelectUser.IsEnabled    = true;
                            btChangeSurname.IsEnabled = true;
                        }));
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Ошибка изменения псевдонима пользователя в Exchange:\r\n" + ex.Message;
                    }));
                    command.Clear();
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Изменение псевдонима пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + "в Exchange";
                }));
                #endregion

                #region Добавление эл.адресов, установка основного адреса пользователю в Exchange
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Добавление эл.адресов, установка основного адреса пользователю " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в Exchange..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    string[] addEmailString = new string[] {};
                    command.AddCommand("Get-Mailbox");
                    command.AddParameter("Identity", userToModify.SamAccountName);
                    command.AddCommand("Select-Object");
                    command.AddParameter("ExpandProperty", "EmailAddresses");
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Text = "";
                        }));
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка добавления эл.адресов, установка основного адреса пользователю:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text += errorMsg;
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            btSelectUser.IsEnabled    = true;
                            btChangeSurname.IsEnabled = true;
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        for (int i = 0; i < result.Count; i++)
                        {
                            var cmd           = result[i];
                            string cmdletName = cmd.Properties["ProxyAddressString"].Value.ToString();
                            if (cmdletName.StartsWith("SMTP"))
                            {
                                Array.Resize(ref addEmailString, addEmailString.Length + 1);
                                addEmailString[addEmailString.Length - 1] = "smtp:" + cmdletName.Split(':')[1];
                            }
                            else
                            {
                                Array.Resize(ref addEmailString, addEmailString.Length + 1);
                                addEmailString[addEmailString.Length - 1] = cmdletName;
                            }
                        }
                    }
                    command.AddCommand("Set-Mailbox");
                    command.AddParameter("Identity", userToModify.SamAccountName);
                    for (int i = 0; i < arrMailDomains.Length; i++)
                    {
                        int index = 0;
                        if (!containsInArr(addEmailString, "smtp:" + newMailUserLogin + "@" + arrMailDomains[i], ref index))
                        {
                            Array.Resize(ref addEmailString, addEmailString.Length + 1);
                            if (newMailUserLogin + "@" + arrMailDomains[i] == newMailUserLogin + "@" + configData["mailprimarydomain"].Trim())
                            {
                                addEmailString[addEmailString.Length - 1] = "SMTP:" + newMailUserLogin + "@" + arrMailDomains[i];
                            }
                            else
                            {
                                addEmailString[addEmailString.Length - 1] = "smtp:" + newMailUserLogin + "@" + arrMailDomains[i];
                            }
                        }
                        else
                        {
                            if (newMailUserLogin + "@" + arrMailDomains[i] == newMailUserLogin + "@" + configData["mailprimarydomain"].Trim())
                            {
                                addEmailString[index] = "SMTP:" + newMailUserLogin + "@" + arrMailDomains[i];
                            }
                        }
                    }
                    command.AddParameter("EmailAddresses", addEmailString);
                    powershell.Commands = command;
                    powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Text = "";
                        }));
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка добавления эл.адресов, установка основного адреса пользователю:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text += errorMsg;
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            btSelectUser.IsEnabled    = true;
                            btChangeSurname.IsEnabled = true;
                        }));
                        return;
                    }
                    Thread.Sleep(15000);
                }
                catch (Exception ex)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Ошибка добавления эл.адресов, установка основного адреса пользователю:\r\n" + ex.Message;
                    }));
                    command.Clear();
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Добавление эл.адресов пользователю, установка основного адреса " + dnUserToChangeSurname.Split(',')[0].Substring(3) + " в Exchange";
                }));
                #endregion

                #endregion

                //============================================================
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
                command.Clear();
                connectionInfo = new WSManConnectionInfo((new Uri(configData["lyncserver"])), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential;
                connectionInfo.SkipCACheck             = true;
                connectionInfo.SkipCNCheck             = true;
                connectionInfo.SkipRevocationCheck     = true;
                runspace   = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                powershell = PowerShell.Create();
                //============================================================

                #region Внесение изменений в Lync

                #region Подключение к Lync Server
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Подключение к Lync Server..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                }
                catch (Exception exp)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image         = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text          = "Ошибка подключения к Lync Server:\r\n" + exp.Message;
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Подключение к Lync Server";
                }));
                #endregion

                #region Внесение изменений в Lync
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Внесение изменений в Lync для пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3) + "..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    command.AddCommand("enable-csuser");
                    command.AddParameter("Identity", userToModify.SamAccountName);
                    command.AddParameter("registrarPool", configData["lyncpool"]);
                    command.AddParameter("SipAddressType", "EmailAddress");
                    powershell.Commands = command;
                    powershell.Invoke();
                    command.Clear();
                }
                catch (Exception ex)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Ошибка внесения изменений в Lync:\r\n" + ex.Message;
                    }));
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        btSelectUser.IsEnabled    = true;
                        btChangeSurname.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/ChangeSurname;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Внесение изменений в Lync для пользователя " + dnUserToChangeSurname.Split(',')[0].Substring(3);
                }));
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
                #endregion

                #endregion

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "---- Процесс завершён! ----"
                    });
                    dnUserForChange.Text            = "";
                    dnUserForChange.FontWeight      = FontWeights.Normal;
                    dnUserForChange.TextDecorations = null;
                    newSurname.Text           = "";
                    btSelectUser.IsEnabled    = true;
                    btChangeSurname.IsEnabled = true;
                }));
            });

            t.IsBackground = true;
            t.Start();
        }
Exemplo n.º 10
0
        // Нажата кнопка руссификации папок сотрудника
        private void btRussificationFolder_Click(object sender, RoutedEventArgs e)
        {
            if (!_userIsSelected)
            {
                MessageBox.Show("Не выбран пользователь!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(_pathToConfig))
            {
                MessageBox.Show("Отсутствует конфигурационный файл плагина!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string errorMesg           = "";
            string userToRussification = dnUserForChange.Text;

            Thread t = new Thread(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Clear();
                    _processRun.Add(new ProcessRunData {
                        Text = "---- Руссификация папок пользователя " + userToRussification + " ----"
                    });
                    btSelectUser.IsEnabled          = false;
                    btRussificationFolder.IsEnabled = false;
                }));

                #region Чтение конфигурационного файла плагина
                ProcessRunData itemProcess = new ProcessRunData {
                    Text = "Чтение конфигурационного файла плагина..."
                };
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Чтение конфигурационного файла плагина..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                configData = GetConfigData(_pathToConfig, ref errorMesg);
                if (!string.IsNullOrWhiteSpace(errorMesg))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Ошибка чтения конфигурационного файла:\r\n" + errorMesg;
                    }));
                    return;
                }
                if (!configData.ContainsKey("mailserver"))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Отсутсвуют требуемые параметры в конфигурационном файле!!!";
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Чтение конфигурационного файла плагина";
                }));
                #endregion

                //============================================================
                PSCredential credential                = new PSCredential(_login, _password);
                WSManConnectionInfo connectionInfo     = new WSManConnectionInfo((new Uri(configData["mailserver"])), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                Runspace runspace     = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                PowerShell powershell = PowerShell.Create();
                PSCommand command     = new PSCommand();
                //============================================================

                #region Подключение к Exchange Server
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Подключение к Exchange Server..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image               = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text                = "Ошибка подключения к Exchange Server:\r\n" + exp.Message;
                        btSelectUser.IsEnabled          = true;
                        btRussificationFolder.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Подключение к Exchange Server";
                }));
                #endregion

                #region  уссификация папок пользователя
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Руссификация папок пользователя " + userToRussification + "..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));

                try
                {
                    command.AddCommand("Set-MailboxRegionalConfiguration");
                    command.AddParameter("Identity", userToRussification);
                    command.AddParameter("Language", "ru-RU");
                    command.AddParameter("LocalizeDefaultFolderName", true);
                    powershell.Commands = command;
                    powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Text = "";
                        }));
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка руссификации папок пользователя:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text += errorMsg;
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            btSelectUser.IsEnabled          = true;
                            btRussificationFolder.IsEnabled = true;
                        }));
                        return;
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image               = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text                = "Ошибка руссификации папок пользователя:\r\n" + exp.Message;
                        btSelectUser.IsEnabled          = true;
                        btRussificationFolder.IsEnabled = true;
                    }));
                    return;
                }

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Руссификация папок пользователя " + userToRussification;
                }));

                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
                #endregion

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "---- Процесс завершён! ----"
                    });
                    dnUserForChange.Text            = "";
                    _userIsSelected                 = false;
                    dnUserForChange.FontWeight      = FontWeights.Normal;
                    dnUserForChange.TextDecorations = null;
                    btSelectUser.IsEnabled          = true;
                    btRussificationFolder.IsEnabled = true;
                }));
            });

            t.IsBackground = true;
            t.Start();
        }