Exemple #1
0
        private static void FatalError()
        {
            string msg = String.Format(Messages.MESSAGEBOX_PROGRAM_UNEXPECTED,
                                       HelpersGUI.DateTimeToString(DateTime.Now, "yyyy-MM-dd HH:mm:ss", false), GetLogFile_());

            var msgWithStackTrace = string.Format("{0}\n{1}", msg, Environment.StackTrace);

            log.Fatal(msgWithStackTrace);

            MainWindow m = MainWindow;

            if (m == null)
            {
                log.Fatal("Program.MainWindow is null");
            }
            else
            {
                log.FatalFormat("Program.MainWindow.Visible == {0}", m.Visible);
                log.FatalFormat("Program.MainWindow.InvokeRequired == {0}", m.InvokeRequired);
                log.FatalFormat("CurrentThread.Name == {0}", Thread.CurrentThread.Name);
            }

            if (RunInAutomatedTestMode)
            {
                if (TestExceptionString == null)
                {
                    TestExceptionString = msgWithStackTrace;
                }
            }
            else
            {
                using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, msg, Messages.MESSAGEBOX_PROGRAM_UNEXPECTED_TITLE)))
                {
                    dlg.ShowDialog();
                }
            }
        }
Exemple #2
0
        private static void AddError(Form owner, IXenConnection connection, string error, string solution)
        {
            string text = string.Format(Messages.MESSAGEBOX_ERRORTEXT, ((XenConnection)connection).Hostname, error, solution);

            // first check if there is already a dialog showing the same error (CA-97070, CA-88901)
            foreach (Form form in Application.OpenForms)
            {
                if (form.GetType() == typeof(ThreeButtonDialog))
                {
                    ThreeButtonDialog dlg = (ThreeButtonDialog)form;
                    if (dlg.Message == text && dlg.Owner == owner)
                    {
                        HelpersGUI.BringFormToFront(form);
                        return;
                    }
                }
            }

            if (((XenConnection)connection).fromDialog)
            {
                if (DialogResult.Retry == new ThreeButtonDialog(
                        new ThreeButtonDialog.Details(SystemIcons.Error, text, Messages.CONNECT_TO_SERVER),
                        new ThreeButtonDialog.TBDButton(Messages.RETRY_BUTTON_LABEL, DialogResult.Retry, ThreeButtonDialog.ButtonType.ACCEPT, true),
                        ThreeButtonDialog.ButtonCancel).ShowDialog(owner))
                {
                    new AddServerDialog(connection, false).Show(owner);
                }
            }
            else
            {
                new ThreeButtonDialog(
                    new ThreeButtonDialog.Details(
                        SystemIcons.Error,
                        text,
                        Messages.CONNECT_TO_SERVER)).ShowDialog(owner);
            }
        }
Exemple #3
0
        /// <summary>
        /// If the answer of the user to the dialog is YES, then make a list with all the updates and call
        /// DismissUpdates on that list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dismissAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result;

            if (!FilterIsOn)
            {
                using (var dlog = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(null, Messages.UPDATE_DISMISS_ALL_NO_FILTER_CONTINUE),
                           new ThreeButtonDialog.TBDButton(Messages.DISMISS_ALL_YES_CONFIRM_BUTTON, DialogResult.Yes),
                           ThreeButtonDialog.ButtonCancel))
                {
                    result = dlog.ShowDialog(this);
                }
            }
            else
            {
                using (var dlog = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(null, Messages.UPDATE_DISMISS_ALL_CONTINUE),
                           new ThreeButtonDialog.TBDButton(Messages.DISMISS_ALL_CONFIRM_BUTTON, DialogResult.Yes),
                           new ThreeButtonDialog.TBDButton(Messages.DISMISS_FILTERED_CONFIRM_BUTTON, DialogResult.No, ThreeButtonDialog.ButtonType.NONE),
                           ThreeButtonDialog.ButtonCancel))
                {
                    result = dlog.ShowDialog(this);
                }
            }

            if (result == DialogResult.Cancel)
            {
                return;
            }

            var alerts = result == DialogResult.No
                         ? from DataGridViewRow row in dataGridViewUpdates.Rows select row.Tag as Alert
                         : Updates.UpdateAlerts;

            DismissUpdates(alerts);
        }
Exemple #4
0
        private void ToolStripMenuItemDismiss_Click(object sender, EventArgs e)
        {
            if (dataGridViewUpdates.SelectedRows.Count != 1)
            {
                log.DebugFormat("Only 1 update can be dismissed at a time (Attempted to dismiss {0}). Dismissing the clicked item.", dataGridViewUpdates.SelectedRows.Count);
            }

            DataGridViewRow clickedRow = FindAlertRow(sender as ToolStripMenuItem);

            if (clickedRow == null)
            {
                log.Debug("Attempted to dismiss update with no update selected.");
                return;
            }

            Alert alert = (Alert)clickedRow.Tag;

            if (alert == null)
            {
                return;
            }

            using (var dlog = new ThreeButtonDialog(
                       new ThreeButtonDialog.Details(null, Messages.UPDATE_DISMISS_CONFIRM, Messages.XENCENTER),
                       ThreeButtonDialog.ButtonYes,
                       ThreeButtonDialog.ButtonNo))
            {
                if (dlog.ShowDialog(this) != DialogResult.Yes)
                {
                    return;
                }
            }

            DismissUpdates(new List <Alert> {
                (Alert)clickedRow.Tag
            });
        }
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            var selectedPolicies     = new List <VMSS>();
            int numberOfProtectedVMs = 0;

            foreach (PolicyRow row in dataGridViewPolicies.SelectedRows)
            {
                selectedPolicies.Add(row.Policy);
                numberOfProtectedVMs += row.Policy.VMs.Count;
            }

            string text = selectedPolicies.Count == 1
                ? String.Format(numberOfProtectedVMs == 0
                    ? Messages.CONFIRM_DELETE_POLICY_0
                    : Messages.CONFIRM_DELETE_POLICY, selectedPolicies[0].Name(), numberOfProtectedVMs)
                : string.Format(numberOfProtectedVMs == 0
                    ? Messages.CONFIRM_DELETE_POLICIES_0
                    : Messages.CONFIRM_DELETE_POLICIES, numberOfProtectedVMs);

            using (var dlg = new ThreeButtonDialog(
                       new ThreeButtonDialog.Details(SystemIcons.Warning, text, Messages.DELETE_VMSS_TITLE),
                       ThreeButtonDialog.ButtonYes,
                       ThreeButtonDialog.ButtonNo))
            {
                if (dlg.ShowDialog(this) == DialogResult.Yes)
                {
                    foreach (PolicyRow row in dataGridViewPolicies.SelectedRows)
                    {
                        row.IsBusy = true;
                    }

                    RefreshButtons();
                    new DestroyPolicyAction(Pool.Connection, selectedPolicies).RunAsync();
                }
            }
        }
Exemple #6
0
        private void helperLink_Click(object sender, EventArgs e)
        {
            if (LinkUri == null)
            {
                return;
            }

            try
            {
                Process.Start(LinkUri.AbsoluteUri);
            }
            catch (Exception)
            {
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               string.Format(Messages.COULD_NOT_OPEN_URL,
                                             LinkUri.AbsoluteUri),
                               Messages.XENCENTER)))
                {
                    dlg.ShowDialog(Program.MainWindow);
                }
            }
        }
Exemple #7
0
        public IWebProxy GetProxyFromSettings(IXenConnection connection)
        {
            try
            {
                if (connection != null && connection.Session != null && connection.Session.uuid == "dummy")
                    return new XenAdminSimulatorWebProxy(DbProxy.proxys[connection]);

                switch ((HTTPHelper.ProxyStyle)XenAdmin.Properties.Settings.Default.ProxySetting)
                {
                    case HTTPHelper.ProxyStyle.SpecifiedProxy:
                        return new WebProxy(string.Format("http://{0}:{1}",
                            XenAdmin.Properties.Settings.Default.ProxyAddress,
                            XenAdmin.Properties.Settings.Default.ProxyPort),
                            XenAdmin.Properties.Settings.Default.BypassProxyForLocal);

                    case HTTPHelper.ProxyStyle.SystemProxy:
                        return WebRequest.GetSystemWebProxy();

                    default:
                        return null;
                }
            }
            catch (ConfigurationErrorsException e)
            {
                log.Error("Error parsing 'ProxySetting' from settings - settings file deemed corrupt", e);
                using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error,
                    string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath()),
                    Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE)))
                {
                    dlg.ShowDialog();
                }

                Environment.Exit(1);
            }
            return null;
        }
Exemple #8
0
        private void buttonEnableDisableHa_Click(object sender, EventArgs e)
        {
            if (pool == null)
            {
                return;
            }

            if (!pool.ha_enabled)
            {
                // Start HA wizard
                EditHA(pool);
                return;
            }

            // Offer to disable HA
            DialogResult dr = new ThreeButtonDialog(
                new ThreeButtonDialog.Details(
                    null,
                    string.Format(Messages.HA_DISABLE_QUERY, Helpers.GetName(pool).Ellipsise(30)),
                    Messages.DISABLE_HA),
                "HADisable",
                ThreeButtonDialog.ButtonYes,
                ThreeButtonDialog.ButtonNo).ShowDialog(this);

            if (dr != DialogResult.Yes)
            {
                return;
            }

            DisableHAAction action = new DisableHAAction(pool);

            // We will need to re-enable buttons when the action completes
            action.Completed += Program.MainWindow.action_Completed;
            action.RunAsync();
            Program.MainWindow.UpdateToolbars();
        }
Exemple #9
0
        /// <summary>
        /// Attempts to save the settings. On catching an exception will prompt the user and close XC.
        /// </summary>
        public static void TrySaveSettings()
        {
            try
            {
                Properties.Settings.Default.Save();
            }
            catch (ConfigurationErrorsException ex)
            {
                // Show a warning to the user and exit the application.
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               string.Format(Messages.MESSAGEBOX_SAVE_CORRUPTED, Settings.GetUserConfigPath()),
                               Messages.MESSAGEBOX_SAVE_CORRUPTED_TITLE)
                           ))
                {
                    dlg.ShowDialog(Program.MainWindow);
                }

                log.Error("Could not save settings. Exiting application.");
                log.Error(ex, ex);
                Application.Exit();
            }
        }
        protected override AsyncAction CreateAction(out bool cancelled)
        {
            AsyncAction action = null;

            if (diskSpaceReq.CanCleanup)
            {
                Program.Invoke(Program.MainWindow, delegate()
                {
                    DialogResult r = new ThreeButtonDialog(
                        new ThreeButtonDialog.Details(
                            SystemIcons.Warning,
                            diskSpaceReq.GetSpaceRequirementsMessage()),
                        new ThreeButtonDialog.TBDButton(Messages.YES, DialogResult.Yes, ThreeButtonDialog.ButtonType.ACCEPT, true),
                        ThreeButtonDialog.ButtonNo
                        ).ShowDialog();


                    if (r == DialogResult.Yes)
                    {
                        action = new CleanupDiskSpaceAction(this.Server, patch, true);
                    }
                });
            }
            else
            {
                Program.Invoke(Program.MainWindow, delegate()
                {
                    new ThreeButtonDialog(
                        new ThreeButtonDialog.Details(SystemIcons.Warning, diskSpaceReq.GetSpaceRequirementsMessage()))
                    .ShowDialog();
                });
            }
            cancelled = action == null;

            return(action);
        }
        private void SaveSubscription()
        {
            if (this._subscription == null)
            {
                _subscription = new WlbReportSubscription(String.Empty);
                _subscription.SubscriberName = GetLoggedInAsText();
                _subscription.Created = DateTime.UtcNow;
            }
            _subscription.Name = this.subNameTextBox.Text;
            _subscription.Description = this.subNameTextBox.Text;

            DateTime utcExecuteTime;
            WlbScheduledTask.WlbTaskDaysOfWeek utcDaysOfWeek;
            WlbScheduledTask.GetUTCTaskTimes((WlbScheduledTask.WlbTaskDaysOfWeek)this.schedDeliverComboBox.SelectedValue, this.dateTimePickerSubscriptionRunTime.Value, out utcDaysOfWeek, out utcExecuteTime);
            _subscription.ExecuteTimeOfDay = utcExecuteTime;
            _subscription.DaysOfWeek = utcDaysOfWeek;
            if (_subscription.DaysOfWeek != WlbScheduledTask.WlbTaskDaysOfWeek.All)
            {
                _subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Weekly;
            }
            else
            {
                _subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Daily;
            }
            _subscription.Enabled = true;
            _subscription.EnableDate = this.dateTimePickerSchedStart.Value == DateTime.MinValue ? DateTime.UtcNow : this.dateTimePickerSchedStart.Value.ToUniversalTime();
            _subscription.DisableDate = this.dateTimePickerSchedEnd.Value == DateTime.MinValue ? DateTime.UtcNow.AddMonths(1) : this.dateTimePickerSchedEnd.Value.ToUniversalTime();
            _subscription.LastTouched = DateTime.UtcNow;
            _subscription.LastTouchedBy = GetLoggedInAsText();

            // store email info
            _subscription.EmailTo = this.emailToTextBox.Text.Trim();
            _subscription.EmailCc = this.emailCcTextBox.Text.Trim();
            _subscription.EmailBcc = this.emailBccTextBox.Text.Trim();
            _subscription.EmailReplyTo = this.emailReplyTextBox.Text.Trim();
            _subscription.EmailSubject = this.emailSubjectTextBox.Text.Trim();
            _subscription.EmailComment = this.emailCommentRichTextBox.Text;

            // store reoprt Info
            //sub.ReportId = ;
            _subscription.ReportRenderFormat = this.rpRenderComboBox.SelectedIndex;
            Dictionary<string, string> rps = new Dictionary<string, string>();
            foreach(string key in this._rpParams.Keys)
            {
                if (String.Compare(key, WlbReportSubscription.REPORT_NAME, true) == 0)
                    _subscription.ReportName = this._rpParams[WlbReportSubscription.REPORT_NAME];
                else
                {
                    //Get start date range
                    if (String.Compare(key, "start", true) == 0)
                    {
                        rps.Add(key, ((this.rpParamComboBox.SelectedIndex + 1) * (-7)+1).ToString());
                    }
                    else
                    {
                        rps.Add(key, _rpParams[key]);
                    }
                }
            }
            _subscription.ReportParameters = rps;

            SendWlbConfigurationAction action = new SendWlbConfigurationAction(this._pool, _subscription.ToDictionary(), SendWlbConfigurationKind.SetReportSubscription);
            using (var dialog = new ActionProgressDialog(action, ProgressBarStyle.Blocks))
            {
                dialog.ShowCancel = true;
                dialog.ShowDialog(this);
            }

            if (action.Succeeded)
            {
                DialogResult = DialogResult.OK;
                this.Close();
            }
            else if(!action.Cancelled)
            {
                using (var dlg = new ThreeButtonDialog(
                   new ThreeButtonDialog.Details(
                       SystemIcons.Error,
                       String.Format(Messages.WLB_SUBSCRIPTION_ERROR, _subscription.Description),
                       Messages.XENCENTER)))
                {
                    dlg.ShowDialog(this);
                }
                //log.ErrorFormat("There was an error calling SendWlbConfigurationAction to SetReportSubscription {0}, Action Result: {1}.", _subscription.Description, action.Result);
                DialogResult = DialogResult.None;
            }
        }
Exemple #12
0
		private void toolStripButtonShutdown_Click(object sender, EventArgs e)
		{
			if (currentSelected == null)
				return;

			using (var confirmDialog = new ThreeButtonDialog(
				new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.CONFIRM_SHUT_DOWN_APPLIANCE, Messages.VM_APPLIANCE_SHUT_DOWN),
				ThreeButtonDialog.ButtonYes,
				ThreeButtonDialog.ButtonNo))
			{
				if (confirmDialog.ShowDialog(this) != DialogResult.Yes)
					return;
				//shut down appliance
				(new ShutDownApplianceAction(currentSelected)).RunAsync();
			}
		}
Exemple #13
0
        private static void ShowConnectingDialogError(Form owner, IXenConnection connection, Exception error)
        {
            if (error is ExpressRestriction e)
            {
                Program.Invoke(Program.MainWindow, delegate()
                {
                    new LicenseWarningDialog(e.HostName, e.ExistingHostName).ShowDialog(owner);
                });
                return;
            }

            if (error is Failure f)
            {
                if (f.ErrorDescription[0] == Failure.HOST_IS_SLAVE)
                {
                    string oldHost        = connection.Name;
                    string poolMasterName = f.ErrorDescription[1];

                    string pool_name = XenConnection.ConnectedElsewhere(poolMasterName);
                    if (pool_name != null)
                    {
                        if (!Program.RunInAutomatedTestMode)
                        {
                            if (pool_name == oldHost)
                            {
                                using (var dlg = new ThreeButtonDialog(
                                           new ThreeButtonDialog.Details(
                                               SystemIcons.Information,
                                               string.Format(Messages.OLD_CONNECTION_ALREADY_CONNECTED, pool_name),
                                               Messages.ADD_NEW_CONNECT_TO)))
                                {
                                    dlg.ShowDialog(owner);
                                }
                            }
                            else
                            {
                                using (var dlg = new ThreeButtonDialog(
                                           new ThreeButtonDialog.Details(
                                               SystemIcons.Information,
                                               string.Format(Messages.SLAVE_ALREADY_CONNECTED, oldHost, pool_name),
                                               Messages.ADD_NEW_CONNECT_TO)))
                                {
                                    dlg.ShowDialog(owner);
                                }
                            }
                        }
                    }
                    else
                    {
                        DialogResult dialogResult;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(
                                       SystemIcons.Warning,
                                       String.Format(Messages.SLAVE_CONNECTION_ERROR, oldHost, poolMasterName),
                                       Messages.CONNECT_TO_SERVER),
                                   ThreeButtonDialog.ButtonYes,
                                   ThreeButtonDialog.ButtonNo))
                        {
                            dialogResult = dlg.ShowDialog(owner);
                        }
                        if (DialogResult.Yes == dialogResult)
                        {
                            ((XenConnection)connection).Hostname = poolMasterName;
                            BeginConnect(connection, true, owner, false);
                        }
                    }
                }
                else if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                {
                    AddError(owner, connection, Messages.ERROR_NO_PERMISSION, Messages.SOLUTION_NO_PERMISSION);
                }
                else if (f.ErrorDescription[0] == XenAPI.Failure.SESSION_AUTHENTICATION_FAILED)
                {
                    AddError(owner, connection, Messages.ERROR_AUTHENTICATION, Messages.SOLUTION_AUTHENTICATION);
                }
                else if (f.ErrorDescription[0] == Failure.HOST_STILL_BOOTING)
                {
                    AddError(owner, connection, Messages.ERROR_HOST_STILL_BOOTING, Messages.SOLUTION_HOST_STILL_BOOTING);
                }
                else
                {
                    AddError(owner, connection, string.IsNullOrEmpty(f.Message) ? Messages.ERROR_UNKNOWN : f.Message, string.Empty);
                }
            }
            else if (error is WebException w)
            {
                if (((XenConnection)connection).SuppressErrors)
                {
                    return;
                }

                var solutionCheckXenServer =
                    Properties.Settings.Default.ProxySetting != (int)HTTPHelper.ProxyStyle.DirectConnection ? Messages.SOLUTION_CHECK_XENSERVER_WITH_PROXY : Messages.SOLUTION_CHECK_XENSERVER;

                switch (w.Status)
                {
                case WebExceptionStatus.ConnectionClosed:
                    AddError(owner, connection, Messages.CONNECTION_CLOSED_BY_SERVER, string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.ConnectFailure:
                    AddError(owner, connection, Messages.CONNECTION_REFUSED, string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.ProtocolError:
                    if (w.Message != null && w.Message.Contains("(404)"))
                    {
                        AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    }
                    else if (w.Message != null && w.Message.Contains("(407)"))
                    {
                        string proxyAddress = Properties.Settings.Default.ProxyAddress;
                        AddError(owner, connection, string.Format(Messages.ERROR_PROXY_AUTHENTICATION, proxyAddress), string.Format(Messages.SOLUTION_CHECK_PROXY, proxyAddress));
                    }
                    else
                    {
                        AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN);
                    }
                    break;

                case WebExceptionStatus.NameResolutionFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_NOT_FOUND, ((XenConnection)connection).Hostname), Messages.SOLUTION_NOT_FOUND);
                    break;

                case WebExceptionStatus.ReceiveFailure:
                case WebExceptionStatus.SendFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.SecureChannelFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_SECURE_CHANNEL_FAILURE, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN);
                    break;

                default:
                    AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN);
                    break;
                }
            }
            else if (error is UriFormatException)
            {
                AddError(owner, connection, string.Format(Messages.ERROR_INVALID_URI, connection.Name), Messages.SOLUTION_NOT_FOUND);
            }
            else if (error is FileNotFoundException)
            {
                // If you're using the DbProxy
                AddError(owner, connection, string.Format(string.Format(Messages.ERROR_FILE_NOT_FOUND, ((XenConnection)connection).Hostname), connection.Name), Messages.SOLUTION_UNKNOWN);
            }
            else if (error is ConnectionExists c)
            {
                ConnectionsManager.ClearCacheAndRemoveConnection(connection);

                if (!Program.RunInAutomatedTestMode)
                {
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Information,
                                   c.GetDialogMessage(connection),
                                   Messages.XENCENTER)))
                    {
                        dlg.ShowDialog(owner);
                    }
                }
            }
            else if (error is ArgumentException)
            {
                // This happens if the server API is incompatible with our bindings.  This should
                // never happen in production, but will happen during development if a field
                // changes type, for example.
                AddError(owner, connection, Messages.SERVER_API_INCOMPATIBLE, Messages.SOLUTION_UNKNOWN);
            }
            else if (error is ServerNotSupported)
            {
                // Server version is too old for this version of XenCenter
                AddError(owner, connection, Messages.SERVER_TOO_OLD, Messages.SERVER_TOO_OLD_SOLUTION);
            }
            else
            {
                if (((XenConnection)connection).SuppressErrors)
                {
                    return;
                }

                AddError(owner, connection, string.Format(Messages.ERROR_UNKNOWN, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN);
            }
        }
Exemple #14
0
        private void ButtonRemove_Click(object sender, EventArgs e)
        {
            Program.AssertOnEventThread();

            // Double check, this method is called from a context menu as well and the state could have changed under it
            if (!ButtonRemove.Enabled)
            {
                return;
            }

            List <Subject> subjectsToRemove = new List <Subject>();

            foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows)
            {
                subjectsToRemove.Add(r.subject);
            }

            var removeMessage = subjectsToRemove.Count == 1
                ? string.Format(Messages.QUESTION_REMOVE_AD_USER_ONE, subjectsToRemove[0].DisplayName ?? subjectsToRemove[0].SubjectName)
                : string.Format(Messages.QUESTION_REMOVE_AD_USER_MANY, subjectsToRemove.Count);

            DialogResult questionDialog;

            using (var dlg = new ThreeButtonDialog(
                       new ThreeButtonDialog.Details(
                           null,
                           removeMessage,
                           Messages.AD_FEATURE_NAME),
                       ThreeButtonDialog.ButtonYes,
                       new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
            {
                questionDialog = dlg.ShowDialog(this);
            }

            //CA-64818: DialogResult can be No if the No button has been hit
            //or Cancel if the dialog has been closed from the control box
            if (questionDialog != DialogResult.Yes)
            {
                return;
            }

            // Warn if user is revoking his currently-in-use credentials
            Session session = _connection.Session;

            if (session != null && session.SessionSubject != null)
            {
                foreach (Subject entry in subjectsToRemove)
                {
                    if (entry.opaque_ref == session.SessionSubject)
                    {
                        string subjectName = entry.DisplayName ?? entry.SubjectName;
                        if (subjectName == null)
                        {
                            subjectName = entry.subject_identifier;
                        }
                        else
                        {
                            subjectName = subjectName.Ellipsise(256);
                        }
                        string msg = string.Format(entry.IsGroup ? Messages.AD_CONFIRM_SUICIDE_GROUP : Messages.AD_CONFIRM_SUICIDE,
                                                   subjectName, Helpers.GetName(_connection).Ellipsise(50));

                        DialogResult r;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(
                                       SystemIcons.Warning,
                                       msg,
                                       Messages.AD_FEATURE_NAME),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            r = dlg.ShowDialog(this);
                        }

                        //CA-64818: DialogResult can be No if the No button has been hit
                        //or Cancel if the dialog has been closed from the control box
                        if (r != DialogResult.Yes)
                        {
                            return;
                        }

                        break;
                    }
                }
            }

            var action = new AddRemoveSubjectsAction(_connection, new List <string>(), subjectsToRemove);

            using (var dlog = new ActionProgressDialog(action, ProgressBarStyle.Continuous))
                dlog.ShowDialog(this);
        }
Exemple #15
0
        private void buttonJoinLeave_Click(object sender, EventArgs e)
        {
            Program.AssertOnEventThread();
            if (buttonJoinLeave.Text == Messages.AD_JOIN_DOMAIN)
            {
                // We're enabling AD
                // Obtain domain, username and password; store the domain and username
                // so the user won't have to retype it for future join attempts

                using (var joinPrompt = new AdPasswordPrompt(true)
                {
                    Domain = _storedDomain, Username = _storedUsername
                })
                {
                    var result = joinPrompt.ShowDialog(this);
                    _storedDomain   = joinPrompt.Domain;
                    _storedUsername = joinPrompt.Username;

                    if (result == DialogResult.Cancel)
                    {
                        return;
                    }

                    new EnableAdAction(_connection, joinPrompt.Domain, joinPrompt.Username, joinPrompt.Password).RunAsync();
                }
            }
            else
            {
                // We're disabling AD

                // Warn if the user will boot himself out by disabling AD
                Session session = _connection.Session;
                if (session == null)
                {
                    return;
                }

                if (session.IsLocalSuperuser)
                {
                    // User is authenticated using local root account. Confirm anyway.
                    string msg = string.Format(Messages.AD_LEAVE_CONFIRM,
                                               Helpers.GetName(_connection).Ellipsise(50).EscapeAmpersands(), Domain.Ellipsise(30));

                    DialogResult r;
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(null, msg, Messages.AD_FEATURE_NAME),
                               ThreeButtonDialog.ButtonYes,
                               new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                    {
                        r = dlg.ShowDialog(this);
                    }

                    //CA-64818: DialogResult can be No if the No button has been hit
                    //or Cancel if the dialog has been closed from the control box
                    if (r != DialogResult.Yes)
                    {
                        return;
                    }
                }
                else
                {
                    // Warn user will be booted out.
                    string msg = string.Format(Helpers.GetPool(_connection) != null ? Messages.AD_LEAVE_WARNING : Messages.AD_LEAVE_WARNING_HOST,
                                               Helpers.GetName(_connection).Ellipsise(50), Domain.Ellipsise(30));

                    DialogResult r;
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.ACTIVE_DIRECTORY_TAB_TITLE),
                               ThreeButtonDialog.ButtonYes,
                               new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                    {
                        r = dlg.ShowDialog(this);
                    }

                    //CA-64818: DialogResult can be No if the No button has been hit
                    //or Cancel if the dialog has been closed from the control box
                    if (r != DialogResult.Yes)
                    {
                        return;
                    }
                }

                Host master = Helpers.GetMaster(_connection);
                if (master == null)
                {
                    // Really shouldn't happen unless we have been very slow with the cache
                    log.Error("Could not retrieve master when trying to look up domain..");
                    throw new Exception(Messages.CONNECTION_IO_EXCEPTION);
                }

                using (var passPrompt = new AdPasswordPrompt(false, master.external_auth_service_name))
                {
                    var result = passPrompt.ShowDialog(this);
                    if (result == DialogResult.Cancel)
                    {
                        return;
                    }

                    var creds = new Dictionary <string, string>();
                    if (result != DialogResult.Ignore)
                    {
                        creds.Add(DisableAdAction.KEY_USER, passPrompt.Username);
                        creds.Add(DisableAdAction.KEY_PASSWORD, passPrompt.Password);
                    }

                    new DisableAdAction(_connection, creds).RunAsync();
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// In the case there being nowhere to start/resume the VM (NO_HOSTS_AVAILABLE), shows the reason why the VM could not be started
        /// on each host. If the start failed due to HA_OPERATION_WOULD_BREAK_FAILOVER_PLAN, offers to decrement ntol and try the operation
        /// again.
        /// </summary>
        /// <param name="vm"></param>
        /// <param name="f"></param>
        /// <param name="kind">The kind of the operation that failed. Must be one of Start/StartOn/Resume/ResumeOn.</param>
        public static void StartDiagnosisForm(VMStartAbstractAction VMStartAction, Failure failure)
        {
            if (failure.ErrorDescription[0] == Failure.NO_HOSTS_AVAILABLE)
            {
                // Show a dialog displaying why the VM couldn't be started on each host
                StartDiagnosisForm(VMStartAction.VM, VMStartAction.IsStart);
            }
            else if (failure.ErrorDescription[0] == Failure.HA_OPERATION_WOULD_BREAK_FAILOVER_PLAN)
            {
                // The action was blocked by HA because it would reduce the number of tolerable server failures.
                // With the user's consent, we'll reduce the number of configured failures to tolerate and try again.
                Pool pool = Helpers.GetPool(VMStartAction.VM.Connection);
                if (pool == null)
                {
                    log.ErrorFormat("Could not get pool for VM {0} in StartDiagnosisForm()", Helpers.GetName(VMStartAction.VM));
                    return;
                }

                long ntol    = pool.ha_host_failures_to_tolerate;
                long newNtol = Math.Min(pool.ha_plan_exists_for - 1, ntol - 1);
                if (newNtol <= 0)
                {
                    // We would need to basically turn HA off to start this VM
                    string msg = String.Format(VMStartAction.IsStart ? Messages.HA_VM_START_NTOL_ZERO : Messages.HA_VM_RESUME_NTOL_ZERO,
                                               Helpers.GetName(pool).Ellipsise(100),
                                               Helpers.GetName(VMStartAction.VM).Ellipsise(100));
                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.HIGH_AVAILABILITY)))
                        {
                            dlg.ShowDialog(Program.MainWindow);
                        }
                    });
                }
                else
                {
                    // Show 'reduce ntol?' dialog
                    string msg = String.Format(VMStartAction.IsStart ? Messages.HA_VM_START_NTOL_DROP : Messages.HA_VM_RESUME_NTOL_DROP,
                                               Helpers.GetName(pool).Ellipsise(100), ntol,
                                               Helpers.GetName(VMStartAction.VM).Ellipsise(100), newNtol);

                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        DialogResult r;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.HIGH_AVAILABILITY),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            r = dlg.ShowDialog(Program.MainWindow);
                        }

                        if (r == DialogResult.Yes)
                        {
                            DelegatedAsyncAction action = new DelegatedAsyncAction(VMStartAction.VM.Connection, Messages.HA_LOWERING_NTOL, null, null,
                                                                                   delegate(Session session)
                            {
                                // Set new ntol, then retry action
                                XenAPI.Pool.set_ha_host_failures_to_tolerate(session, pool.opaque_ref, newNtol);
                                // ntol set succeeded, start new action
                                VMStartAction.Clone().RunAsync();
                            });
                            action.RunAsync();
                        }
                    });
                }
            }
        }
        private void toolStripButtonExportAll_Click(object sender, EventArgs e)
        {
            bool exportAll = true;

            if (FilterIsOn)
            {
                using (var dlog = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(null, Messages.ALERT_EXPORT_ALL_OR_FILTERED),
                           new ThreeButtonDialog.TBDButton(Messages.ALERT_EXPORT_ALL_BUTTON, DialogResult.Yes),
                           new ThreeButtonDialog.TBDButton(Messages.ALERT_EXPORT_FILTERED_BUTTON, DialogResult.No, ThreeButtonDialog.ButtonType.NONE),
                           ThreeButtonDialog.ButtonCancel))
                {
                    var result = dlog.ShowDialog(this);
                    if (result == DialogResult.No)
                    {
                        exportAll = false;
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        return;
                    }
                }
            }

            string fileName;

            using (SaveFileDialog dialog = new SaveFileDialog
            {
                AddExtension = true,
                Filter = string.Format("{0} (*.csv)|*.csv|{1} (*.*)|*.*",
                                       Messages.CSV_DESCRIPTION, Messages.ALL_FILES),
                FilterIndex = 0,
                Title = Messages.EXPORT_ALL,
                RestoreDirectory = true,
                DefaultExt = "csv",
                CheckPathExists = false,
                OverwritePrompt = true
            })
            {
                if (dialog.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }
                fileName = dialog.FileName;
            }

            new DelegatedAsyncAction(null,
                                     string.Format(Messages.EXPORT_SYSTEM_ALERTS, fileName),
                                     string.Format(Messages.EXPORTING_SYSTEM_ALERTS, fileName),
                                     string.Format(Messages.EXPORTED_SYSTEM_ALERTS, fileName),
                                     delegate
            {
                using (StreamWriter stream = new StreamWriter(fileName, false, UTF8Encoding.UTF8))
                {
                    stream.WriteLine("{0},{1},{2},{3},{4}", Messages.TITLE,
                                     Messages.SEVERITY, Messages.DESCRIPTION,
                                     Messages.APPLIES_TO, Messages.TIMESTAMP);

                    if (exportAll)
                    {
                        foreach (Alert a in Alert.Alerts)
                        {
                            if (!a.Dismissing)
                            {
                                stream.WriteLine(a.GetAlertDetailsCSVQuotes());
                            }
                        }
                    }
                    else
                    {
                        foreach (DataGridViewRow row in GridViewAlerts.Rows)
                        {
                            var a = row.Tag as Alert;
                            if (a != null && !a.Dismissing)
                            {
                                stream.WriteLine(a.GetAlertDetailsCSVQuotes());
                            }
                        }
                    }
                }
            }).RunAsync();
        }
Exemple #18
0
        private void RunFinalAction(out bool closeWizard)
        {
            FinalAction = null;
            closeWizard = false;

            // Override the WizardBase: try running the SR create/attach. If it succeeds, close the wizard.
            // Otherwise show the error and allow the user to adjust the settings and try again.
            Pool pool = Helpers.GetPoolOfOne(xenConnection);

            if (pool == null)
            {
                log.Error("New SR Wizard: Pool has disappeared");
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.NEW_SR_CONNECTION_LOST, Helpers.GetName(xenConnection)), Messages.XENCENTER)))
                {
                    dlg.ShowDialog(this);
                }

                closeWizard = true;
                return;
            }

            Host master = xenConnection.Resolve(pool.master);

            if (master == null)
            {
                log.Error("New SR Wizard: Master has disappeared");
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.NEW_SR_CONNECTION_LOST, Helpers.GetName(xenConnection)), Messages.XENCENTER)))
                {
                    dlg.ShowDialog(this);
                }

                closeWizard = true;
                return;
            }

            if (_srToReattach != null && _srToReattach.HasPBDs() && _srToReattach.Connection == xenConnection)
            {
                // Error - cannot reattach attached SR
                MessageBox.Show(this,
                                String.Format(Messages.STORAGE_IN_USE, _srToReattach.Name(), Helpers.GetName(xenConnection)),
                                Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                FinishCanceled();
                return;
            }

            // show warning prompt if required
            if (!AskUserIfShouldContinue())
            {
                FinishCanceled();
                return;
            }

            List <AsyncAction> actionList = GetActions(master, m_srWizardType.DisasterRecoveryTask);

            if (actionList.Count == 1)
            {
                FinalAction = actionList[0];
            }
            else
            {
                FinalAction = new ParallelAction(xenConnection, Messages.NEW_SR_WIZARD_FINAL_ACTION_TITLE,
                                                 Messages.NEW_SR_WIZARD_FINAL_ACTION_START,
                                                 Messages.NEW_SR_WIZARD_FINAL_ACTION_END, actionList);
            }

            // if this is a Disaster Recovery Task, it could be either a "Find existing SRs" or an "Attach SR needed for DR" case
            if (m_srWizardType.DisasterRecoveryTask)
            {
                closeWizard = true;
                return;
            }

            ProgressBarStyle progressBarStyle = FinalAction is SrIntroduceAction ? ProgressBarStyle.Blocks : ProgressBarStyle.Marquee;

            using (var dialog = new ActionProgressDialog(FinalAction, progressBarStyle)
            {
                ShowCancel = true
            })
            {
                if (m_srWizardType is SrWizardType_Hba || m_srWizardType is SrWizardType_Fcoe)
                {
                    ActionProgressDialog closureDialog = dialog;
                    // close dialog even when there's an error for HBA SR type as there will be the Summary page displayed.
                    FinalAction.Completed +=
                        s => Program.Invoke(Program.MainWindow, () =>
                    {
                        if (closureDialog != null)
                        {
                            closureDialog.Close();
                        }
                    });
                }
                dialog.ShowDialog(this);
            }

            if (m_srWizardType is SrWizardType_Hba || m_srWizardType is SrWizardType_Fcoe)
            {
                foreach (var asyncAction in actionList)
                {
                    AddActionToSummary(asyncAction);
                }
            }

            if (!FinalAction.Succeeded && FinalAction is SrReattachAction && _srToReattach.HasPBDs())
            {
                // reattach failed. Ensure PBDs are now unplugged and destroyed.
                using (var dialog = new ActionProgressDialog(new SrAction(SrActionKind.UnplugAndDestroyPBDs, _srToReattach), progressBarStyle))
                {
                    dialog.ShowCancel = false;
                    dialog.ShowDialog();
                }
            }

            // If action failed and frontend wants to stay open, just return
            if (!FinalAction.Succeeded)
            {
                DialogResult = DialogResult.None;
                FinishCanceled();

                if (m_srWizardType.AutoDescriptionRequired)
                {
                    foreach (var srDescriptor in m_srWizardType.SrDescriptors)
                    {
                        srDescriptor.Description = null;
                    }
                }

                return;
            }

            // Close wizard
            closeWizard = true;
        }
Exemple #19
0
        static public void Main(string[] Args)
        {
            //Upgrade settings
            System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
            Version appVersion           = a.GetName().Version;
            string  appVersionString     = appVersion.ToString();

            log.DebugFormat("Application version of new settings {0}", appVersionString);

            try
            {
                if (Properties.Settings.Default.ApplicationVersion != appVersion.ToString())
                {
                    log.Debug("Upgrading settings...");
                    Properties.Settings.Default.Upgrade();

                    // if program's hash has changed (e.g. by upgrading to .NET 4.0), then Upgrade() doesn't import the previous application settings
                    // because it cannot locate a previous user.config file. In this case a new user.config file is created with the default settings.
                    // We will try and find a config file from a previous installation and update the settings from it
                    if (Properties.Settings.Default.ApplicationVersion == "" && Properties.Settings.Default.DoUpgrade)
                    {
                        SettingsUpdate.Update();
                    }
                    log.DebugFormat("Settings upgraded from '{0}' to '{1}'", Properties.Settings.Default.ApplicationVersion, appVersionString);
                    Properties.Settings.Default.ApplicationVersion = appVersionString;
                    Settings.TrySaveSettings();
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                log.Error("Could not load settings.", ex);
                var msg = string.Format("{0}\n\n{1}", Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE,
                                        string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath()));
                var dlog = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, msg, Messages.XENCENTER))
                {
                    StartPosition = FormStartPosition.CenterScreen,
                    //For reasons I do not fully comprehend at the moment, the runtime
                    //overrides the above StartPosition with WindowsDefaultPosition if
                    //ShowInTaskbar is false. However it's a good idea anyway to show it
                    //in the taskbar since the main form is not launcched at this point.
                    ShowInTaskbar = true
                };
                dlog.ShowDialog();
                Application.Exit();
                return;
            }

            // Reset statics, because XenAdminTests likes to call Main() twice.
            TestExceptionString = null;
            Exiting             = false;
            // Clear XenConnections and History so static classes like OtherConfigAndTagsWatcher
            // listening to changes still work when Main is called more than once.
            ConnectionsManager.XenConnections.Clear();
            ConnectionsManager.History.Clear();

            Search.InitSearch(Branding.Search);
            TreeSearch.InitSearch();

            ArgType argType = ArgType.None;

            AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException -= Application_ThreadException;
            Application.ThreadException += Application_ThreadException;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            try
            {
                if (SystemInformation.FontSmoothingType == 2) // ClearType
                {
                    TransparentUsually = SystemColors.Window;
                }
            }
            catch (NotSupportedException)
            {
                // Leave TransparentUsually == Color.Transparent.  This is an old platform
                // without FontSmoothingType support.
            }

            switch (Environment.OSVersion.Version.Major)
            {
            case 6:     // Vista, 2K8, Win7.
                if (Application.RenderWithVisualStyles)
                {
                    // Vista, Win7 with styles.
                    TitleBarStartColor      = Color.FromArgb(242, 242, 242);
                    TitleBarEndColor        = Color.FromArgb(207, 207, 207);
                    TitleBarBorderColor     = Color.FromArgb(160, 160, 160);
                    TitleBarForeColor       = Color.FromArgb(60, 60, 60);
                    HeaderGradientForeColor = Color.White;
                    HeaderGradientFont      = new Font(DefaultFont.FontFamily, 11.25f);
                    HeaderGradientFontSmall = DefaultFont;
                    TabbedDialogHeaderFont  = HeaderGradientFont;
                    TabPageRowBorder        = Color.Gainsboro;
                    TabPageRowHeader        = Color.WhiteSmoke;
                }
                else
                {
                    // 2K8, and Vista, Win7 without styles.
                    TitleBarForeColor       = SystemColors.ControlText;
                    HeaderGradientForeColor = SystemColors.ControlText;
                    HeaderGradientFont      = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold);
                    HeaderGradientFontSmall = DefaultFontBold;
                    TabbedDialogHeaderFont  = HeaderGradientFont;
                    TabPageRowBorder        = Color.DarkGray;
                    TabPageRowHeader        = Color.Silver;
                }
                break;

            default:
                TitleBarStartColor      = ProfessionalColors.OverflowButtonGradientBegin;
                TitleBarEndColor        = ProfessionalColors.OverflowButtonGradientEnd;
                TitleBarBorderColor     = TitleBarEndColor;
                TitleBarForeColor       = Application.RenderWithVisualStyles ? Color.White : SystemColors.ControlText;
                HeaderGradientForeColor = TitleBarForeColor;
                HeaderGradientFont      = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold);
                HeaderGradientFontSmall = DefaultFontBold;
                TabbedDialogHeaderFont  = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1.75f, FontStyle.Bold);
                TabPageRowBorder        = Color.DarkGray;
                TabPageRowHeader        = Color.Silver;
                break;
            }

            // Force the current culture, to make the layout the same whatever the culture of the underlying OS (CA-46983).
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(InvisibleMessages.LOCALE, false);

            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
            {
                Thread.CurrentThread.Name = "Main program thread";
            }

            ServicePointManager.DefaultConnectionLimit = 20;
            ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            XenAPI.Session.UserAgent             = string.Format("XenCenter/{0}", ClientVersion());
            ReconfigureConnectionSettings();

            log.Info("Application started");
            logSystemDetails();
            OptionsDialog.Log();

            if (Args.Length > 0)
            {
                log.InfoFormat("Args[0]: {0}", Args[0]);
            }

            List <string> sanitizedArgs = new List <string>(Args);

            // Remove the '--wait' argument, which may have been passed to the splash screen
            sanitizedArgs.Remove("--wait");
            string[] args = null;
            if (sanitizedArgs.Count > 1)
            {
                argType = ParseFileArgs(sanitizedArgs, out args);

                if (argType == ArgType.Passwords)
                {
                    log.DebugFormat("Handling password request using '{0}'", args[0]);
                    try
                    {
                        PasswordsRequest.HandleRequest(args[0]);
                    }
                    catch (Exception exn)
                    {
                        log.Fatal(exn, exn);
                    }
                    Application.Exit();
                    return;
                }
            }
            else if (sanitizedArgs.Count == 1 && sanitizedArgs[0] == "messageboxtest")
            {
                new Dialogs.MessageBoxTest().ShowDialog();
                Application.Exit();
                return;
            }
            else if (sanitizedArgs.Count > 0)
            {
                log.Warn("Unrecognised command line options");
            }

            try
            {
                ConnectPipe();
            }
            catch (System.ComponentModel.Win32Exception exn)
            {
                log.Error("Creating named pipe failed. Continuing to launch XenCenter.", exn);
            }

            Application.ApplicationExit -= Application_ApplicationExit;
            Application.ApplicationExit += Application_ApplicationExit;

            MainWindow mainWindow = new MainWindow(argType, args);

            Application.Run(mainWindow);

            log.Info("Application main thread exited");
        }
Exemple #20
0
        public override void PageLeave(PageLoadedDirection direction, ref bool cancel)
        {
            if (direction == PageLoadedDirection.Back)
            {
                return;
            }

            Host master = Helpers.GetMaster(Connection);

            if (master == null)
            {
                cancel = true;
                return;
            }

            SrDescriptors = new List <LvmOhbaSrDescriptor>();

            var existingSrDescriptors = new List <LvmOhbaSrDescriptor>();
            var formatDiskDescriptors = new List <LvmOhbaSrDescriptor>();

            foreach (var device in _selectedDevices)
            {
                LvmOhbaSrDescriptor descr = CreateSrDescriptor(device);

                var action = new SrProbeAction(Connection, master, SrType, descr.DeviceConfig);
                new ActionProgressDialog(action, ProgressBarStyle.Marquee).ShowDialog(this);

                if (!action.Succeeded)
                {
                    cancel = true;
                    return;
                }

                descr.UUID = SrWizardHelpers.ExtractUUID(action.Result);

                if (!string.IsNullOrEmpty(SrWizardType.UUID))
                {
                    // Check LUN contains correct SR
                    if (descr.UUID == SrWizardType.UUID)
                    {
                        SrDescriptors.Add(descr);
                        continue;
                    }

                    using (var dlog = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(SystemIcons.Error,
                                                             String.Format(Messages.INCORRECT_LUN_FOR_SR, SrWizardType.SrName), Messages.XENCENTER)))
                    {
                        dlog.ShowDialog(this);
                    }

                    cancel = true;
                    return;
                }

                if (string.IsNullOrEmpty(descr.UUID))
                {
                    // No existing SRs were found on this LUN. If allowed to create
                    // a new SR, ask the user if they want to proceed and format.
                    if (!SrWizardType.AllowToCreateNewSr)
                    {
                        using (var dlog = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Error,
                                                                 Messages.NEWSR_LUN_HAS_NO_SRS, Messages.XENCENTER)))
                        {
                            dlog.ShowDialog(this);
                        }

                        cancel = true;
                        return;
                    }

                    if (!Program.RunInAutomatedTestMode)
                    {
                        formatDiskDescriptors.Add(descr);
                    }
                }
                else
                {
                    // CA-17230: Check this isn't a detached SR. If it is then just continue
                    SR sr = SrWizardHelpers.SrInUse(descr.UUID);
                    if (sr != null)
                    {
                        SrDescriptors.Add(descr);
                        continue;
                    }

                    // We found a SR on this LUN. Will ask user for choice later.
                    existingSrDescriptors.Add(descr);
                }
            }

            if (!cancel && existingSrDescriptors.Count > 0)
            {
                var launcher = new LVMoHBAWarningDialogLauncher(this, existingSrDescriptors, true);
                launcher.ShowWarnings();
                cancel = launcher.Cancelled;
                if (!cancel && launcher.SrDescriptors.Count > 0)
                {
                    SrDescriptors.AddRange(launcher.SrDescriptors);
                }
            }

            if (!cancel && formatDiskDescriptors.Count > 0)
            {
                var launcher = new LVMoHBAWarningDialogLauncher(this, formatDiskDescriptors, false);
                launcher.ShowWarnings();
                cancel = launcher.Cancelled;
                if (!cancel && launcher.SrDescriptors.Count > 0)
                {
                    SrDescriptors.AddRange(launcher.SrDescriptors);
                }
            }

            base.PageLeave(direction, ref cancel);
        }
        private void disableLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (poolsDataGridView.SelectedRows.Count != 1 || !(poolsDataGridView.SelectedRows[0] is PoolRow))
                return;

            var poolRow = (PoolRow)poolsDataGridView.SelectedRows[0];
            if (poolRow.Pool == null)
                return;
            var healthCheckSettings = poolRow.Pool.HealthCheckSettings;
            if (healthCheckSettings.Status == HealthCheckStatus.Enabled)
            {
                string msg = Helpers.GetPool(poolRow.Pool.Connection) == null 
                    ? Messages.CONFIRM_DISABLE_HEALTH_CHECK_SERVER 
                    : Messages.CONFIRM_DISABLE_HEALTH_CHECK_POOL;
                using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(null, msg, Messages.XENCENTER), 
                    ThreeButtonDialog.ButtonYes, ThreeButtonDialog.ButtonNo))
                {
                    if (dlg.ShowDialog(this) != DialogResult.Yes)
                        return;
                }
                healthCheckSettings.Status = HealthCheckStatus.Disabled;
                new SaveHealthCheckSettingsAction(poolRow.Pool, healthCheckSettings, null, null, null, null, false).RunAsync();
                
            }
        }
        protected override void PageLeaveCore(PageLoadedDirection direction, ref bool cancel)
        {
            if (direction == PageLoadedDirection.Forward)
            {
                if (IsInAutomatedUpdatesMode)
                {
                    var succeed = Updates.CheckForUpdatesSync(this.Parent);
                    cancel = !succeed;
                }
                else if (downloadUpdateRadioButton.Checked)
                {
                    UpdateAlertFromWeb = dataGridViewPatches.SelectedRows.Count > 0
                        ? ((PatchGridViewRow)dataGridViewPatches.SelectedRows[0]).UpdateAlert
                        : null;

                    var distinctHosts = UpdateAlertFromWeb != null ? UpdateAlertFromWeb.DistinctHosts : null;
                    SelectedUpdateType = distinctHosts != null && distinctHosts.Any(Helpers.ElyOrGreater)
                        ? UpdateType.ISO
                        : UpdateType.Legacy;

                    AlertFromFileOnDisk      = null;
                    FileFromDiskHasUpdateXml = false;
                    unzippedUpdateFilePath   = null;
                    SelectedPatchFilePath    = null;
                    PatchFromDisk            = new KeyValuePair <XenServerPatch, string>(null, null);
                }
                else
                {
                    UpdateAlertFromWeb    = null;
                    SelectedPatchFilePath = null;

                    if (!WizardHelpers.IsValidFile(FilePath, out var pathFailure))
                    {
                        using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(
                                                                   SystemIcons.Error, pathFailure, Messages.UPDATES)))
                        {
                            cancel = true;
                            dlg.ShowDialog();
                            return;
                        }
                    }

                    SelectedPatchFilePath = FilePath;

                    if (Path.GetExtension(FilePath).ToLowerInvariant().Equals(".zip"))
                    {
                        //check if we are installing the update the user sees in the textbox
                        if (unzippedUpdateFilePath == null || !File.Exists(unzippedUpdateFilePath) ||
                            Path.GetFileNameWithoutExtension(unzippedUpdateFilePath) != Path.GetFileNameWithoutExtension(FilePath))
                        {
                            unzippedUpdateFilePath = WizardHelpers.ExtractUpdate(FilePath, this);
                        }

                        if (!WizardHelpers.IsValidFile(unzippedUpdateFilePath, out var zipFailure))
                        {
                            using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(
                                                                       SystemIcons.Error, zipFailure, Messages.UPDATES)))
                            {
                                cancel = true;
                                dlg.ShowDialog();
                                return;
                            }
                        }

                        if (!unzippedFiles.Contains(unzippedUpdateFilePath))
                        {
                            unzippedFiles.Add(unzippedUpdateFilePath);
                        }

                        SelectedPatchFilePath = unzippedUpdateFilePath;
                    }
                    else
                    {
                        unzippedUpdateFilePath = null;
                    }

                    if (SelectedPatchFilePath.EndsWith("." + Branding.Update))
                    {
                        SelectedUpdateType = UpdateType.Legacy;
                    }
                    else if (SelectedPatchFilePath.EndsWith("." + Branding.UpdateIso))
                    {
                        SelectedUpdateType = UpdateType.ISO;
                    }

                    AlertFromFileOnDisk      = GetAlertFromFile(SelectedPatchFilePath, out var hasUpdateXml);
                    FileFromDiskHasUpdateXml = hasUpdateXml;
                    PatchFromDisk            = AlertFromFileOnDisk == null
                        ? new KeyValuePair <XenServerPatch, string>(null, null)
                        : new KeyValuePair <XenServerPatch, string>(AlertFromFileOnDisk.Patch, SelectedPatchFilePath);
                }
            }

            if (!cancel) //unsubscribe only if we are really leaving this page
            {
                Updates.RestoreDismissedUpdatesStarted -= Updates_RestoreDismissedUpdatesStarted;
                Updates.CheckForUpdatesStarted         -= CheckForUpdates_CheckForUpdatesStarted;
                Updates.CheckForUpdatesCompleted       -= CheckForUpdates_CheckForUpdatesCompleted;
            }
        }
Exemple #23
0
        protected override void FinishWizard()
        {
            // If the user has chosen a file that already exists, get confirmation
            string path = bugToolPageDestination1.OutputFile;

            if (File.Exists(path))
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.FILE_X_EXISTS_OVERWRITE, path), Messages.XENCENTER),
                           ThreeButtonDialog.ButtonOK,
                           new ThreeButtonDialog.TBDButton(Messages.CANCEL, DialogResult.Cancel, ThreeButtonDialog.ButtonType.CANCEL, true)))
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                if (dialogResult != DialogResult.OK)
                {
                    FinishCanceled();
                    return;
                }
            }

            // Check we can write to the destination file - otherwise we only find out at the
            // end of the ZipStatusReportAction, and the downloaded server files are lost,
            // and the user will have to run the wizard again.
            try
            {
                using (FileStream temp = File.OpenWrite(path))
                {
                    // Yay, it worked
                }
            }
            catch (Exception exn)
            {
                // Failure
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               string.Format(Messages.COULD_NOT_WRITE_FILE, path, exn.Message),
                               Messages.XENCENTER)))
                {
                    dlg.ShowDialog(this);
                }
                FinishCanceled();
                return;
            }

            // Proceed to finish the wizard and start the zip action

            // zip up the report files and save them to the chosen file
            Actions.ZipStatusReportAction action =
                new Actions.ZipStatusReportAction(bugToolPageRetrieveData.OutputFolder, bugToolPageDestination1.OutputFile);
            using (var dialog = new ActionProgressDialog(action, ProgressBarStyle.Blocks))
            {
                dialog.ShowCancel = true;
                dialog.ShowDialog();
            }

            if (!action.Succeeded)
            {
                // Close. We can't recover from a partially-completed ZipStatusReportAction.
                base.FinishWizard();
                return;
            }

            // upload the report files
            if (bugToolPageDestination1.Upload)
            {
                var uploadAction = new Actions.UploadServerStatusReportAction(bugToolPageDestination1.OutputFile,
                                                                              bugToolPageDestination1.UploadToken, bugToolPageDestination1.CaseNumber,
                                                                              Registry.HealthCheckUploadDomainName, false);
                using (var dialog = new ActionProgressDialog(uploadAction, ProgressBarStyle.Marquee)
                {
                    ShowCancel = true
                })
                    dialog.ShowDialog();
            }

            // Save away the output path for next time
            XenAdmin.Properties.Settings.Default.ServerStatusPath = bugToolPageDestination1.OutputFile;

            log.Debug("Cleaning up crash dump logs on server");
            var capabilities = bugToolPageSelectCapabilities1.Capabilities;

            foreach (Capability c in capabilities)
            {
                if (c.Key == "host-crashdump-dumps" && c.Checked)
                {
                    var hostList = bugToolPageSelectHosts1.SelectedHosts;
                    if (!hostList.Any(h => h.HasCrashDumps))
                    {
                        break;
                    }

                    DialogResult result;
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(null, Messages.REMOVE_CRASHDUMP_QUESTION, Messages.REMOVE_CRASHDUMP_FILES),
                               ThreeButtonDialog.ButtonYes,
                               ThreeButtonDialog.ButtonNo))
                    {
                        result = dlg.ShowDialog(this);
                    }
                    if (result == DialogResult.Yes)
                    {
                        foreach (Host host in hostList)
                        {
                            if (host != null && host.HasCrashDumps)
                            {
                                new Actions.DestroyHostCrashDumpAction(host).RunAsync();
                            }
                        }
                    }
                    break;
                }
            }
            base.FinishWizard();
        }
Exemple #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="vm">The VM to export.</param>
        /// <param name="host">Used for filtering purposes. May be null.</param>
        private void Execute(IXenConnection connection, VM vm, Host host)
        {
            /*
             * These properties have not been copied over to the new save file dialog.
             *
             * dlg.AddExtension = true;
             * dlg.CheckPathExists = true;
             * dlg.CreatePrompt = false;
             * dlg.CheckFileExists = false;
             * dlg.OverwritePrompt = true;
             * dlg.ValidateNames = true;*/

            string filename;
            bool   verify;

            // Showing this dialog has the (undocumented) side effect of changing the working directory
            // to that of the file selected. This means a handle to the directory persists, making
            // it undeletable until the program exits, or the working dir moves on. So, save and
            // restore the working dir...
            String oldDir = "";

            try
            {
                oldDir = Directory.GetCurrentDirectory();
                while (true)
                {
                    ExportVMDialog dlg = new ExportVMDialog();
                    dlg.DefaultExt = "xva";
                    dlg.Filter     = Messages.MAINWINDOW_XVA_BLURB;
                    dlg.Title      = Messages.MAINWINDOW_XVA_TITLE;

                    if (dlg.ShowDialog(Parent) != DialogResult.OK)
                    {
                        return;
                    }

                    filename = dlg.FileName;
                    verify   = dlg.Verify;

                    // CA-12975: Warn the user if the export operation does not have enough disk space to
                    // complete.  This is an approximation only.
                    Win32.DiskSpaceInfo diskSpaceInfo = Win32.GetDiskSpaceInfo(dlg.FileName);

                    if (diskSpaceInfo == null)
                    {
                        // Could not determine free disk space. Carry on regardless.
                        break;
                    }
                    else
                    {
                        ulong   freeSpace   = diskSpaceInfo.FreeBytesAvailable;
                        decimal neededSpace = vm.GetRecommendedExportSpace(Properties.Settings.Default.ShowHiddenVMs);
                        ulong   spaceLeft   = 100 * Util.BINARY_MEGA; // We want the user to be left with some disk space afterwards
                        if (neededSpace >= freeSpace - spaceLeft)
                        {
                            string msg = string.Format(Messages.CONFIRM_EXPORT_NOT_ENOUGH_MEMORY, Util.DiskSizeString((long)neededSpace),
                                                       Util.DiskSizeString((long)freeSpace), vm.Name);

                            DialogResult dr = new ThreeButtonDialog(
                                new ThreeButtonDialog.Details(SystemIcons.Warning, msg),
                                "ExportVmDialogInsufficientDiskSpace",
                                new ThreeButtonDialog.TBDButton(Messages.CONTINUE_WITH_EXPORT, DialogResult.OK),
                                new ThreeButtonDialog.TBDButton(Messages.CHOOSE_ANOTHER_DESTINATION, DialogResult.Retry),
                                ThreeButtonDialog.ButtonCancel).ShowDialog(Parent);

                            if (dr == DialogResult.Retry)
                            {
                                continue;
                            }
                            else if (dr == DialogResult.Cancel)
                            {
                                return;
                            }
                        }
                        if (diskSpaceInfo.IsFAT && neededSpace > (4 * Util.BINARY_GIGA) - 1)
                        {
                            string msg = string.Format(Messages.CONFIRM_EXPORT_FAT, Util.DiskSizeString((long)neededSpace),
                                                       Util.DiskSizeString(4 * Util.BINARY_GIGA), vm.Name);

                            DialogResult dr = new ThreeButtonDialog(
                                new ThreeButtonDialog.Details(SystemIcons.Warning, msg),
                                "ExportVmDialogFSLimitExceeded",
                                new ThreeButtonDialog.TBDButton(Messages.CONTINUE_WITH_EXPORT, DialogResult.OK),
                                new ThreeButtonDialog.TBDButton(Messages.CHOOSE_ANOTHER_DESTINATION, DialogResult.Retry),
                                ThreeButtonDialog.ButtonCancel).ShowDialog(Parent);

                            if (dr == DialogResult.Retry)
                            {
                                continue;
                            }
                            else if (dr == DialogResult.Cancel)
                            {
                                return;
                            }
                        }
                        break;
                    }
                }
            }
            finally
            {
                Directory.SetCurrentDirectory(oldDir);
            }

            new ExportVmAction(connection, host, vm, filename, verify).RunAsync();
        }
        public AsyncAction SaveSettings()
        {
            // Check user has entered valid params
            if (DevicePositionChanged &&
                vdi.type == vdi_type.system)
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.EDIT_SYS_DISK_WARNING,
                                                         Messages.EDIT_SYS_DISK_WARNING_TITLE),
                           ThreeButtonDialog.ButtonYes,
                           ThreeButtonDialog.ButtonNo))
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                if (DialogResult.Yes != dialogResult)
                {
                    return(null);
                }
            }

            bool     diskAccessPriorityEnabled = diskAccessPriorityTrackBar.Enabled;
            int      diskAccessPriority        = diskAccessPriorityTrackBar.Value;
            vbd_mode vbdMode        = modeComboBox.SelectedIndex == 0 ? vbd_mode.RW : vbd_mode.RO;
            string   devicePosition = DevicePosition;

            int priorityToSet = vbd.IONice;

            if (diskAccessPriorityEnabled)
            {
                priorityToSet = diskAccessPriority;
            }


            bool changeDevicePosition = false;
            VBD  other = null;

            if (devicePosition != vbd.userdevice)
            {
                foreach (VBD otherVBD in vm.Connection.ResolveAll(vm.VBDs))
                {
                    if (otherVBD.userdevice != devicePosition ||
                        vbd.opaque_ref == otherVBD.opaque_ref)
                    {
                        continue;
                    }

                    other = otherVBD;
                    break;
                }

                if (other == null)
                {
                    changeDevicePosition = true;
                }
                else
                {
                    // The selected userdevice is already in use. Ask the user what to do about this.
                    DialogResult result = new UserDeviceDialog(devicePosition).ShowDialog(this);

                    changeDevicePosition = result != DialogResult.Cancel;

                    if (result == DialogResult.No || !changeDevicePosition)
                    {
                        other = null;
                    }
                }
            }
            WarnUserSwap(vbd, other);

            return(new VbdEditAction(vbd, vbdMode, priorityToSet, changeDevicePosition, other, devicePosition, true));
        }
Exemple #26
0
        /// <summary>
        /// Attempts to install tools on several VMs
        /// </summary>
        /// <param name="vms"></param>
        /// <returns>Whether the action was launched (i.e., the user didn't Cancel)</returns>
        private bool MultipleVMExecute(List <VM> vms)
        {
            bool newDvdDrivesRequired = false;

            foreach (VM vm in vms)
            {
                if (CanExecute(vm) && vm.FindVMCDROM() == null)
                {
                    newDvdDrivesRequired = true;
                    break;
                }
            }

            if (newDvdDrivesRequired)
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.NEW_DVD_DRIVES_REQUIRED, Messages.XENCENTER),
                                                       ThreeButtonDialog.ButtonYes,
                                                       ThreeButtonDialog.ButtonNo))
                {
                    dialogResult = dlg.ShowDialog(Parent);
                }
                if (dialogResult == DialogResult.Yes)
                {
                    foreach (VM vm in vms)
                    {
                        if (CanExecute(vm) && vm.FindVMCDROM() == null)
                        {
                            CreateCdDriveAction createDriveAction = new CreateCdDriveAction(vm, true, NewDiskDialog.ShowMustRebootBoxCD, NewDiskDialog.ShowVBDWarningBox);
                            using (var dlg = new ActionProgressDialog(createDriveAction, ProgressBarStyle.Marquee))
                            {
                                dlg.ShowDialog(Parent);
                            }
                        }
                    }
                    ShowMustRebootBox();
                    return(true);
                }
            }
            else
            {
                List <IXenConnection> vmConnections = new List <IXenConnection>();
                foreach (VM vm in vms)
                {
                    vmConnections.Add(vm.Connection);
                }

                if (new InstallToolsWarningDialog(null, true, vmConnections).ShowDialog(Parent) == DialogResult.Yes)
                {
                    foreach (VM vm in vms)
                    {
                        var installToolsAction = new InstallPVToolsAction(vm, Properties.Settings.Default.ShowHiddenVMs);

                        if (vms.IndexOf(vm) == 0)
                        {
                            installToolsAction.Completed += FirstInstallToolsActionCompleted;
                        }
                        else
                        {
                            installToolsAction.Completed += InstallToolsActionCompleted;
                        }
                        installToolsAction.RunAsync();
                    }
                    return(true);
                }
            }
            return(false);
        }
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            var selectedPolicies = new List<VMPP>();
            int numberOfProtectedVMs = 0;
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                var policy = ((PolicyRow)row).VMPP;
                selectedPolicies.Add(policy);
                numberOfProtectedVMs += policy.VMs.Count;

            }
            string text = "";
            if (selectedPolicies.Count == 1)
            {
                text = String.Format(numberOfProtectedVMs == 0 ? Messages.CONFIRM_DELETE_POLICY_0 : Messages.CONFIRM_DELETE_POLICY, selectedPolicies[0].Name, numberOfProtectedVMs);
            }
            else
            {
                text = string.Format(numberOfProtectedVMs == 0 ? Messages.CONFIRM_DELETE_POLICIES_0 : Messages.CONFIRM_DELETE_POLICIES, numberOfProtectedVMs);
            }

            using (var dlg = new ThreeButtonDialog(
                    new ThreeButtonDialog.Details(SystemIcons.Warning, text, Messages.DELETE_VM_PROTECTION_TITLE),
                    ThreeButtonDialog.ButtonYes,
                    ThreeButtonDialog.ButtonNo))
            {
                if (dlg.ShowDialog(this) == DialogResult.Yes)
                    new DestroyPolicyAction(Pool.Connection, selectedPolicies).RunAsync();
            }
        }
Exemple #28
0
        internal DialogResult ShowCreationWarning()
        {
            List <PIF> pifs = BondedPIFs;

            bool will_disturb_primary   = NetworkingHelper.ContainsPrimaryManagement(pifs);
            bool will_disturb_secondary = NetworkingHelper.ContainsSecondaryManagement(pifs);

            if (will_disturb_primary && will_disturb_secondary)
            {
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               Messages.BOND_CREATE_WILL_DISTURB_BOTH,
                               Messages.BOND_CREATE)))
                {
                    dlg.ShowDialog(this);
                }

                return(DialogResult.Cancel);
            }

            if (will_disturb_primary)
            {
                Pool pool = Helpers.GetPool(Connection);
                if (pool != null && pool.ha_enabled)
                {
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Error,
                                   string.Format(Messages.BOND_CREATE_HA_ENABLED, pool.Name),
                                   Messages.BOND_CREATE)))
                    {
                        dlg.ShowDialog(this);
                    }

                    return(DialogResult.Cancel);
                }

                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.BOND_CREATE_WILL_DISTURB_PRIMARY, Messages.BOND_CREATE),
                           "BondConfigError",
                           new ThreeButtonDialog.TBDButton(Messages.BOND_CREATE_CONTINUE, DialogResult.OK),
                           ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                return(dialogResult);
            }

            if (will_disturb_secondary)
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Warning,
                               Messages.BOND_CREATE_WILL_DISTURB_SECONDARY,
                               Messages.BOND_CREATE),
                           ThreeButtonDialog.ButtonOK,
                           ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                return(dialogResult);
            }

            return(DialogResult.OK);
        }
Exemple #29
0
        /// <summary>
        /// Called with the results of an iSCSI SR.probe(), either immediately after the scan, or after the
        /// user has performed a scan, clicked 'cancel' on a dialog, and then clicked 'next' again (this
        /// avoids duplicate probing if none of the settings have changed).
        /// </summary>
        /// <returns>
        /// Whether to continue or not - wheter to format or not is stored in
        /// iScsiFormatLUN.
        /// </returns>
        private bool ExamineIscsiProbeResults(SrProbeAction action)
        {
            _srToIntroduce = null;

            if (!action.Succeeded)
            {
                Exception exn = action.Exception;
                log.Warn(exn, exn);
                Failure failure = exn as Failure;
                if (failure != null && failure.ErrorDescription[0] == "SR_BACKEND_FAILURE_140")
                {
                    errorIconAtHostOrIP.Visible  = true;
                    errorLabelAtHostname.Visible = true;
                    errorLabelAtHostname.Text    = Messages.INVALID_HOST;
                    textBoxIscsiHost.Focus();
                }
                else if (failure != null)
                {
                    errorIconAtHostOrIP.Visible  = true;
                    errorLabelAtHostname.Visible = true;
                    errorLabelAtHostname.Text    = failure.ErrorDescription.Count > 2 ? failure.ErrorDescription[2] : failure.ErrorDescription[0];
                    textBoxIscsiHost.Focus();
                }
                return(false);
            }

            try
            {
                List <SR.SRInfo> SRs = SR.ParseSRListXML(action.Result);

                if (!String.IsNullOrEmpty(SrWizardType.UUID))
                {
                    // Check LUN contains correct SR
                    if (SRs.Count == 1 && SRs[0].UUID == SrWizardType.UUID)
                    {
                        _srToIntroduce = SRs[0];
                        return(true);
                    }

                    errorIconAtTargetLUN.Visible  = true;
                    errorLabelAtTargetLUN.Visible = true;
                    errorLabelAtTargetLUN.Text    = String.Format(Messages.INCORRECT_LUN_FOR_SR, SrWizardType.SrName);

                    return(false);
                }
                else if (SRs.Count == 0)
                {
                    // No existing SRs were found on this LUN. If allowed to create new SR, ask the user if they want to proceed and format.
                    if (!SrWizardType.AllowToCreateNewSr)
                    {
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Error, Messages.NEWSR_LUN_HAS_NO_SRS, Messages.XENCENTER)))
                        {
                            dlg.ShowDialog(this);
                        }

                        return(false);
                    }
                    DialogResult result = DialogResult.Yes;
                    if (!Program.RunInAutomatedTestMode)
                    {
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.NEWSR_ISCSI_FORMAT_WARNING, this.Text),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            result = dlg.ShowDialog(this);
                        }
                    }

                    return(result == DialogResult.Yes);
                }
                else
                {
                    // There should be 0 or 1 SRs on the LUN
                    System.Diagnostics.Trace.Assert(SRs.Count == 1);

                    // CA-17230
                    // Check this isn't a detached SR
                    SR.SRInfo info = SRs[0];
                    SR        sr   = SrWizardHelpers.SrInUse(info.UUID);
                    if (sr != null)
                    {
                        DialogResult res;
                        using (var d = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(null, string.Format(Messages.DETACHED_ISCI_DETECTED, Helpers.GetName(sr.Connection))),
                                   new ThreeButtonDialog.TBDButton(Messages.ATTACH_SR, DialogResult.OK),
                                   ThreeButtonDialog.ButtonCancel))
                        {
                            res = d.ShowDialog(Program.MainWindow);
                        }

                        if (res == DialogResult.Cancel)
                        {
                            return(false);
                        }

                        _srToIntroduce = info;
                        return(true);
                    }

                    // An SR exists on this LUN. Ask the user if they want to attach it, format it and
                    // create a new SR, or cancel.
                    DialogResult result = Program.RunInAutomatedTestMode ? DialogResult.Yes :
                                          new IscsiChoicesDialog(Connection, info).ShowDialog(this);

                    switch (result)
                    {
                    case DialogResult.Yes:
                        // Reattach
                        _srToIntroduce = SRs[0];
                        return(true);

                    case DialogResult.No:
                        // Format - SrToIntroduce is already null
                        return(true);

                    default:
                        return(false);
                    }
                }
            }
            catch
            {
                // We really want to prevent the user getting to the next step if there is any kind of
                // exception here, since clicking 'finish' might destroy data: require another probe.
                return(false);
            }
        }
Exemple #30
0
        private static void ProcessUnhandledException(object sender, Exception e, bool isTerminating)
        {
            try
            {
                if (e != null)
                {
                    log.Fatal("Uncaught exception", e);
                    if (e.InnerException != null)
                    {
                        log.Fatal("Inner exception", e.InnerException);
                    }
                }
                else
                {
                    log.Fatal("Fatal error");
                }
                logSystemDetails();
                logApplicationStats();

                if (!RunInAutomatedTestMode)
                {
                    string filepath = GetLogFile();

                    ThreeButtonDialog d = new ThreeButtonDialog(
                        new ThreeButtonDialog.Details(
                            SystemIcons.Error,
                            String.Format(Messages.MESSAGEBOX_PROGRAM_UNEXPECTED, HelpersGUI.DateTimeToString(DateTime.Now, "yyyy-MM-dd HH:mm:ss", false), filepath),
                            Messages.MESSAGEBOX_PROGRAM_UNEXPECTED_TITLE));

                    // CA-44733
                    if (MainWindow != null && !IsExiting(MainWindow) && !MainWindow.InvokeRequired)
                    {
                        d.ShowDialog(MainWindow);
                    }
                    else
                    {
                        d.ShowDialog();
                    }
                }
            }
            catch (Exception exception)
            {
                try
                {
                    log.Fatal("Fatal error while handling fatal error!", exception);
                }
                catch (Exception)
                {
                }
                if (!RunInAutomatedTestMode)
                {
                    new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, exception.ToString(), Messages.XENCENTER)).ShowDialog();
                    // To be handled by WER
                    throw;
                }
            }
            if (RunInAutomatedTestMode && TestExceptionString == null)
            {
                TestExceptionString = e.GetBaseException().ToString();
            }
        }
Exemple #31
0
        internal bool CanCreateBond()
        {
            List <PIF> pifs = BondedPIFs;

            bool will_disturb_primary    = NetworkingHelper.ContainsPrimaryManagement(pifs);
            bool will_disturb_secondary  = NetworkingHelper.ContainsSecondaryManagement(pifs);
            bool will_disturb_clustering = NetworkingHelper.ContainsClusteringPif(pifs);

            // It is not allowed to bond primary and secondary interfaces together.
            if (will_disturb_primary && will_disturb_secondary)
            {
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               Messages.BOND_CREATE_WILL_DISTURB_BOTH,
                               Messages.BOND_CREATE)))
                {
                    dlg.ShowDialog(this);
                }

                return(false);
            }

            // Only primary management interface.
            // In this case, clustering interface warning is hidden if it happens to be the management interface.
            if (will_disturb_primary)
            {
                Pool pool = Helpers.GetPool(Connection);
                if (pool != null && pool.ha_enabled)
                {
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Error,
                                   string.Format(Messages.BOND_CREATE_HA_ENABLED, pool.Name()),
                                   Messages.BOND_CREATE)))
                    {
                        dlg.ShowDialog(this);
                    }

                    return(false);
                }

                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.BOND_CREATE_WILL_DISTURB_PRIMARY, Messages.BOND_CREATE),
                           "BondConfigError",
                           new ThreeButtonDialog.TBDButton(Messages.BOND_CREATE_CONTINUE, DialogResult.OK),
                           ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                return(dialogResult == DialogResult.OK);
            }

            // Only secondary interface.
            // If there is clustering interface, shows clustering warning. Otherwise, shows secondary interface warning.
            if (will_disturb_secondary)
            {
                DialogResult dialogResult;
                if (will_disturb_clustering)
                {
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Warning,
                                   Messages.BOND_CREATE_WILL_DISTURB_CLUSTERING,
                                   Messages.BOND_CREATE),
                               ThreeButtonDialog.ButtonOK,
                               ThreeButtonDialog.ButtonCancel))
                    {
                        dialogResult = dlg.ShowDialog(this);
                    }
                }

                else
                {
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Warning,
                                   Messages.BOND_CREATE_WILL_DISTURB_SECONDARY,
                                   Messages.BOND_CREATE),
                               ThreeButtonDialog.ButtonOK,
                               ThreeButtonDialog.ButtonCancel))
                    {
                        dialogResult = dlg.ShowDialog(this);
                    }
                }

                return(dialogResult == DialogResult.OK);
            }

            return(true);
        }
Exemple #32
0
        private bool AskUserIfShouldContinue()
        {
            if (!Program.RunInAutomatedTestMode && !String.IsNullOrEmpty(m_srWizardType.UUID))
            {
                if (_srToReattach == null)
                {
                    // introduce
                    if (m_srWizardType.ShowIntroducePrompt)
                    {
                        DialogResult dialogResult;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Warning, String.Format(Messages.NEWSR_MULTI_POOL_WARNING, m_srWizardType.UUID), Text),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            dialogResult = dlg.ShowDialog(this);
                        }
                        return(DialogResult.Yes == dialogResult);
                    }
                }
                else if (_srToReattach.Connection == xenConnection)
                {
                    // Reattach
                    if (m_srWizardType.ShowReattachWarning)
                    {
                        DialogResult dialogResult;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Warning, String.Format(Messages.NEWSR_MULTI_POOL_WARNING, _srToReattach.Name()), Text),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            dialogResult = dlg.ShowDialog(this);
                        }
                        return(DialogResult.Yes == dialogResult);
                    }
                }
                else
                {
                    // uuid != null
                    // _srToReattach != null
                    // _srToReattach.Server.IsDetached
                    // _srToReattach.Connection != current connection

                    // Warn user SR is already attached to other pool, and then introduce to this pool

                    DialogResult dialogResult;
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Warning,
                                   string.Format(Messages.ALREADY_ATTACHED_ELSEWHERE, _srToReattach.Name(), Helpers.GetName(xenConnection),
                                                 Text)),
                               ThreeButtonDialog.ButtonOK,
                               ThreeButtonDialog.ButtonCancel))
                    {
                        dialogResult = dlg.ShowDialog(this);
                    }
                    return(DialogResult.OK == dialogResult);
                }
            }

            return(true);
        }
Exemple #33
0
        private void ButtonLogout_Click(object sender, EventArgs e)
        {
            Program.AssertOnEventThread();
            // Double check, this method is called from a context menu as well and the state could have changed under it
            if (!ButtonLogout.Enabled)
            {
                return;
            }

            Session session = _connection.Session;

            if (session == null)
            {
                return;
            }

            var  subjectsToLogout = new List <Subject>();
            bool logSelfOut       = false;

            foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows)
            {
                if (r.IsLocalRootRow || !r.LoggedIn)
                {
                    continue;
                }

                subjectsToLogout.Add(r.subject);

                if (session.SessionSubject != null && r.subject.opaque_ref == session.SessionSubject)
                {
                    logSelfOut = true;
                }
            }

            bool suicide = false;

            if (logSelfOut)
            {
                var warnMsg = string.Format(subjectsToLogout.Count > 1 ? Messages.AD_LOGOUT_SUICIDE_MANY : Messages.AD_LOGOUT_SUICIDE_ONE,
                                            Helpers.GetName(_connection).Ellipsise(50));

                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, warnMsg, Messages.AD_FEATURE_NAME),
                           ThreeButtonDialog.ButtonYes,
                           new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                {
                    //CA-64818: DialogResult can be No if the No button has been hit
                    //or Cancel if the dialog has been closed from the control box
                    if (dlg.ShowDialog(this) != DialogResult.Yes)
                    {
                        return;
                    }

                    suicide = true;
                }
            }

            var logoutMessage = subjectsToLogout.Count == 1
                ? string.Format(Messages.QUESTION_LOGOUT_AD_USER_ONE, subjectsToLogout[0].DisplayName ?? subjectsToLogout[0].SubjectName)
                : string.Format(Messages.QUESTION_LOGOUT_AD_USER_MANY, subjectsToLogout.Count);

            if (!suicide)//CA-68645
            {
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, logoutMessage, Messages.AD_FEATURE_NAME),
                           ThreeButtonDialog.ButtonYes,
                           new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                {
                    //CA-64818: DialogResult can be No if the No button has been hit
                    //or Cancel if the dialog has been closed from the control box
                    if (dlg.ShowDialog(this) != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }

            // Then we go through the list and disconnect each user session, doing our own last if necessary
            foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows)
            {
                if (r.IsLocalRootRow || !r.LoggedIn)
                {
                    continue;
                }

                if (session.UserSid == r.subject.subject_identifier)
                {
                    continue;
                }

                new DelegatedAsyncAction(_connection,
                                         string.Format(Messages.TERMINATING_USER_SESSION, r.subject.DisplayName ?? r.subject.SubjectName),
                                         Messages.IN_PROGRESS, Messages.COMPLETED,
                                         s => Session.logout_subject_identifier(s, r.subject.subject_identifier),
                                         "session.logout_subject_identifier").RunAsync();
            }

            if (suicide)
            {
                new DisconnectCommand(Program.MainWindow, _connection, true).Execute();
            }
            else
            {
                // signal the background thread to update the logged in status
                lock (statusUpdaterLock)
                    Monitor.Pulse(statusUpdaterLock);
            }
        }
Exemple #34
0
        protected override void PageLeaveCore(PageLoadedDirection direction, ref bool cancel)
        {
            if (direction == PageLoadedDirection.Back)
            {
                return;
            }

            Host master = Helpers.GetMaster(Connection);

            if (master == null)
            {
                cancel = true;
                return;
            }

            SrDescriptors = new List <FibreChannelDescriptor>();

            var existingSrDescriptors = new List <FibreChannelDescriptor>();
            var formatDiskDescriptors = new List <FibreChannelDescriptor>();

            var performSecondProbe = Helpers.KolkataOrGreater(Connection) && !Helpers.FeatureForbidden(Connection, Host.CorosyncDisabled) &&
                                     SrType != SR.SRTypes.lvmofcoe; // gfs2 over fcoe is not supported yet

            foreach (var device in _selectedDevices)
            {
                // Start probe
                var formatDiskDescriptor = CreateSrDescriptor(device);
                List <SR.SRInfo> srs;

                var currentSrDescriptor = formatDiskDescriptor;

                if (!RunProbe(master, currentSrDescriptor, out srs))
                {
                    cancel = true;
                    return;
                }

                if (performSecondProbe && srs.Count == 0)
                {
                    // Start second probe
                    currentSrDescriptor = SrType == SR.SRTypes.gfs2 ? CreateLvmSrDescriptor(device) : CreateGfs2Descriptor(device);

                    if (!RunProbe(master, currentSrDescriptor, out srs))
                    {
                        cancel = true;
                        return;
                    }
                }

                currentSrDescriptor.UUID = srs.Select(sr => sr.UUID).FirstOrDefault();
                if (srs.Count > 0)
                {
                    currentSrDescriptor.UpdateDeviceConfig(srs[0].Configuration);
                }

                if (!string.IsNullOrEmpty(SrWizardType.UUID))
                {
                    // Check LUN contains correct SR
                    if (currentSrDescriptor.UUID == SrWizardType.UUID)
                    {
                        SrDescriptors.Add(currentSrDescriptor);
                        continue;
                    }

                    using (var dlog = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(SystemIcons.Error,
                                                             String.Format(Messages.INCORRECT_LUN_FOR_SR, SrWizardType.SrName), Messages.XENCENTER)))
                    {
                        dlog.ShowDialog(this);
                    }

                    cancel = true;
                    return;
                }

                if (string.IsNullOrEmpty(currentSrDescriptor.UUID))
                {
                    // No existing SRs were found on this LUN. If allowed to create
                    // a new SR, ask the user if they want to proceed and format.
                    if (!SrWizardType.AllowToCreateNewSr)
                    {
                        using (var dlog = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Error,
                                                                 Messages.NEWSR_LUN_HAS_NO_SRS, Messages.XENCENTER)))
                        {
                            dlog.ShowDialog(this);
                        }

                        cancel = true;
                        return;
                    }

                    if (!Program.RunInAutomatedTestMode)
                    {
                        formatDiskDescriptors.Add(formatDiskDescriptor);
                    }
                }
                else
                {
                    // Check this isn't an existing SR on the current pool
                    var existingSr = Connection.Cache.SRs.FirstOrDefault(sr => sr.uuid == currentSrDescriptor.UUID);
                    if (existingSr != null)
                    {
                        var pool      = Helpers.GetPool(existingSr.Connection);
                        var errorText = pool != null
                            ? string.Format(Messages.NEWSR_LUN_IN_USE_ON_SELECTED_POOL, device.SCSIid, existingSr.Name())
                            : string.Format(Messages.NEWSR_LUN_IN_USE_ON_SELECTED_SERVER, device.SCSIid, existingSr.Name());

                        using (var dlog = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error,
                                                                                              errorText, Messages.XENCENTER)))
                        {
                            dlog.ShowDialog(this);
                        }
                        cancel = true;
                        return;
                    }

                    // CA-17230: Check this isn't an existing SR on any of the known pools.
                    // If it is then just continue (i.e. do not ask the user if they want to format or reattach it, we will just reattach it)
                    existingSr = SrWizardHelpers.SrInUse(currentSrDescriptor.UUID);
                    if (existingSr != null)
                    {
                        SrDescriptors.Add(currentSrDescriptor);
                        continue;
                    }

                    // We found a SR on this LUN. Will ask user for choice later.
                    existingSrDescriptors.Add(currentSrDescriptor);
                }
            }

            if (!cancel && existingSrDescriptors.Count > 0)
            {
                var launcher = new LVMoHBAWarningDialogLauncher(this, existingSrDescriptors, true, SrType);
                launcher.ShowWarnings();
                cancel = launcher.Cancelled;
                if (!cancel && launcher.SrDescriptors.Count > 0)
                {
                    SrDescriptors.AddRange(launcher.SrDescriptors);
                }
            }

            if (!cancel && formatDiskDescriptors.Count > 0)
            {
                var launcher = new LVMoHBAWarningDialogLauncher(this, formatDiskDescriptors, false, SrType);
                launcher.ShowWarnings();
                cancel = launcher.Cancelled;
                if (!cancel && launcher.SrDescriptors.Count > 0)
                {
                    SrDescriptors.AddRange(launcher.SrDescriptors);
                }
            }
        }
        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            var selectedAppliances = new List<VM_appliance>();
            int numberOfProtectedVMs = 0;
            foreach (DataGridViewRow row in dataGridViewVMAppliances.SelectedRows)
            {
                var appliance = ((VMApplianceRow)row).VMAppliance;
                selectedAppliances.Add(appliance);
                numberOfProtectedVMs += appliance.VMs.Count;

            }
            string text = "";
            if (selectedAppliances.Count == 1)
            {
                if (numberOfProtectedVMs == 1)
                    text = String.Format(Messages.CONFIRM_DELETE_VM_APPLIANCE_1, selectedAppliances[0].Name.Ellipsise(120), numberOfProtectedVMs);
                else
                    text = String.Format(numberOfProtectedVMs == 0 ? Messages.CONFIRM_DELETE_VM_APPLIANCE_0 : Messages.CONFIRM_DELETE_VM_APPLIANCE, selectedAppliances[0].Name.Ellipsise(120), numberOfProtectedVMs);
            }
            else
            {
                if (numberOfProtectedVMs == 1)
                    text = String.Format(Messages.CONFIRM_DELETE_VM_APPLIANCES_1, numberOfProtectedVMs);
                else
                    text = string.Format(numberOfProtectedVMs == 0 ? Messages.CONFIRM_DELETE_VM_APPLIANCES_0 : Messages.CONFIRM_DELETE_VM_APPLIANCES, numberOfProtectedVMs);
            }

            using (var dlg = new ThreeButtonDialog(
                    new ThreeButtonDialog.Details(SystemIcons.Warning, text, Messages.DELETE_VM_APPLIANCE_TITLE),
                    ThreeButtonDialog.ButtonYes,
                    ThreeButtonDialog.ButtonNo))
            {
                if (dlg.ShowDialog(this) == DialogResult.Yes)
                    new DestroyVMApplianceAction(Pool.Connection, selectedAppliances).RunAsync();
            }
        }