protected override void ExecuteCore(SelectedItemCollection selection) { Dictionary <SelectedItem, string> reasons = new Dictionary <SelectedItem, string>(); foreach (Host host in _hosts) { PoolJoinRules.Reason reason = PoolJoinRules.CanJoinPool(host.Connection, _pool.Connection, true, true, true); if (reason != PoolJoinRules.Reason.Allowed) { reasons[new SelectedItem(host)] = PoolJoinRules.ReasonMessage(reason); } } if (reasons.Count > 0) { string title = Messages.ERROR_DIALOG_ADD_TO_POOL_TITLE; string text = string.Format(Messages.ERROR_DIALOG_ADD_TO_POOL_TEXT, Helpers.GetName(_pool).Ellipsise(500)); new CommandErrorDialog(title, text, reasons).ShowDialog(Parent); return; } if (_confirm && !ShowConfirmationDialog()) { // Bail out if the user doesn't want to continue. return; } if (!Helpers.IsConnected(_pool)) { string message = _hosts.Count == 1 ? string.Format(Messages.ADD_HOST_TO_POOL_DISCONNECTED_POOL, Helpers.GetName(_hosts[0]).Ellipsise(500), Helpers.GetName(_pool).Ellipsise(500)) : string.Format(Messages.ADD_HOST_TO_POOL_DISCONNECTED_POOL_MULTIPLE, Helpers.GetName(_pool).Ellipsise(500)); using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Error, message, Messages.XENCENTER))) { dlg.ShowDialog(Parent); } return; } // Check supp packs and warn List <string> badSuppPacks = PoolJoinRules.HomogeneousSuppPacksDiffering(_hosts, _pool); if (!HelpersGUI.GetPermissionFor(badSuppPacks, sp => true, Messages.ADD_HOST_TO_POOL_SUPP_PACK, Messages.ADD_HOST_TO_POOL_SUPP_PACKS, false, "PoolJoinSuppPacks")) { return; } // Are there any hosts which are forbidden from masking their CPUs for licensing reasons? // If so, we need to show upsell. Host master = Helpers.GetMaster(_pool); if (null != _hosts.Find(host => !PoolJoinRules.CompatibleCPUs(host, master, false) && Helpers.FeatureForbidden(host, Host.RestrictCpuMasking) && !PoolJoinRules.FreeHostPaidMaster(host, master, false))) // in this case we can upgrade the license and then mask the CPU { using (var dlg = new UpsellDialog(HiddenFeatures.LinkLabelHidden ? Messages.UPSELL_BLURB_CPUMASKING : Messages.UPSELL_BLURB_CPUMASKING + Messages.UPSELL_BLURB_CPUMASKING_MORE, InvisibleMessages.UPSELL_LEARNMOREURL_CPUMASKING)) dlg.ShowDialog(Parent); return; } // Get permission for any fix-ups: 1) Licensing free hosts; 2) CPU masking 3) Ad configuration 4) CPU feature levelling (Dundee or higher only) // (We already know that these things are fixable because we have been through CanJoinPool() above). if (!HelpersGUI.GetPermissionFor(_hosts, host => PoolJoinRules.FreeHostPaidMaster(host, master, false), Messages.ADD_HOST_TO_POOL_LICENSE_MESSAGE, Messages.ADD_HOST_TO_POOL_LICENSE_MESSAGE_MULTIPLE, true, "PoolJoinRelicensing") || !HelpersGUI.GetPermissionFor(_hosts, host => !PoolJoinRules.CompatibleCPUs(host, master, false), Messages.ADD_HOST_TO_POOL_CPU_MASKING_MESSAGE, Messages.ADD_HOST_TO_POOL_CPU_MASKING_MESSAGE_MULTIPLE, true, "PoolJoinCpuMasking") || !HelpersGUI.GetPermissionFor(_hosts, host => !PoolJoinRules.CompatibleAdConfig(host, master, false), Messages.ADD_HOST_TO_POOL_AD_MESSAGE, Messages.ADD_HOST_TO_POOL_AD_MESSAGE_MULTIPLE, true, "PoolJoinAdConfiguring") || !HelpersGUI.GetPermissionForCpuFeatureLevelling(_hosts, _pool)) { return; } MainWindowCommandInterface.SelectObjectInTree(_pool); List <AsyncAction> actions = new List <AsyncAction>(); foreach (Host host in _hosts) { string opaque_ref = host.opaque_ref; AddHostToPoolAction action = new AddHostToPoolAction(_pool, host, GetAdPrompt, NtolDialog, ApplyLicenseEditionCommand.ShowLicensingFailureDialog); action.Completed += s => Program.ShowObject(opaque_ref); actions.Add(action); // hide connection. If the action fails, re-show it. Program.HideObject(opaque_ref); } RunMultipleActions(actions, string.Format(Messages.ADDING_SERVERS_TO_POOL, _pool.Name), Messages.POOLCREATE_ADDING, Messages.POOLCREATE_ADDED, true); }
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.EXPORT_ALL_BUTTON, DialogResult.Yes), new ThreeButtonDialog.TBDButton(Messages.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, Encoding.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(); }
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)); }
/// <summary> /// In the case there was 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">vm</param> /// <param name="failure">failure, xapi exception</param> /// <param name="newNtol"></param> //private static bool StartDiagnosisForm(XenObject<VM> vm, Failure failure, string recommendationId) private bool RaiseHANotl(VM vm, Failure failure, out long newNtol) { bool error = false; newNtol = 0; if (failure.ErrorDescription[0] == Failure.NO_HOSTS_AVAILABLE) { VMOperationCommand.StartDiagnosisForm(vm, vm.power_state == vm_power_state.Halted); } 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. if (this.Pool == null) { log.ErrorFormat("Could not get pool for VM {0} in StartDiagnosisForm()", Helpers.GetName(vm)); return(error); } long ntol = this.Pool.ha_host_failures_to_tolerate; newNtol = Math.Min(this.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(Messages.HA_OPT_VM_RELOCATE_NTOL_ZERO, Helpers.GetName(this.Pool).Ellipsise(100), Helpers.GetName(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(Messages.HA_OPT_DISABLE_NTOL_DROP, Helpers.GetName(this.Pool).Ellipsise(100), ntol, Helpers.GetName(vm).Ellipsise(100), newNtol); Program.Invoke(Program.MainWindow, delegate() { 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))) { DialogResult r = dlg.ShowDialog(Program.MainWindow); if (r != DialogResult.Yes) { error = true; } } }); } } return(error); }
/// <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(SR.SRTypes currentSrType, List <SR.SRInfo> srs) { _srToIntroduce = null; if (srs == null) { return(false); } try { if (!String.IsNullOrEmpty(SrWizardType.UUID)) { // Check LUN contains correct SR if (srs.Count == 1 && srs[0].UUID == SrWizardType.UUID) { _srToIntroduce = srs[0]; SrType = currentSrType; // the type of the existing SR 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; SrType = currentSrType; // the type of the existing SR 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, currentSrType, SrType).ShowDialog(this); switch (result) { case DialogResult.Yes: // Reattach _srToIntroduce = srs[0]; SrType = currentSrType; // the type of the existing SR 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); } }
public static void Launch(string pageref) { MainWindow w = Program.MainWindow; if (pageref != null) { log.DebugFormat("User Request Help ID for {0}", pageref); string s = GetID(pageref); if (s != null) { log.DebugFormat("Help ID for {0} is {1}", pageref, s); if (Properties.Settings.Default.DebugHelp && !Program.RunInAutomatedTestMode) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Information, string.Format(Messages.MESSAGEBOX_HELP_TOPICS, s, pageref), Messages.XENCENTER))) { dlg.ShowDialog(w); } } w.ShowHelpTopic(s); } else { log.WarnFormat("Failed to find Help ID for {0}", pageref); // Do not show the help window with TOC if the help ID is not found with the system running in AutomatedTest mode if (!Program.RunInAutomatedTestMode) { if (Properties.Settings.Default.DebugHelp) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, string.Format(Messages.MESSAGEBOX_HELP_TOPIC_NOT_FOUND, pageref), Messages.MESSAGEBOX_HELP_TOPIC_NOT_FOUND))) { dlg.ShowDialog(w); } } w.ShowHelpTOC(); } } } else { log.WarnFormat("Null help ID passed to Help Manager"); // Do not show the help window with TOC if the help ID is not found with the system running in AutomatedTest mode if (!Program.RunInAutomatedTestMode) { if (Properties.Settings.Default.DebugHelp) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, string.Format(Messages.MESSAGEBOX_HELP_TOPIC_NOT_FOUND, pageref), Messages.MESSAGEBOX_HELP_TOPIC_NOT_FOUND))) { dlg.ShowDialog(w); } } w.ShowHelpTOC(); } } }
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; }
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; } }
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(); }
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); }
/// <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 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(); } }
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 formatDiskDescriptors = new Dictionary <FibreChannelDescriptor, FibreChannelDescriptor>(); // key = requested SR, value = existing SR 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, null); } } 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. formatDiskDescriptors.Add(formatDiskDescriptor, currentSrDescriptor); } } if (!cancel && formatDiskDescriptors.Count > 0) { var launcher = new LVMoHBAWarningDialogLauncher(this, formatDiskDescriptors, SrType); launcher.ShowWarnings(); cancel = launcher.Cancelled; if (!cancel && launcher.SrDescriptors.Count > 0) { SrDescriptors.AddRange(launcher.SrDescriptors); } } }
private void m_buttonAddNetwork_Click(object sender, EventArgs e) { if (m_networkGridView.Rows.Count >= m_vm.MaxVIFsAllowed) { using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details( SystemIcons.Error, FriendlyErrorNames.VIFS_MAX_ALLOWED, FriendlyErrorNames.VIFS_MAX_ALLOWED_TITLE))) { dlg.ShowDialog(Program.MainWindow); } return; } VIF vif = new VIF { Connection = m_selectedConnection }; int i = 0; while (true) { bool exists = false; foreach (DataGridViewRow row in m_networkGridView.Rows) { VifRow vifRow = row as VifRow; if (vifRow == null) { continue; } VIF v = vifRow.Vif; if (v == null) { continue; } if (int.Parse(v.device) == i) { exists = true; } } if (exists) { i++; } else { break; } } vif.device = i.ToString(); vif.MAC = Messages.MAC_AUTOGENERATE; if (GetDefaultNetwork() != null) { vif.network = new XenRef <XenAPI.Network>(GetDefaultNetwork().opaque_ref); } AddVIFRow(vif); }
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); }
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(); } }
internal static void ShowConnectingDialogError_(Form owner, IXenConnection connection, Exception error) { if (error is ExpressRestriction) { ExpressRestriction e = (ExpressRestriction)error; Program.Invoke(Program.MainWindow, delegate() { new LicenseWarningDialog(e.HostName, e.ExistingHostName).ShowDialog(owner); }); return; } if (error is Failure) { Failure f = (Failure)error; 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) { if (((XenConnection)connection).SupressErrors) { return; } WebException w = (WebException)error; 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) { ConnectionsManager.ClearCacheAndRemoveConnection(connection); if (!Program.RunInAutomatedTestMode) { ConnectionExists c = error as ConnectionExists; 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).SupressErrors) { return; } AddError(owner, connection, string.Format(Messages.ERROR_UNKNOWN, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN); } }
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(); using (var 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) { using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, exception.ToString(), Messages.XENCENTER))) { dlg.ShowDialog(); } // To be handled by WER throw; } } if (RunInAutomatedTestMode && TestExceptionString == null) { TestExceptionString = e.GetBaseException().ToString(); } }
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; } // First we check through the list to check what warning message we show List <Subject> subjectsToLogout = new List <Subject>(); foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows) { if (r.IsLocalRootRow || !r.LoggedIn) { continue; } subjectsToLogout.Add(r.subject); } bool suicide = false; // Warn if user is logging themselves out if (session.Subject != null)//have already checked session not null { var warnMsg = string.Format(subjectsToLogout.Count > 1 ? Messages.AD_LOGOUT_SUICIDE_MANY : Messages.AD_LOGOUT_SUICIDE_ONE, Helpers.GetName(_connection).Ellipsise(50)); foreach (Subject entry in subjectsToLogout) { if (entry.opaque_ref == session.Subject) { DialogResult r; 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))) { 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; } suicide = true; break; } } } 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 { DialogResult questionDialog; 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))) { 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; } } // Then we go through the list and disconnect each user session, doing our own last if necessary foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows) { // check they are not the root row and are logged in if (r.IsLocalRootRow || !r.LoggedIn) { continue; } if (session.UserSid == r.subject.subject_identifier) { continue; } DelegatedAsyncAction logoutAction = new DelegatedAsyncAction(_connection, Messages.TERMINATING_SESSIONS, Messages.IN_PROGRESS, Messages.COMPLETED, delegate(Session s) { Session.logout_subject_identifier(s, r.subject.subject_identifier); }, "session.logout_subject_identifier"); logoutAction.RunAsync(); } if (suicide) { DelegatedAsyncAction logoutAction = new DelegatedAsyncAction(_connection, Messages.TERMINATING_SESSIONS, Messages.IN_PROGRESS, Messages.COMPLETED, delegate(Session s) { Session.logout_subject_identifier(s, session.UserSid); _connection.Logout(); }, "session.logout_subject_identifier"); logoutAction.RunAsync(); } else { // signal the background thread to update the logged in status lock (statusUpdaterLock) Monitor.Pulse(statusUpdaterLock); } }
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; } var descr = new LvmObondSrDescriptor(_selectedDevices, Connection); if (this.checkBoxThin.Checked) { descr.SMConfig.Add(SrCreateAction.allocation, "thin"); } SrDescriptors = new List <LvmObondSrDescriptor>(); var existingSrDescriptors = new List <LvmObondSrDescriptor>(); var formatDiskDescriptors = new List <LvmObondSrDescriptor>(); var action = new SrProbeAction(Connection, master, SR.SRTypes.lvmobond, 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); return; } 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); //return; formatDiskDescriptors.Add(descr); } else { // We found a SR on this LUN. Will ask user for choice later. existingSrDescriptors.Add(descr); } } if (!cancel && existingSrDescriptors.Count > 0) { var launcher = new LVMoBONDWarningDialogLauncher(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 LVMoBONDWarningDialogLauncher(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 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(); } } }
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(); } }
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.Subject != null) { foreach (Subject entry in subjectsToRemove) { if (entry.opaque_ref == session.Subject) { 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); }
/// <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(); } }); } } }
/// <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; using (var d = 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)) { dr = d.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; using (var d = 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)) { dr = d.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 static bool NtolDialog(HostAbstractAction action, Pool pool, long currentNtol, long targetNtol) { bool cancel = false; Program.Invoke(Program.MainWindow, delegate() { string poolName = Helpers.GetName(pool).Ellipsise(500); string hostName = Helpers.GetName(action.Host).Ellipsise(500); string msg; if (targetNtol == 0) { string f; if (action is EvacuateHostAction) { f = Messages.HA_HOST_DISABLE_NTOL_ZERO; } else if (action is RebootHostAction) { f = Messages.HA_HOST_REBOOT_NTOL_ZERO; } else { f = Messages.HA_HOST_SHUTDOWN_NTOL_ZERO; } msg = string.Format(f, poolName, hostName); } else { string f; if (action is EvacuateHostAction) { f = Messages.HA_HOST_DISABLE_NTOL_DROP; } else if (action is RebootHostAction) { f = Messages.HA_HOST_REBOOT_NTOL_DROP; } else { f = Messages.HA_HOST_SHUTDOWN_NTOL_DROP; } msg = string.Format(f, poolName, currentNtol, hostName, targetNtol); } 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) )) { if (dlg.ShowDialog(Program.MainWindow) == DialogResult.No) { cancel = true; } } }); return(cancel); }
protected override void FinishWizard() { AsyncAction action; if (bugToolPageDestination1.Upload) { // The MultipleAction is only used as a wrapper, we will suppress its history and expose the sub-actions in the history List <AsyncAction> subActions = new List <AsyncAction>(); ZipStatusReportAction zipAction = new ZipStatusReportAction(bugToolPageRetrieveData.OutputFolder, bugToolPageDestination1.OutputFile, false); subActions.Add(zipAction); UploadServerStatusReportAction uploadAction = new UploadServerStatusReportAction(bugToolPageDestination1.OutputFile, // tmp folder bugToolPageDestination1.UploadToken, // upload token bugToolPageDestination1.CaseNumber, // case id Registry.HealthCheckUploadDomainName, // domain name false); // suppressHistory subActions.Add(uploadAction); action = new MultipleAction(null, Messages.BUGTOOL_SAVING, Messages.BUGTOOL_SAVING, Messages.COMPLETED, subActions, true); } else { action = new ZipStatusReportAction(bugToolPageRetrieveData.OutputFolder, bugToolPageDestination1.OutputFile, false); } action.RunAsync(); 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(); }
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; } AsyncAction action; if (bugToolPageDestination1.Upload) { // The MultipleAction is only used as a wrapper, we will suppress its history and expose the sub-actions in the history List <AsyncAction> subActions = new List <AsyncAction>(); ZipStatusReportAction zipAction = new ZipStatusReportAction(bugToolPageRetrieveData.OutputFolder, bugToolPageDestination1.OutputFile, false); subActions.Add(zipAction); UploadServerStatusReportAction uploadAction = new UploadServerStatusReportAction(bugToolPageDestination1.OutputFile, // tmp folder bugToolPageDestination1.UploadToken, // upload token bugToolPageDestination1.CaseNumber, // case id Registry.HealthCheckUploadDomainName, // domain name false); // suppressHistory subActions.Add(uploadAction); action = new MultipleAction(null, Messages.BUGTOOL_SAVING, Messages.BUGTOOL_SAVING, Messages.COMPLETED, subActions, true); } else { action = new ZipStatusReportAction(bugToolPageRetrieveData.OutputFolder, bugToolPageDestination1.OutputFile, false); } action.RunAsync(); // 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(); }
private void ScanForSRs(SR.SRTypes type) { var srs = new List <SR.SRInfo>(); switch (type) { case SR.SRTypes.lvmohba: var devices = FiberChannelScan(); if (devices != null && devices.Count > 0) { foreach (FibreChannelDevice device in devices) { string deviceId = string.IsNullOrEmpty(device.SCSIid) ? device.Path : device.SCSIid; var metadataSrs = ScanDeviceForSRs(SR.SRTypes.lvmohba, deviceId, new Dictionary <string, string> { { SCSIID, device.SCSIid } }); if (metadataSrs != null && metadataSrs.Count > 0) { srs.AddRange(metadataSrs); } } } AddScanResultsToDataGridView(srs, SR.SRTypes.lvmohba); break; case SR.SRTypes.lvmoiscsi: using (var dialog = new IscsiDeviceConfigDialog(Connection)) { if (dialog.ShowDialog(this) == DialogResult.OK) { Dictionary <String, String> dconf = dialog.DeviceConfig; string deviceId = string.IsNullOrEmpty(dconf[SCSIID]) ? dconf[LUNSERIAL] : dconf[SCSIID]; var metadataSrs = ScanDeviceForSRs(SR.SRTypes.lvmoiscsi, deviceId, dconf); if (metadataSrs != null && metadataSrs.Count > 0) { srs.AddRange(metadataSrs); } } else { // if the user cancels the dialog there is no need to show the "no SRs found" pop-up return; } } AddScanResultsToDataGridView(srs, SR.SRTypes.lvmoiscsi); break; } if (srs.Count == 0) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Information, Messages.DR_WIZARD_STORAGEPAGE_SCAN_RESULT_NONE, Messages.XENCENTER))) { dlg.ShowDialog(this); } } }
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("." + BrandManager.ExtensionUpdate)) { SelectedUpdateType = UpdateType.Legacy; } else if (SelectedPatchFilePath.EndsWith("." + InvisibleMessages.ISO_UPDATE)) { 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; } }
protected sealed override void ExecuteCore(SelectedItemCollection selection) { //It only supports one item selected for now Trace.Assert(selection.Count == 1); XenAPI.Network network = (XenAPI.Network)selection.FirstAsXenObject; List <PIF> pifs = network.Connection.ResolveAll(network.PIFs); if (pifs.Count == 0) { // Should never happen as long as the caller is enabling the button correctly, but // it's possible in a tiny window across disconnecting. log.Error("Network has no PIFs"); return; } // We just want one, so that we can name it. PIF pif = pifs[0]; string msg = string.Format(Messages.DELETE_BOND_MESSAGE, pif.Name()); bool will_disturb_primary = NetworkingHelper.ContainsPrimaryManagement(pifs); bool will_disturb_secondary = NetworkingHelper.ContainsSecondaryManagement(pifs); if (will_disturb_primary) { Pool pool = Helpers.GetPool(network.Connection); if (pool != null && pool.ha_enabled) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, string.Format(Messages.BOND_DELETE_HA_ENABLED, pif.Name(), pool.Name()), Messages.DELETE_BOND))) { dlg.ShowDialog(Parent); } return; } string message = string.Format(will_disturb_secondary ? Messages.BOND_DELETE_WILL_DISTURB_BOTH : Messages.BOND_DELETE_WILL_DISTURB_PRIMARY, msg); DialogResult result; using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, message, Messages.DELETE_BOND), "NetworkingConfigWarning", new ThreeButtonDialog.TBDButton(Messages.BOND_DELETE_CONTINUE, DialogResult.OK), ThreeButtonDialog.ButtonCancel)) { result = dlg.ShowDialog(Parent); } if (DialogResult.OK != result) { return; } } else if (will_disturb_secondary) { DialogResult dialogResult; using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.BOND_DELETE_WILL_DISTURB_SECONDARY, msg), Messages.XENCENTER), ThreeButtonDialog.ButtonOK, ThreeButtonDialog.ButtonCancel)) { dialogResult = dlg.ShowDialog(Parent); } if (DialogResult.OK != dialogResult) { return; } } else { DialogResult dialogResult; using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.XENCENTER), new ThreeButtonDialog.TBDButton(Messages.OK, DialogResult.OK, ThreeButtonDialog.ButtonType.ACCEPT, true), ThreeButtonDialog.ButtonCancel)) { dialogResult = dlg.ShowDialog(Parent); } if (DialogResult.OK != dialogResult) { return; } } // The UI shouldn't offer deleting a bond in this case, but let's make sure we've // done the right thing and that the bond hasn't been deleted in the meantime. (CA-27436). Bond bond = pif.BondMasterOf(); if (bond != null) { new Actions.DestroyBondAction(bond).RunAsync(); } }
private void RelocateVmWithHa(AsyncAction action, VM vm, Host host, int start, int end, int recommendationId) { bool setDoNotRestart = false; if (vm.HaPriorityIsRestart()) { try { XenAPI.VM.assert_agile(action.Session, vm.opaque_ref); } catch (Failure) { // VM is not agile, but it is 'Protected' by HA. This is an inconsistent state (see CA-20820). // Tell the user the VM will be started without HA protection. Program.Invoke(Program.MainWindow, delegate() { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Warning, String.Format(Messages.HA_INVALID_CONFIG_RESUME, Helpers.GetName(vm).Ellipsise(500)), Messages.HIGH_AVAILABILITY))) { dlg.ShowDialog(Program.MainWindow); } }); // Set the VM to 'Do not restart'. XenAPI.VM.set_ha_restart_priority(action.Session, vm.opaque_ref, XenAPI.VM.RESTART_PRIORITY_DO_NOT_RESTART); setDoNotRestart = true; } } if (!setDoNotRestart && vm.HasSavedRestartPriority()) { // If HA is turned on, setting ha_always_run will cause the VM to be started by itself // but when the VM fails to start we want to know why, so we do a VM.start here too. // This will fail with a power state exception if HA has already started the VM - but in // that case we don't care, since the VM successfully started already. SetHaProtection(true, action, vm, start, end); try { DoAction(action, vm, host, start, end, recommendationId); } catch (Failure f) { if (f.ErrorDescription.Count == 4 && f.ErrorDescription[0] == Failure.VM_BAD_POWER_STATE && f.ErrorDescription[3] == "running") { // The VM started successfully via HA } else { throw; } } } else { // HA off: just do a regular start DoAction(action, vm, host, start, end, recommendationId); } }
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())); using (var dlg = 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 }) { dlg.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"); }
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; } }
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(); } }