public EmailCommand (string name, string address, AsyncAction action = null) : base (name, action) { Address = address; Subject = ""; BodyHtml = ""; }
public EmailSupportCommand (string name, string address, AsyncAction action = null) : base (name, address, action) { var mainBundle = NSBundle.MainBundle; var dev = UIDevice.CurrentDevice; var scr = UIScreen.MainScreen; var appName = mainBundle.ObjectForInfoDictionary ("CFBundleDisplayName"); var version = mainBundle.ObjectForInfoDictionary ("CFBundleVersion"); Subject = appName + " Feedback (" + dev.SystemName + ")"; var sb = new System.Text.StringBuilder(); sb.AppendFormat ("<br/><br/><ul>"); sb.AppendFormat ("<li>Software: <b>{0} {1}</b></li>", appName, version); sb.AppendFormat ("<li>Model: <b>{0}</b></li>", dev.Model); sb.AppendFormat ("<li>Screen: <b>{0}x{1} @{2}x</b></li>", scr.Bounds.Width, scr.Bounds.Height, scr.Scale); sb.AppendFormat ("<li>System: <b>{0} {1}</b></li>", dev.SystemName, dev.SystemVersion); sb.AppendFormat ("<li>Culture: <b>{0}</b></li>", System.Globalization.CultureInfo.CurrentCulture.EnglishName); sb.AppendFormat ("</ul>"); BodyHtml = sb.ToString (); }
public static void Invoke(Form form, AsyncAction action) { if (!form.InvokeRequired) { action(); } else { form.Invoke((DispatcherInvoker)Invoke, form, action); } }
/// <summary> /// Enables or disables HA protection for a VM (VM.ha_always_run). Also does a pool.sync_database afterwards. /// May throw a XenAPI.Failure. /// </summary> /// <param name="protect"></param> /// <param name="act"></param> /// <param name="session"></param> /// <param name="vm"></param> /// <param name="start"></param> /// <param name="end"></param> protected static void SetHaProtection(bool protect, AsyncAction action, VM vm, int start, int end) { if (!Helpers.BostonOrGreater(vm.Connection)) { // Enable or disable HA protection for the VM. XenAPI.VM.set_ha_always_run(action.Session, vm.opaque_ref, protect); } // Do database sync. Helps to ensure that the change persists over master failover. action.RelatedTask = XenAPI.Pool.async_sync_database(action.Session); action.PollToCompletion(start, end); }
public ScheduleTask RegisterTask(AsyncAction task, TaskMoment moment, bool repeat = true) { var momentInfo = moment.GetInfo(); var scheduleTask = new ScheduleTask { LastExecuted = momentInfo.Item1, AsyncAction = task, Frequency = momentInfo.Item2, Repeat = repeat }; AddScheduleTask(scheduleTask); return scheduleTask; }
protected void Run(Func<object, object> action, Action<object> callback, object argument) { var asyncAction = new AsyncAction { Action = action, Callback = callback, Argument = argument }; if (_worker.IsBusy || _queue.Count > 0) { _queue.Enqueue(asyncAction); } else { _worker.RunWorkerAsync(asyncAction); } }
private void RunAsyncInternal(AsyncAction action) { pnlLog.Visible = true; CurrentError = string.Empty; var parameter = GetParameters(); ctlAsyncLog.RunAsync(p => action(parameter), WindowsIdentity.GetCurrent()); }
/// <summary> /// Method that creates the various task using the FRomAsync methods /// </summary> /// <returns></returns> private AsyncWork RunAPMTest() { switch (_api) { case API.APM: if (_sourceType == TaskType.Task) { if (_fromAsyncType == TaskType.Task) { AsyncAction action = new AsyncAction(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync((Func<AsyncCallback, object, IAsyncResult>)null, action.EndInvoke, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync(action.BeginInvoke, null, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync(action.BeginInvoke, action.EndInvoke, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync(action.BeginInvoke, action.EndInvoke, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM"); } } return action; } else // must be FromAsync type of TaskType_FromAsync.TaskT { AsyncFunc func = new AsyncFunc(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync<ReadOnlyCollection<object>>((Func<AsyncCallback, object, IAsyncResult>)null, func.EndInvoke, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync<ReadOnlyCollection<object>>(func.BeginInvoke, null, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync<ReadOnlyCollection<object>>(func.BeginInvoke, func.EndInvoke, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync<ReadOnlyCollection<object>>(func.BeginInvoke, func.EndInvoke, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM"); } } return func; } } else // must be TaskType_FromAsync.TaskT { AsyncFunc func = new AsyncFunc(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task<ReadOnlyCollection<object>>.Factory.FromAsync((Func<AsyncCallback, object, IAsyncResult>)null, func.EndInvoke, null); else if (_errorCase == ErrorCase.NullEnd) Task<ReadOnlyCollection<object>>.Factory.FromAsync(func.BeginInvoke, null, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func.BeginInvoke, func.EndInvoke, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func.BeginInvoke, func.EndInvoke, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM"); } } return func; } case API.APM_T: _expectedInputs.Add(TestInteger); if (_sourceType == TaskType.Task) { if (_fromAsyncType == TaskType.Task) { AsyncAction<int> action1 = new AsyncAction<int>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync((Func<int, AsyncCallback, object, IAsyncResult>)null, action1.EndInvoke, TestInteger, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync(action1.BeginInvoke, null, TestInteger, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync(action1.BeginInvoke, action1.EndInvoke, TestInteger, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync(action1.BeginInvoke, action1.EndInvoke, TestInteger, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T"); } } return action1; } else // must be FromAsync type of TaskType_FromAsync.TaskT { AsyncFunc<int> func1 = new AsyncFunc<int>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync<int, ReadOnlyCollection<object>>((Func<int, AsyncCallback, object, IAsyncResult>)null, func1.EndInvoke, TestInteger, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync<int, ReadOnlyCollection<object>>(func1.BeginInvoke, null, TestInteger, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync<int, ReadOnlyCollection<object>>(func1.BeginInvoke, func1.EndInvoke, TestInteger, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync<int, ReadOnlyCollection<object>>(func1.BeginInvoke, func1.EndInvoke, TestInteger, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T"); } } return func1; } } else // must be TaskType_FromAsync.TaskT { AsyncFunc<int> func1 = new AsyncFunc<int>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task<ReadOnlyCollection<object>>.Factory.FromAsync((Func<int, AsyncCallback, object, IAsyncResult>)null, func1.EndInvoke, TestInteger, null); else if (_errorCase == ErrorCase.NullEnd) Task<ReadOnlyCollection<object>>.Factory.FromAsync(func1.BeginInvoke, null, TestInteger, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func1.BeginInvoke, func1.EndInvoke, TestInteger, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func1.BeginInvoke, func1.EndInvoke, TestInteger, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T"); } } return func1; } case API.APM_T2: //Two variables _expectedInputs.Add(TestInteger); _expectedInputs.Add(TestDouble); if (_sourceType == TaskType.Task) { if (_fromAsyncType == TaskType.Task) { AsyncAction<int, double> action2 = new AsyncAction<int, double>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync((Func<int, double, AsyncCallback, object, IAsyncResult>)null, action2.EndInvoke, TestInteger, TestDouble, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync(action2.BeginInvoke, null, TestInteger, TestDouble, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync(action2.BeginInvoke, action2.EndInvoke, TestInteger, TestDouble, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync(action2.BeginInvoke, action2.EndInvoke, TestInteger, TestDouble, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T2"); } } return action2; } else // must be FromAsync type of TaskType_FromAsync.TaskT { AsyncFunc<int, double> func2 = new AsyncFunc<int, double>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync<int, double, ReadOnlyCollection<object>>((Func<int, double, AsyncCallback, object, IAsyncResult>)null, func2.EndInvoke, TestInteger, TestDouble, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync<int, double, ReadOnlyCollection<object>>(func2.BeginInvoke, null, TestInteger, TestDouble, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync<int, double, ReadOnlyCollection<object>>(func2.BeginInvoke, func2.EndInvoke, TestInteger, TestDouble, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync<int, double, ReadOnlyCollection<object>>(func2.BeginInvoke, func2.EndInvoke, TestInteger, TestDouble, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T2"); } } return func2; } } else // must be TaskType_FromAsync.TaskT { AsyncFunc<int, double> func2 = new AsyncFunc<int, double>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task<ReadOnlyCollection<object>>.Factory.FromAsync((Func<int, double, AsyncCallback, object, IAsyncResult>)null, func2.EndInvoke, TestInteger, TestDouble, null); else if (_errorCase == ErrorCase.NullEnd) Task<ReadOnlyCollection<object>>.Factory.FromAsync(func2.BeginInvoke, null, TestInteger, TestDouble, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func2.BeginInvoke, func2.EndInvoke, TestInteger, TestDouble, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func2.BeginInvoke, func2.EndInvoke, TestInteger, TestDouble, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T2"); } } return func2; } case API.APM_T3: _expectedInputs.Add(TestInteger); _expectedInputs.Add(TestDouble); _expectedInputs.Add(TestBoolean); if (_sourceType == TaskType.Task) { if (_fromAsyncType == TaskType.Task) { AsyncAction<int, double, bool> action3 = new AsyncAction<int, double, bool>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync((Func<int, double, bool, AsyncCallback, object, IAsyncResult>)null, action3.EndInvoke, TestInteger, TestDouble, TestBoolean, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync(action3.BeginInvoke, null, TestInteger, TestDouble, TestBoolean, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync(action3.BeginInvoke, action3.EndInvoke, TestInteger, TestDouble, TestBoolean, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync(action3.BeginInvoke, action3.EndInvoke, TestInteger, TestDouble, TestBoolean, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T3"); } } return action3; } else // must be FromAsync type of TaskType_FromAsync.TaskT { AsyncFunc<int, double, bool> func3 = new AsyncFunc<int, double, bool>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync<int, double, bool, ReadOnlyCollection<object>>((Func<int, double, bool, AsyncCallback, object, IAsyncResult>)null, func3.EndInvoke, TestInteger, TestDouble, TestBoolean, null); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync<int, double, bool, ReadOnlyCollection<object>>(func3.BeginInvoke, null, TestInteger, TestDouble, TestBoolean, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync<int, double, bool, ReadOnlyCollection<object>>(func3.BeginInvoke, func3.EndInvoke, TestInteger, TestDouble, TestBoolean, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync<int, double, bool, ReadOnlyCollection<object>>(func3.BeginInvoke, func3.EndInvoke, TestInteger, TestDouble, TestBoolean, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T3"); } } return func3; } } else // must be TaskType_FromAsync.TaskT { AsyncFunc<int, double, bool> func3 = new AsyncFunc<int, double, bool>(_errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task<ReadOnlyCollection<object>>.Factory.FromAsync((Func<int, double, bool, AsyncCallback, object, IAsyncResult>)null, func3.EndInvoke, TestInteger, TestDouble, TestBoolean, null); else if (_errorCase == ErrorCase.NullEnd) Task<ReadOnlyCollection<object>>.Factory.FromAsync(func3.BeginInvoke, null, TestInteger, TestDouble, TestBoolean, null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func3.BeginInvoke, func3.EndInvoke, TestInteger, TestDouble, TestBoolean, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }); break; case OverloadChoice.WithTaskOption: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func3.BeginInvoke, func3.EndInvoke, TestInteger, TestDouble, TestBoolean, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for APM_T3"); } } return func3; } case API.IAsyncResult: // put the current params into the expectedInputs object[] inputs = new object[] { _api, _sourceType, _errorCase }; _expectedInputs.AddRange(inputs); if (_sourceType == TaskType.Task) { if (_fromAsyncType == TaskType.Task) { AsyncAction action = new AsyncAction(inputs, _errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync((IAsyncResult)null, action.EndInvoke); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync(action.BeginInvoke(null, null), null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync(action.BeginInvoke(null, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }), action.EndInvoke); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync(action.BeginInvoke(null, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }), action.EndInvoke, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for IAsyncResult"); } } return action; } else // must be FromAsync type of TaskType_FromAsync.TaskT { AsyncFunc func = new AsyncFunc(inputs, _errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task.Factory.FromAsync<ReadOnlyCollection<object>>((IAsyncResult)null, func.EndInvoke); else if (_errorCase == ErrorCase.NullEnd) Task.Factory.FromAsync<ReadOnlyCollection<object>>(func.BeginInvoke(null, null), null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task.Factory.FromAsync<ReadOnlyCollection<object>>(func.BeginInvoke(null, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }), func.EndInvoke); break; case OverloadChoice.WithTaskOption: _task = Task.Factory.FromAsync<ReadOnlyCollection<object>>(func.BeginInvoke(null, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }), func.EndInvoke, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for IAsyncResult"); } } return func; } } else // must be TaskType_FromAsync.TaskT { AsyncFunc func = new AsyncFunc(inputs, _errorCase == ErrorCase.Throwing); if (_errorCase == ErrorCase.NullBegin) Task<ReadOnlyCollection<object>>.Factory.FromAsync((IAsyncResult)null, func.EndInvoke); else if (_errorCase == ErrorCase.NullEnd) Task<ReadOnlyCollection<object>>.Factory.FromAsync(func.BeginInvoke(null, null), null); else { switch (_overloadChoice) { case OverloadChoice.None: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func.BeginInvoke(null, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TaskCreationOptions.None }), func.EndInvoke); break; case OverloadChoice.WithTaskOption: _task = Task<ReadOnlyCollection<object>>.Factory.FromAsync(func.BeginInvoke(null, new TaskOptionAndScheduler { Scheduler = TaskScheduler.Default, Option = TestOption }), func.EndInvoke, TestOption); break; default: throw new ArgumentOutOfRangeException("invalid overloadChoice for IAsyncResult"); } } return func; } default: throw new ArgumentException("unknown api to test"); } }
private void btnOK_Click(object sender, EventArgs e) { if (!ValidToSave) { // Keep dialog open and allow user to correct the error as // indicated by the balloon tooltip. DialogResult = DialogResult.None; return; } // Have any of the fields in the tab pages changed? if (!HasChanged) { Close(); return; } // Yes, save to the LocalXenObject. List <AsyncAction> actions = SaveSettings(); Program.Invoke(Program.MainWindow.GeneralPage, Program.MainWindow.GeneralPage.UpdateButtons); // Add a save changes on the beginning of the actions to enact the alterations that were just changes to the xenObjectCopy. // Must come first because some pages' SaveChanges() rely on modifying the object via the xenObjectCopy before their actions are run. if (xenObjectBefore is VMSS) { XenAPI.VMSS VMSSObj = xenObjectBefore as XenAPI.VMSS; if (VMSSObj.type == vmss_type.snapshot_with_quiesce) { actions.Insert(0, new SaveChangesAction(xenObjectCopy, xenObjectBefore, true)); } else { actions.Insert(actions.Count, new SaveChangesAction(xenObjectCopy, xenObjectBefore, true)); } } else { actions.Insert(0, new SaveChangesAction(xenObjectCopy, xenObjectBefore, true)); } var objName = Helpers.GetName(xenObject).Ellipsise(50); _action = new MultipleAction( connection, string.Format(Messages.UPDATE_PROPERTIES, objName), Messages.UPDATING_PROPERTIES, string.Format(Messages.UPDATED_PROPERTIES, objName), actions); _action.SetObject(xenObjectCopy); _action.Completed += action_Completed; Close(); if (_startAction) { _action.RunAsync(); } }
public static void InitCasc(AsyncAction bgAction = null, string basedir = null, string program = "wowt") { CASC.bgAction = bgAction; //bgAction.ProgressChanged += new EventHandler<AsyncActionProgressChangedEventArgs>(bgAction_ProgressChanged); if (basedir == null) { Console.WriteLine("Initializing CASC from web with program " + program); cascHandler = CASCHandler.OpenOnlineStorage(program, bgAction); } else { Console.WriteLine("Initializing CASC from local disk with basedir " + basedir); cascHandler = CASCHandler.OpenLocalStorage(basedir, bgAction); } cascHandler.Root.SetFlags(LocaleFlags.enUS, ContentFlags.None, false); fIsCASCInit = true; }
/// <summary> /// Migrate vm and log recommendation id for reporting purpose /// </summary> /// <param name="action">AsyncAction</param> /// <param name="vm">VM that needs to be migrated</param> /// <param name="host">Host that vm will migrate to</param> /// <param name="start">progress bar start point</param> /// <param name="end">progress bar end point</param> /// <param name="recommendationId">recommendation id</param> private static void DoAction(AsyncAction action, VM vm, Host host, int start, int end, int recommendationId) { action.RelatedTask = XenAPI.VM.async_live_migrate(action.Session, vm.opaque_ref, host.opaque_ref); if (recommendationId != 0) { // set vm migrate task key values for wlb reporting purpose Task.add_to_other_config(action.Session, action.RelatedTask.opaque_ref, "wlb_advised", recommendationId.ToString()); Task.add_to_other_config(action.Session, action.RelatedTask.opaque_ref, "wlb_action", "vm_migrate"); Task.add_to_other_config(action.Session, action.RelatedTask.opaque_ref, "wlb_action_obj_ref", vm.opaque_ref); Task.add_to_other_config(action.Session, action.RelatedTask.opaque_ref, "wlb_action_obj_type", "vm"); } action.PollToCompletion(start, end); }
public ScheduleTask RegisterTask(AsyncAction action, TimeSpan frequency, bool repeat = true) { var scheduleTask = new ScheduleTask { LastExecuted = DateTime.Now, AsyncAction = action, Frequency = frequency, Repeat = repeat }; AddScheduleTask(scheduleTask); return scheduleTask; }
public CopyToClipboardCommand (string name, string text, AsyncAction action = null) : base (name, action) { Text = text; }
public OpenUrlCommand(string name, string url, AsyncAction action = null) : base(name, action) { Url = url; }
public CopyToClipboardCommand(string name, string text, AsyncAction action = null) : base(name, action) { Text = text; }
public void UpdateSolutionAction(AsyncAction action) { this.solutionAction = action; this.error = hasSolutionActionInProgress() ? Messages.EVACUATE_SOLUTION_IN_PROGRESS : ""; Update(); }
/// <summary> /// Runs asynchronous thread /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
public static void AsWorkingProcessForm(AsyncAction action) { Invoke(Program.WorkingProcessForm, action); }
public static void AsLoadingForm(AsyncAction action) { Invoke(Program.LoadingForm, action); }
private void PrepareUploadActions() { OnPageUpdated(); SuppPackVdis.Clear(); uploadActions.Clear(); //Upload the patches to the masters if it is necessary List <Host> masters = SelectedMasters; foreach (Host selectedServer in masters) { AsyncAction action = null; switch (SelectedUpdateType) { case UpdateType.NewRetail: if (CanUploadUpdateOnHost(SelectedNewPatchPath, selectedServer)) { bool deleteFileOnCancel = AllDownloadedPatches.ContainsValue(SelectedNewPatchPath); action = new UploadPatchAction(selectedServer.Connection, SelectedNewPatchPath, true, deleteFileOnCancel); AddToUploadedUpdates(SelectedNewPatchPath, selectedServer); } break; case UpdateType.Existing: if (!PatchExistsOnPool(_patch, selectedServer)) { //Download patch from server Upload in the selected server action = new CopyPatchFromHostToOther(SelectedExistingPatch.Connection, selectedServer, SelectedExistingPatch); } break; case UpdateType.NewSuppPack: if (CanUploadUpdateOnHost(SelectedNewPatchPath, selectedServer)) { action = new UploadSupplementalPackAction( selectedServer.Connection, SelectedServers.Where(s => s.Connection == selectedServer.Connection).ToList(), SelectedNewPatchPath, true); AddToUploadedUpdates(SelectedNewPatchPath, selectedServer); } break; } if (action != null) { action.Changed += singleAction_Changed; action.Completed += singleAction_Completed; } else { _patch = GetPatchFromPatchPath(); } uploadActions.Add(selectedServer, action); } foreach (KeyValuePair <Host, AsyncAction> uploadAction in uploadActions) { flickerFreeListBox1.Items.Add(uploadAction); } flickerFreeListBox1.Refresh(); OnPageUpdated(); }
private void ShowDialog(Task task) { var asyncAction = new AsyncAction(task, this); ShowDialog(asyncAction); }
/// <summary> /// Build optimize pool list view properly /// </summary> private void BuildRecList() { Program.AssertOnEventThread(); if (_xenObject == null) { return; } if (Helpers.WlbEnabled(_xenObject.Connection)) { try { if (_xenObject is Pool) { _pool = (Pool)_xenObject; // get any active WLB action action = HelpersGUI.FindActiveWLBAction(_xenObject.Connection); // make sure we are not initializing, starting or stopping WLB if (action is DisableWLBAction || action is EnableWLBAction || action is InitializeWLBAction) { return; } optimizePoolListView.BeginUpdate(); // check whether optimize pool is running before load optimize pool listview if ((action != null && action is WlbOptimizePoolAction) || (action == null && _pool.other_config.ContainsKey(WlbOptimizationRecommendation.OPTIMIZINGPOOL) && _pool.other_config[WlbOptimizationRecommendation.OPTIMIZINGPOOL] == Messages.IN_PROGRESS)) { //statusLabel.Text = Messages.WLB_OPT_OPTIMIZING; this.applyButton.Text = Messages.WLB_OPT_OPTIMIZING; EnableControls(false, false); } else if (action == null || (action != null && action.GetType() != typeof(WlbRetrieveRecommendationAction))) { this.applyButton.Text = Messages.WLB_OPT_APPLY_RECOMMENDATIONS; // retrieve recommendations, and load optimize pool listview properly WlbRetrieveRecommendationAction optAction = new WlbRetrieveRecommendationAction(_pool); optAction.Completed += this.OptRecRetrieveAction_Completed; optAction.RunAsync(); } } } catch (Failure f) { statusLabel.Text = Messages.WLB_OPT_LOADING_ERROR; log.Error(f, f); } catch (Exception e) { statusLabel.Text = Messages.WLB_OPT_LOADING_ERROR; log.ErrorFormat("There was an error calling retrieve_wlb_recommendations on pool {0}", _pool.name_label); log.Error(e, e); } finally { optimizePoolListView.EndUpdate(); } } else { this.WLBOptDisable(true); } }
/// <summary> /// Enables or disables HA protection for a VM (VM.ha_always_run). Also does a pool.sync_database afterwards. /// Does nothing if the server is a build before ha_always_run was introduced. /// May throw a XenAPI.Failure. /// </summary> /// <param name="protect">true if vm is protected</param> /// <param name="action">AsyncAction</param> /// <param name="vm">vm</param> /// <param name="start">progress bar start point</param> /// <param name="end">progress bar end point</param> private static void SetHaProtection(bool protect, AsyncAction action, VM vm, int start, int end) { // Do database sync. Helps to ensure that the change persists over master failover. action.RelatedTask = XenAPI.Pool.async_sync_database(action.Session); action.PollToCompletion(start, end); }
/// <summary> /// HTTP GET file from HTTP action f, saving it to path (via a temporary file). /// </summary> /// <param name="action">Action on which to update the progress</param> /// <param name="timeout">Whether to apply a timeout</param> /// <param name="path">Path to save file to.</param> /// <returns>Result of the task used to GET the file</returns> public static String Get(AsyncAction action, bool timeout, string path, string hostname, Delegate f, params object[] p) { return Get(action, timeout, null, path, hostname, f, p); }
public static void AsMainForm(AsyncAction action) { Invoke(Program.MainForm, action); }
// // The following functions do puts and gets to and from the filesystem // updating Actions etc where appropriate. // /// <summary> /// HTTP PUT file from path to HTTP action f, updating action with progress every 500ms. /// </summary> /// <param name="action">Action on which to update the progress</param> /// <param name="timeout">Whether to apply a timeout</param> /// <param name="path">path of file to put</param> public static String Put(AsyncAction action, bool timeout, string path, string hostname, Delegate f, params object[] p) { return Put(action, XenAdminConfigManager.Provider.GetProxyTimeout(timeout), path, hostname, f, p); }
/// <summary> /// Runs async thread. /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { pnlLog.Visible = true; pnlInfo.Visible = false; CurrentLog.Close(); CurrentError = string.Empty; CurrentInfo = string.Empty; AddScript("InitializeLog();"); // Ensure current user SessionHelper.SetValue("CurrentUser", CurrentUser); ctlAsync.Parameter = HttpContext.Current; ctlAsync.RunAsync(action, WindowsIdentity.GetCurrent()); }
private void TryUploading() { // reset progress bar and action progress description UpdateActionProgress(null); // Check if we can upload the patches to the masters if it is necessary. // This check is only available for Cream or greater hosts. // If we can upload (i.e. there is enough disk space) then start the upload. // Otherwise display error. canUpload = true; diskSpaceRequirements = null; var diskSpaceActions = new List <AsyncAction>(); foreach (Host master in SelectedMasters.Where(master => Helpers.CreamOrGreater(master.Connection))) { AsyncAction action = null; switch (SelectedUpdateType) { case UpdateType.NewRetail: action = new CheckDiskSpaceForPatchUploadAction(master, SelectedNewPatch, true); break; case UpdateType.Existing: if (SelectedExistingPatch != null && !PatchExistsOnPool(SelectedExistingPatch, master)) { action = new CheckDiskSpaceForPatchUploadAction(master, SelectedExistingPatch, true); } break; } if (action != null) { action.Changed += delegate { Program.Invoke(Program.MainWindow, () => UpdateActionDescription(action)); }; diskSpaceActions.Add(action); } } if (diskSpaceActions.Count == 0) { StartUploading(); return; } using (var multipleAction = new MultipleAction(Connection, "", "", "", diskSpaceActions, true, true, true)) { multipleAction.Completed += delegate { Program.Invoke(Program.MainWindow, () => { if (multipleAction.Exception is NotEnoughSpaceException) { canUpload = false; diskSpaceRequirements = (multipleAction.Exception as NotEnoughSpaceException).DiskSpaceRequirements; } UpdateButtons(); OnPageUpdated(); if (canUpload) { StartUploading(); } }); }; multipleAction.RunAsync(); } }
/// <summary> /// Executes given action asynchronously /// </summary> /// <param name="action">Action to run</param> protected override void RunAsync(AsyncAction action) { base.RunAsync(action); pnlLog.Visible = true; plcContent.Visible = false; }
private void UpdateActionProgress(AsyncAction action) { UpdateActionDescription(action); progressBar1.Value = action == null ? 0 : action.PercentComplete; }
/// <summary> /// Rebuilds the panel contents. Must be called on the event thread. /// </summary> private void Rebuild() { Program.AssertOnEventThread(); if (!this.Visible) { return; } customListPanel.BeginUpdate(); try { customListPanel.ClearRows(); tableLatencies.Controls.Clear(); if (xenObject == null) { return; } AsyncAction action = HelpersGUI.FindActiveHaAction(xenObject.Connection); if (action != null) { // There is an EnableHAAction or DisableHAAction in progress relating to this connection. // Show some text and disable editing buttonConfigure.Enabled = false; buttonDisableHa.Enabled = false; pictureBoxWarningTriangle.Visible = false; labelStatus.Text = String.Format(action is EnableHAAction ? Messages.HA_PAGE_ENABLING : Messages.HA_PAGE_DISABLING, Helpers.GetName(xenObject.Connection)); } else { //CA-250234 no need to rebuild HA page if we lost connection to the pool if (pool.Connection == null || pool.Connection.Session == null || !pool.Connection.IsConnected) { return; } // Generate the tab contents depending on what XenObject we're displaying if (pool.ha_enabled) { if (PassedRbacChecks()) { bool haRestricted = Helpers.FeatureForbidden(pool, Host.RestrictHA); buttonConfigure.Visible = !haRestricted; buttonConfigure.Enabled = !haRestricted; buttonDisableHa.Visible = true; buttonDisableHa.Enabled = true; pictureBoxWarningTriangle.Visible = false; labelStatus.Text = string.Format(haRestricted ? Messages.HA_TAB_CONFIGURED_UNLICENSED : Messages.HA_TAB_CONFIGURED_BLURB, Helpers.GetName(pool).Ellipsise(30)); } else { buttonConfigure.Visible = false; buttonDisableHa.Visible = false; pictureBoxWarningTriangle.Visible = true; labelStatus.Text = String.Format(Messages.RBAC_HA_TAB_WARNING, Role.FriendlyCSVRoleList(Role.ValidRoleList(HA_PERMISSION_CHECKS, pool.Connection)), Role.FriendlyCSVRoleList(pool.Connection.Session.Roles)); } } else { buttonConfigure.Visible = true; buttonConfigure.Enabled = true; buttonDisableHa.Visible = false; pictureBoxWarningTriangle.Visible = false; labelStatus.Text = String.Format(Messages.HAPANEL_BLURB, Helpers.GetName(pool).Ellipsise(30)); } var sr = xenObject as SR; if (sr != null) { // Currently unused generateSRHABox(sr); } else if (xenObject is Pool) { generatePoolHABox(pool); tableLayoutPanel1.AutoScrollMinSize = new Size(0, tableLatencies.Height + customListPanel.Height); } } } finally { customListPanel.EndUpdate(); } }
public PropertiesDialogClosingEventArgs(AsyncAction action, bool startAction) { StartAction = startAction; Action = action; }
/// <summary> /// Runs async thread. /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { pnlLog.Visible = true; //pnlContent.Visible = false; CurrentError = string.Empty; CurrentInfo = string.Empty; ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
public AsyncSolution(string name, string description, AsyncAction action) : base(name, description) { _action = action; }
protected override void Run() { if (vmOptList.Count == 0) { log.ErrorFormat("{0} has no VMs need to be optimized", Helpers.GetName(Pool)); return; } this.Description = Messages.ACTION_WLB_POOL_OPTIMIZING; try { log.Debug("Optimizing " + Pool.Name); // for checking whether to display recommendations on optimize pool listview Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, Messages.IN_PROGRESS); int start = 0; int each = 90 / vmOptList.Count; foreach (KeyValuePair <VM, WlbOptimizationRecommendation> vmItem in vmOptList) { VM vm = vmItem.Key; Host fromHost = null; Host toHost = null; if (vmItem.Key.is_control_domain) { log.Debug(vmItem.Value.powerOperation + " " + Helpers.GetName(vmItem.Value.toHost)); fromHost = vmItem.Value.fromHost; Helpers.SetOtherConfig(fromHost.Connection.Session, fromHost, WlbOptimizationRecommendation.OPTIMIZINGPOOL, vmItem.Value.recId.ToString()); try { AsyncAction hostAction = null; int waitingInterval = 10 * 1000; // default to 10s if (vmItem.Value.fromHost.IsLive) { hostAction = new ShutdownHostAction(fromHost, AddHostToPoolCommand.NtolDialog); } else { hostAction = new HostPowerOnAction(fromHost); waitingInterval = 30 * 1000; // wait for 30s } hostAction.Completed += HostAction_Completed; hostAction.RunAsync(); while (!moveToNext) { if (!String.IsNullOrEmpty(hostActionError)) { throw new Exception(hostActionError); } else { //wait System.Threading.Thread.Sleep(waitingInterval); } } } catch (Exception) { throw; } } else { log.Debug("Migrating VM " + vm.Name); fromHost = this.Pool.Connection.Resolve(vm.resident_on); toHost = vmItem.Value.toHost; try { // check if there is a conflict with HA, start optimize if we can RelocateVmWithHa(this, vm, toHost, start, start + each, vmItem.Value.recId); } catch (Failure f) { // prompt to user if ha notl can be raised, if yes, continue long newNtol = 0; if (RaiseHANotl(vm, f, out newNtol)) { DelegatedAsyncAction action = new DelegatedAsyncAction(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, this.Pool.opaque_ref, newNtol); // ntol set succeeded, start new action Program.MainWindow.CloseActiveWizards(vm); new VMMigrateAction(vm, toHost).RunAsync(); }); action.RunAsync(); } else { Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, Messages.WLB_OPT_FAILED); this.Description = Messages.WLB_OPT_FAILED; throw f; } } } start += each; // stop if user cancels optimize pool if (Cancelling) { throw new CancelledException(); } } this.Description = Messages.WLB_OPT_OK_NOTICE_TEXT; Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId); log.Debug("Completed optimizing " + Pool.Name); } catch (Failure ex) { Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId); WlbServerState.SetState(Pool, WlbServerState.ServerState.ConnectionError, (Failure)ex); throw; } catch (CancelledException) { Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId); throw; } catch (Exception ex) { log.Error(ex, ex); this.Description = Messages.WLB_OPT_FAILED; Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId); log.Debug("Optimizing " + Pool.Name + " is failed"); } this.PercentComplete = 100; }
public OpenUrlCommand (string name, string url, AsyncAction action = null) : base (name, action) { Url = url; }
protected override void RunWithSession(ref Session session) { var path = AllDownloadedPatches[patch]; var poolPatches = new List <Pool_patch>(session.Connection.Cache.Pool_patches); var poolUpdates = new List <Pool_update>(session.Connection.Cache.Pool_updates); var conn = session.Connection; var master = Helpers.GetMaster(conn); var existingMapping = mappings.Find(m => m.MasterHost != null && master != null && m.MasterHost.uuid == master.uuid && (m.Pool_patch != null || m.Pool_update != null) && m.XenServerPatch.Equals(patch)); if (existingMapping == null || !(existingMapping.Pool_patch != null && poolPatches.Any(p => string.Equals(p.uuid, existingMapping.Pool_patch.uuid, StringComparison.OrdinalIgnoreCase))) && !(existingMapping.Pool_update != null && poolUpdates.Any(p => string.Equals(p.uuid, existingMapping.Pool_update.uuid, StringComparison.OrdinalIgnoreCase))) ) { try { if (Helpers.ElyOrGreater(master)) { var uploadIsoAction = new UploadSupplementalPackAction(session.Connection, new List <Host>() { master }, path, true); inProgressAction = uploadIsoAction; uploadIsoAction.RunExternal(session); var poolupdate = uploadIsoAction.PoolUpdate; if (poolupdate == null) { log.ErrorFormat("Upload finished successfully, but Pool_update object has not been found for update (uuid={0}) on host (uuid={1}).", patch.Uuid, session.Connection); throw new Exception(Messages.ACTION_UPLOADPATCHTOMASTERPLANACTION_FAILED); } var newMapping = new PoolPatchMapping(patch, poolupdate, Helpers.GetMaster(session.Connection)); if (!mappings.Contains(newMapping)) { mappings.Add(newMapping); } } else { var checkSpaceForUpload = new CheckDiskSpaceForPatchUploadAction(Helpers.GetMaster(conn), path, true); inProgressAction = checkSpaceForUpload; checkSpaceForUpload.RunExternal(session); var uploadPatchAction = new UploadPatchAction(session.Connection, path, true, false); inProgressAction = uploadPatchAction; uploadPatchAction.RunExternal(session); // this has to be run again to refresh poolPatches (to get the recently uploaded one as well) poolPatches = new List <Pool_patch>(session.Connection.Cache.Pool_patches); var poolPatch = poolPatches.Find(p => string.Equals(p.uuid, patch.Uuid, StringComparison.OrdinalIgnoreCase)); if (poolPatch == null) { log.ErrorFormat("Upload finished successfully, but Pool_patch object has not been found for patch (uuid={0}) on host (uuid={1}).", patch.Uuid, session.Connection); throw new Exception(Messages.ACTION_UPLOADPATCHTOMASTERPLANACTION_FAILED); } var newMapping = new PoolPatchMapping(patch, poolPatch, Helpers.GetMaster(session.Connection)); if (!mappings.Contains(newMapping)) { mappings.Add(newMapping); } } } catch (Exception ex) { Error = ex; throw; } } }
public AsyncMultiSolution(string name, string description, AsyncAction action) : this(name, description, (error, token) => action.Invoke(error)) { }
public RelayCommandAsync(AsyncAction handler) { _handler = handler; IsEnabled = true; }
/// <summary> /// Runs asynchronous thread /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { ctlAsyncLog.EnsureLog(); ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
private void RunAsyncInternal(AsyncAction action) { pnlLog.Visible = true; CurrentError = string.Empty; CurrentLog.Close(); EnsureLog(); ctlAsyncLog.Parameter = GetParameters(); ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
/// <summary> /// Runs the asynchronous action. /// </summary> /// <param name="action">Action to run</param> /// <param name="wi">Windows identity (windows user)</param> public void RunAsync(AsyncAction action, WindowsIdentity wi) { RenderScripts(true); Worker.Stop(); Worker.Reset(); Worker.RunAsync(action, wi); }
private async void SwitchToCASC() { Console.WriteLine("Intializing CASC filesystem.."); ModelListBox.Visibility = System.Windows.Visibility.Hidden; contentTypeLoading.Visibility = System.Windows.Visibility.Visible; CASCdesc.Visibility = System.Windows.Visibility.Visible; CASCprogress.Visibility = System.Windows.Visibility.Visible; FilterBox.Visibility = System.Windows.Visibility.Hidden; if (ConfigurationManager.AppSettings["basedir"] != "" && Directory.Exists(ConfigurationManager.AppSettings["basedir"])) { Console.WriteLine("Using basedir " + ConfigurationManager.AppSettings["basedir"] + " to load.."); bgAction = new AsyncAction(() => WoWFormatLib.Utils.CASC.InitCasc(bgAction, ConfigurationManager.AppSettings["basedir"])); } else { bgAction = new AsyncAction(() => WoWFormatLib.Utils.CASC.InitCasc(bgAction)); } bgAction.ProgressChanged += new EventHandler<AsyncActionProgressChangedEventArgs>(bgAction_ProgressChanged); try { await bgAction.DoAction(); } catch { } Console.WriteLine("CASC filesystem initialized."); Console.WriteLine("Generating listfile.."); List<string> files = new List<String>(); models = CASC.GenerateListfile(); ModelListBox.DataContext = models; ModelListBox.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("", System.ComponentModel.ListSortDirection.Ascending)); Console.WriteLine("Listfile generated!"); CASCinitialized = true; Console.WriteLine("BUILD: " + CASC.cascHandler.Config.BuildName); FilterBox.Visibility = System.Windows.Visibility.Visible; CASCdesc.Visibility = System.Windows.Visibility.Hidden; CASCprogress.Visibility = System.Windows.Visibility.Hidden; contentTypeLoading.Visibility = System.Windows.Visibility.Collapsed; ModelListBox.Visibility = System.Windows.Visibility.Visible; MapsTab.Visibility = System.Windows.Visibility.Visible; // using (TerrainWindow tw = new TerrainWindow("Draenor_30_31")) // { // tw.Run(30.0, 60.0); // } // new Render(@"World\wmo\Draenor\Orc\6OC_OrcClans_HouseSmall.wmo"); }
public IAsyncAction DeleteAsync() => AsyncAction.FromTask(async ct => { await DeleteAsync(CancellationToken.None); });
private void UpdateActionProgress(AsyncAction action) { progressBar1.Value = action == null ? 0 : action.PercentComplete; labelProgress.Text = action == null ? string.Empty : action.Description; }
/// <summary> /// Runs async thread. /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { pnlLog.Visible = true; pnlGeneralTab.Visible = false; CurrentError = string.Empty; bool copyPerm = CopyPermissions && sameSite; AddScript("InitializeLog();"); switch (CurrentAction) { case Action.Copy: ctlAsyncLog.Parameter = String.Format("{0};{1}", ValidationHelper.GetBoolean(WindowHelper.GetItem(Action.Copy + underlying), false), copyPerm); break; case Action.Link: case Action.LinkDoc: ctlAsyncLog.Parameter = String.Format("{0};{1}", ValidationHelper.GetBoolean(WindowHelper.GetItem(Action.Link + underlying), false), copyPerm); break; case Action.Move: ctlAsyncLog.Parameter = copyPerm.ToString(); break; } ctlAsyncLog.EnsureLog(); ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
private void SetButtonState() { string statusMessage = string.Empty; string rbacUser = string.Empty; bool passedRbacChecks = PassedRbacChecks(); if (!passedRbacChecks) { List <Role> roleList = _pool.Connection.Session.Roles; roleList.Sort(); rbacUser = roleList[0].FriendlyName; } AsyncAction thisAction = HelpersGUI.FindActiveWLBAction(_pool.Connection); if (thisAction is RetrieveWlbConfigurationAction) { DisableButtons(); return; } //if wlb is not configured, // disable the config button and change the text of the Enable button to Initialize WLB... //else if (!wlbConfigured) else if (WlbServerState.GetState(_pool) == WlbServerState.ServerState.NotConfigured) { buttonConnect.Visible = true; buttonConnect.Text = Messages.WLB_CONNECT; buttonConfigure.Visible = false; buttonEnableDisableWlb.Visible = false; buttonReports.Visible = false; pictureBoxWarningTriangle.Visible = false; if (passedRbacChecks) { statusMessage = string.Format(Messages.WLB_INITIALIZE_WLB_BLURB, _pool.Name); } else { statusMessage = string.Format(Messages.WLB_INITIALIZE_WLB_BLURB_NO_PRIV, _pool.Name, rbacUser); } labelStatus.Text = statusMessage; pictureBoxWarningTriangle.Visible = (WlbServerState.GetState(_pool) == WlbServerState.ServerState.ConnectionError); panelConfiguration.Visible = false; wlbOptimizePool.Visible = false; } //if there is an error contacting the WLB server, // disable the config button and change the text of the Enable button to Initialize WLB... //else if (!wlbConfigured) else if (WlbServerState.GetState(_pool) == WlbServerState.ServerState.ConnectionError) { buttonConnect.Visible = true; buttonConnect.Text = Messages.WLB_RECONNECT; buttonConfigure.Visible = false; buttonEnableDisableWlb.Visible = false; buttonReports.Visible = false; pictureBoxWarningTriangle.Visible = true; if (passedRbacChecks) { statusMessage = Messages.WLB_CONNECTION_ERROR_BLURB; } else { statusMessage = string.Format(Messages.WLB_CONNECTION_ERROR_BLURB_NO_PRIV, rbacUser); } labelStatus.Text = statusMessage; labelStatus.Visible = true; pictureBoxWarningTriangle.Visible = (WlbServerState.GetState(_pool) == WlbServerState.ServerState.ConnectionError); buttonReports.Enabled = false; panelConfiguration.Visible = false; wlbOptimizePool.Visible = false; } //if wlb is configured but not enabled, //enable the configure button and enble the enable button //else if (wlbConfigured && !wlbEnabled) else if (WlbServerState.GetState(_pool) == WlbServerState.ServerState.Disabled) { base.Text = Messages.WORKLOAD_BALANCING; buttonConnect.Visible = false; buttonConfigure.Visible = true; buttonEnableDisableWlb.Visible = true; buttonReports.Visible = true; pictureBoxWarningTriangle.Visible = true; buttonConfigure.Enabled = true; buttonEnableDisableWlb.Enabled = true; buttonEnableDisableWlb.Text = Messages.ENABLE_WLB_ELLIPSIS; buttonEnableDisableWlb.ImageIndex = 1; //Play arrow if (!passedRbacChecks) { statusMessage = string.Format(Messages.WLB_ENABLE_WLB_BLURB_NO_PRIV, _pool.Name, rbacUser); } else { statusMessage = string.Format(Messages.WLB_ENABLE_WLB_BLURB, _pool.Name); } labelStatus.Text = statusMessage; buttonReports.Enabled = true; panelConfiguration.Visible = true; wlbOptimizePool.Visible = true; } //otherwise, if wlb is configured and enabled, allow configuration, and show enable as Disable //else if (wlbEnabled) else if (WlbServerState.GetState(_pool) == WlbServerState.ServerState.Enabled) { buttonConnect.Visible = false; buttonConfigure.Visible = true; buttonEnableDisableWlb.Visible = true; buttonReports.Visible = true; pictureBoxWarningTriangle.Visible = false; buttonConfigure.Enabled = true; buttonEnableDisableWlb.Enabled = true; buttonEnableDisableWlb.Text = Messages.DISABLE_WLB_ELLIPSIS; buttonEnableDisableWlb.ImageIndex = 0; //Pause hashes if (!passedRbacChecks) { statusMessage = string.Format(Messages.WLB_NO_PERMISSION_BLURB, rbacUser); } else { statusMessage = string.Format(Messages.WLB_ENABLED_BLURB, _pool.Name); } labelStatus.Text = statusMessage; buttonReports.Enabled = true; panelConfiguration.Visible = true; wlbOptimizePool.Visible = true; } if (PassedRbacChecks()) { //Show the buttons flowLayoutPanelLeftButtons.Visible = true; //panelButtons.Visible = true; } else { //disable and hide the buttons DisableButtons(); flowLayoutPanelLeftButtons.Visible = false; //panelButtons.Visible = false; } }
public AsyncMultiSolution(string name, string description, AsyncAction action) : base(name, description, action) { }
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"); new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.NEW_SR_CONNECTION_LOST, Helpers.GetName(xenConnection)), Messages.XENCENTER)).ShowDialog(this); closeWizard = true; return; } Host master = xenConnection.Resolve(pool.master); if (master == null) { log.Error("New SR Wizard: Master has disappeared"); new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.NEW_SR_CONNECTION_LOST, Helpers.GetName(xenConnection)), Messages.XENCENTER)).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; ActionProgressDialog dialog = new ActionProgressDialog(FinalAction, progressBarStyle) { ShowCancel = true }; if (m_srWizardType is SrWizardType_LvmoHba) { 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_LvmoHba) { foreach (var asyncAction in actionList) { AddActionToSummary(asyncAction); } } if (!FinalAction.Succeeded && FinalAction is SrReattachAction && _srToReattach.HasPBDs) { // reattach failed. Ensure PBDs are now unplugged and destroyed. 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; }
/// <summary> /// Runs asynchronous thread /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { ctlAsync.RunAsync(action, WindowsIdentity.GetCurrent()); }
private List <AsyncAction> GetActions(Host master, bool disasterRecoveryTask) { // Now we need to decide what to do. // This will be one off create, introduce, reattach List <AsyncAction> finalActions = new List <AsyncAction>(); actionSrDescriptorDict.Clear(); foreach (var srDescriptor in m_srWizardType.SrDescriptors) { if (String.IsNullOrEmpty(srDescriptor.UUID)) { // Don't need to show any warning, as the only destructive creates // are in iSCSI and HBA, where they show their own warning finalActions.Add(new SrCreateAction(xenConnection, master, srDescriptor.Name, srDescriptor.Description, m_srWizardType.Type, m_srWizardType.ContentType, !master.RestrictPoolAttachedStorage, srDescriptor.DeviceConfig, Program.StorageLinkConnections.GetCopy())); } else if (_srToReattach == null || _srToReattach.Connection != xenConnection) { // introduce if (disasterRecoveryTask && (_srToReattach == null || SR.SupportsDatabaseReplication(xenConnection, _srToReattach))) { // "Find existing SRs" or "Attach SR needed for DR" cases ScannedDeviceInfo deviceInfo = new ScannedDeviceInfo(m_srWizardType.Type, srDescriptor.DeviceConfig, srDescriptor.UUID); finalActions.Add(new DrTaskCreateAction(xenConnection, deviceInfo)); } else { finalActions.Add(new SrIntroduceAction(xenConnection, srDescriptor.UUID, srDescriptor.Name, srDescriptor.Description, m_srWizardType.Type, m_srWizardType.ContentType, !master.RestrictPoolAttachedStorage, srDescriptor.DeviceConfig)); } } else { // Reattach if (disasterRecoveryTask && SR.SupportsDatabaseReplication(xenConnection, _srToReattach)) { // "Attach SR needed for DR" case ScannedDeviceInfo deviceInfo = new ScannedDeviceInfo(_srToReattach.GetSRType(true), srDescriptor.DeviceConfig, _srToReattach.uuid); finalActions.Add(new DrTaskCreateAction(xenConnection, deviceInfo)); } else { finalActions.Add(new SrReattachAction(_srToReattach, srDescriptor.Name, srDescriptor.Description, srDescriptor.DeviceConfig)); } } AsyncAction action = finalActions.Last(); if (!actionSrDescriptorDict.ContainsKey(action)) { actionSrDescriptorDict.Add(action, srDescriptor); } } return(finalActions); }
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() { new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Warning, String.Format(Messages.HA_INVALID_CONFIG_RESUME, Helpers.GetName(vm).Ellipsise(500)), Messages.HIGH_AVAILABILITY)).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); } }
/// <summary> /// 异步动作派遣分发器 /// </summary> /// <param name="action">异步动作名称</param> /// <returns>Task任务</returns> public Task Dispatch(AsyncAction action) { return(action(Dispatch, GetState)); }
/// <summary> /// Executes given action asynchronously /// </summary> /// <param name="action">Action to run</param> protected void RunAsync(AsyncAction action) { pnlLog.Visible = true; CurrentLog.Close(); EnsureLog(); CurrentError = string.Empty; CurrentInfo = string.Empty; eventType = EventType.INFORMATION; plcContent.Visible = false; ctlAsync.RunAsync(action, WindowsIdentity.GetCurrent()); }
/// <summary> /// 异步动作派遣器,仅有出参 /// </summary> /// <typeparam name="Result">出参类型</typeparam> /// <param name="action">异步动作</param> /// <returns></returns> public AsyncAction <Result> asyncAction <Result>( AsyncAction <Result> action) { return((dispatch, getState) => action(dispatch, getState)); }
/// <summary> /// Runs async thread. /// </summary> /// <param name="action">Method to run</param> protected void RunAsync(AsyncAction action) { pnlLog.Visible = true; CurrentError = string.Empty; CurrentInfo = string.Empty; CurrentLog.Close(); EnsureLog(); ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
/// <summary> /// 异步动作派遣分发器 /// </summary> /// <typeparam name="Result">异步动作结果类型</typeparam> /// <param name="action">异步动作名称</param> /// <returns>返回异步动作结果</returns> public Task <Result> Dispatch <Result>(AsyncAction <Result> action) { return(action(Dispatch, GetState)); }
/// <summary> /// Runs the specified action asynchronously. /// </summary> /// <param name="actionName">Action name</param> /// <param name="action">Action</param> private void RunAsync(string actionName, AsyncAction action) { // Set action name as process parameter ctlAsyncLog.Parameter = actionName; // Log async action start EventLogProvider.LogEvent(EventType.INFORMATION, actionName, "STARTED"); // Run async action ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent()); }
/// <summary> /// Writes lines of text to the specified file using the specified character encoding. /// </summary> /// <param name="file">The file that the lines are written to.</param> /// <param name="lines">The list of text strings to write as lines.</param> /// <param name="encoding">The character encoding of the file.</param> /// <returns>No object or value is returned when this method completes.</returns> public static IAsyncAction WriteLinesAsync(IStorageFile file, IEnumerable <string> lines, UwpUnicodeEncoding encoding) => AsyncAction.FromTask(cancellationToken => WriteLinesTaskAsync(file, lines, append: false, recognizeEncoding: true, cancellationToken, encoding));