protected async void OnOkCommand() { try { await _SemaphoreSlimOnOkCommand.WaitAsync(); UpdateOptionSettings(); _loggerService?.LogEvent(nameof(OnOkCommand)); ImageAction Action = OverwriteFiles ? ImageAction.Save : ImageAction.SaveAs; bool successfull = await ResizeImages(Action); if (successfull && _localSettings.Settings.ClearImageListAfterSuccess && ImageFiles?.Count != 0) { CancelCommand?.Execute(ImageFiles); } //if the app was started from command line exit the app after resize if (AppStartType.CommandLine.Equals(_appStartType)) { _applicationService.Exit(); } } catch (Exception e) { _loggerService?.LogException(nameof(OnOkCommand), e); } finally { _SemaphoreSlimOnOkCommand.Release(); } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { IProjectInfoProvider solutionInfoProvider = new SolutionInfoProvider(this); IProjectInfoProvider projectInfoProvider = new ProjectInfoProvider(this); IProjectInfoProvider fileInfoProvider = new FileInfoProvider(this); IProjectInfoProvider solutionSnapshotInfoProvider = new SolutionInfoProvider(this, true); IProjectInfoProvider projectSnapshotInfoProvider = new ProjectInfoProvider(this, true); IDexterInfoProvider dexterInfoProvider = new SettingsStoreDexterInfoProvider(this); ConfigurationProvider solutionConfigProvider = new ConfigurationProvider(solutionInfoProvider, dexterInfoProvider); ConfigurationProvider projectConfigProvider = new ConfigurationProvider(projectInfoProvider, dexterInfoProvider); ConfigurationProvider fileConfigProvider = new ConfigurationProvider(fileInfoProvider, dexterInfoProvider); ConfigurationProvider solutionSnapshotConfigProvider = new ConfigurationProvider(solutionSnapshotInfoProvider, dexterInfoProvider); ConfigurationProvider projectSnapshotConfigProvider = new ConfigurationProvider(projectSnapshotInfoProvider, dexterInfoProvider); var commandSet = new Guid("2ed6d891-bce1-414d-8251-80a0800a831f"); DexterAnalysisCommand fileAnalysisCommand = new DexterFileAnalysisCommand(this, 0x0102, commandSet, fileConfigProvider); DexterAnalysisCommand projectAnalysisCommand = new DexterSolutionAnalysisCommand(this, 0x0101, commandSet, projectConfigProvider); DexterAnalysisCommand solutionAnalysisCommand = new DexterSolutionAnalysisCommand(this, 0x0100, commandSet, solutionConfigProvider); DexterAnalysisCommand projectSnapshotCommand = new DexterSolutionAnalysisCommand(this, 0x0111, commandSet, projectSnapshotConfigProvider); DexterAnalysisCommand solutionSnapshotCommand = new DexterSolutionAnalysisCommand(this, 0x0110, commandSet, solutionSnapshotConfigProvider); settingsCommand = new SettingsCommand(this, 0x0103, commandSet); dashboardCommand = new DashboardCommand(this, 0x0104, commandSet, dexterInfoProvider); cancelCommand = new CancelCommand(this, 0x0105, commandSet); DexterAnalysisCommand solutionAnalysisToolbarCommand = new DexterSolutionAnalysisCommand(this, 0x0200, commandSet, solutionConfigProvider); settingsToolbarCommand = new SettingsCommand(this, 0x0203, commandSet); dashboardToolbarCommand = new DashboardCommand(this, 0x0204, commandSet, dexterInfoProvider); cancelToolbarCommand = new CancelCommand(this, 0x0205, commandSet); analysisCommands.Add(fileAnalysisCommand); analysisCommands.Add(projectAnalysisCommand); analysisCommands.Add(solutionAnalysisCommand); analysisCommands.Add(projectSnapshotCommand); analysisCommands.Add(solutionSnapshotCommand); analysisCommands.Add(solutionAnalysisToolbarCommand); foreach (DexterAnalysisCommand analysisCommand in analysisCommands) { analysisCommand.AnalysisStarted += onAnalysisStarted; analysisCommand.AnalysisFinished += onAnalysisFinished; } SettingsPage settingsPage = (SettingsPage)GetDialogPage(typeof(SettingsPage)); settingsPage.SettingsChanged += onSettingsChanged; PeerReviewService.Instance = new PeerReviewService(new DexterTextService()); RegisterSolutionManager(); CreateReviewCommentManager(); base.Initialize(); }
protected override void OnPropertyChanged(string propertyName) { base.OnPropertyChanged(propertyName); if (propertyName == "CanSave") { SaveCommand.RaiseCanExecuteChanged(); } else if (propertyName == "CanCancel") { CancelCommand.RaiseCanExecuteChanged(); } else if (propertyName == "CanDelete") { DeleteCommand.RaiseCanExecuteChanged(); } else if (propertyName == "CanRemove") { RemoveCommand.RaiseCanExecuteChanged(); } else if (propertyName == "CanAddNew") { AddCommand.RaiseCanExecuteChanged(); } else if (propertyName == "IsBusy") { RefreshCommands(); } }
private async void DoLogin() { if (string.IsNullOrWhiteSpace(Login) || string.IsNullOrWhiteSpace(Password)) { return; } IsWorking = true; CanLogin = false; try { await AccountManager.LoginLastFm(Login, Password); CancelCommand.Execute(null); } catch (LastFmLoginException ex) { LoggingService.Log(ex.ToString()); LoginError = ErrorResources.LoginErrorInvalidClient; CanLogin = true; IsWorking = false; } catch (Exception ex) { LoggingService.Log(ex.ToString()); CanLogin = true; IsWorking = false; } }
private void Cancel() { if (CancelCommand != null) { CancelCommand.Execute(new object()); } }
public EggProductionEntryViewModel(IMessageBroker broker, IEggProductionService service, IConsumableUsageService usageService, IHenHouseService houseService, SaveEggProductionCommand saveCommand, CancelCommand cancelCommand, ShowEggProductionListCommand showListCommand) { this.broker = broker; this.service = service; this.usageService = usageService; ActualSaveCommand = saveCommand; CancelCommand = cancelCommand; ShowListCommand = showListCommand; PropertiesToValidate = new List <string> { "Date", "Details" }; InitializeCommands(); NavigationCommands = new List <CommandBase>() { SaveCommand, CancelCommand, RefreshCommand }; CancelCommand.Action = b => showListCommand.Execute(null); HenHouses = new ObservableCollection <HenHouse>(houseService.GetAll().OrderBy(h => h.Name)); SubscribeMessages(); }
private void SetEventHandlers() { MainList.CollectionChanged += UpdateStatusTexts; _remotes.Loading += (s, e) => { BusyText = "Getting list of files ..."; RetryingText = ""; MessageTone = L4j.Info; IsDelayingRetry = false; }; _remotes.DelayingRetry += (s, e) => { BusyText = $"Unable to get list of files."; RetryingText = $"retrying in {e.Value} ..."; MessageTone = L4j.Warn; IsDelayingRetry = true; }; PropertyChanged += (s, e) => { if (e.PropertyName == nameof(IsBusy) || e.PropertyName == nameof(IsDelayingRetry)) { CancelCommand.Fire_CanExecuteChanged(); } }; Cancelled += (s, e) => { _remotes.RaiseCancelled(); }; }
public DownloadingViewModel(IUnityContainer container) : base(container) { PauseAllCommand = new RelayCommand(() => { foreach (var task in TransferTasks) { if (PauseCommand.CanExecute(task)) { PauseCommand.Execute(task); } } }, () => TransferTasks?.Any() ?? false); CancelAllCommand = new RelayCommand(() => { foreach (var task in TransferTasks) { if (CancelCommand.CanExecute(task)) { CancelCommand.Execute(task); } } }, () => TransferTasks?.Any() ?? false); }
public void AddToCart() { if (_navigationService.HostScreen.CurrentUser != null) { if (CurrentUserCard != null && CurrentUserCard.Activated != false) { ILoansService _loans = IoC.ServiceProvider.GetService <ILoansService>(); _loans.LoanCart.Add(currentBook); _dialog.Alert("Varukorg", $"Tillagd i varukorgen"); if (currentBook.Category == 1) { currentBook.Quantity--; } CancelCommand.Execute(null); } else { _dialog.Alert("Lånekort", "Du har inget Lånekort registrerat eller aktiverat \nVänligen kontakta personalen"); } } else { _dialog.Alert("Login", "Vänligen logga in för att låna"); } }
public AccountCreationPageViewModel() { User = new User(); CancelCommand = new CancelCommand(); GenerateNumberCommand = new GenerateNumberCommand(this); CreateCommand = new CreateCommand(this); }
void RaisePostBackEvent(string eventArgument) { if (eventArgument == "Upload") { HttpPostedFile uploadedFile = Page.Request.Files[ClientID + "_Upload"]; if (uploadedFile != null && uploadedFile.ContentLength > 0) { FileManagerItemInfo dir = GetCurrentDirectory(); Controller.ProcessFileUpload(dir, uploadedFile); } } else if (eventArgument == "Select") { if (SelectCommand != null) SelectCommand.Invoke(this, EventArgs.Empty); } else if (eventArgument == "Cancel") { if (CancelCommand != null) CancelCommand.Invoke(this, EventArgs.Empty); } else if (eventArgument.StartsWith("Toolbar:", StringComparison.Ordinal)) { int i = int.Parse(eventArgument.Substring(8)); CustomToolbarButton button = CustomToolbarButtons[i]; OnToolbarCommand(new CommandEventArgs(button.CommandName, button.CommandArgument)); } }
public SolveAddView() { InitializeComponent(); SolveTextBox = this.FindControl <TextBox>("SolveTextBox"); SolveTextBox.Text = "00:00:00.00"; SolveTextBox.CaretIndex = 6; SolveTextBox.CaretBrush = Avalonia.Media.Brushes.Yellow; SolveTextBox.AddHandler(TextInputEvent, PreviewTextInput, RoutingStrategies.Tunnel); SolveTextBox.AddHandler(KeyDownEvent, PreviewKeyDown, RoutingStrategies.Tunnel); CancelButton = this.Find <Button>("CancelButton"); #if DEBUG this.AttachDevTools(); #endif this.WhenActivated(disposableRegistration => { this.BindCommand( ViewModel, viewModel => viewModel.CancelCommand, view => view.CancelButton) .DisposeWith(disposableRegistration); ViewModel !.CancelCommand.Subscribe(_ => Close()) .DisposeWith(disposableRegistration); }); }
private void maininput_PreviewKeyDown(object sender, KeyEventArgs e) { try { if (e.Key == Key.Escape) { if (string.IsNullOrEmpty(maininput.Text)) { if (CancelCommand != null) { CancelCommand.Execute(null); } } else { SearchText = ""; e.Handled = true; } } if (e.Key == Key.Enter) { if (AcceptCommand != null) { AcceptCommand.Execute(maininput.Text); } } } catch (Exception ex) { logger.Error(ex); } }
private void SaveAction(object obj) { try { if (this.context.Save(Selected)) { if (Message.QuestionYesNo("Data Berhasil Disimpan, Print Faktur ?")) { Selected.NamaCustomer = Selected.Customer.NamaCustomer; Selected.KodeCustomer = Selected.Customer.KodeCustomer; var layout = "MainApp.Reports.Layouts.FakturPernjualan.rdlc"; if (Selected.Pembayaran == StatusPembayaran.Kredit) { layout = "MainApp.Reports.Layouts.FakturPernjualanKredit.rdlc"; } HelperPrint.PrintWithFormActionTwoSource("Print Preview", new ReportDataSource { Name = "Header", Value = new List <Penjualan> { Selected } }, new ReportDataSource { Name = "DataSet1", Value = Selected.Details.ToList() }, layout, null); } BarangSourceView.Refresh(); CancelCommand.Execute(null); } } catch (Exception ex) { Message.Error(ex.Message); } }
private void OnToolbarClick(object sender, ToolbarButtonClickEventArgs e) { switch (e.ClickedButton) { case ToolbarButton.Back: BackCommand?.TryExecute(); break; case ToolbarButton.Edit: EditCommand?.TryExecute(); break; case ToolbarButton.Delete: DeleteCommand?.TryExecute(); break; case ToolbarButton.Save: SaveCommand?.TryExecute(); break; case ToolbarButton.Cancel: CancelCommand?.TryExecute(); break; } }
public IObservable <RecoveryOptionResult> Show(UserError userError) { IsBusy = false; var error = userError as TwoFactorRequiredUserError; Debug.Assert(error != null, String.Format(CultureInfo.InvariantCulture, "The user error is '{0}' not a TwoFactorRequiredUserError", userError)); InvalidAuthenticationCode = error.RetryFailed; TwoFactorType = error.TwoFactorType; var ok = OkCommand .Do(_ => IsBusy = true) .Select(_ => AuthenticationCode == null ? RecoveryOptionResult.CancelOperation : RecoveryOptionResult.RetryOperation) .Do(_ => error.ChallengeResult = AuthenticationCode != null ? new TwoFactorChallengeResult(AuthenticationCode) : null); var resend = ResendCodeCommand.Select(_ => RecoveryOptionResult.RetryOperation) .Do(_ => error.ChallengeResult = TwoFactorChallengeResult.RequestResendCode); var cancel = CancelCommand.Select(_ => RecoveryOptionResult.CancelOperation); return(Observable.Merge(ok, cancel, resend) .Take(1) .Do(_ => IsAuthenticationCodeSent = error.ChallengeResult == TwoFactorChallengeResult.RequestResendCode)); }
public UsageEntryViewModel(IMessageBroker messageBroker, IConsumableUsageService usageService, IHenHouseService houseService, IConsumableService consumableService, SaveUsageCommand saveUsageCommand, CancelCommand cancelCommand, ShowUsageCommand showListCommand ) { this.messageBroker = messageBroker; this.usageService = usageService; this.houseService = houseService; this.consumableService = consumableService; this.saveUsageCommand = saveUsageCommand; this.showListCommand = showListCommand; CancelCommand = cancelCommand; PropertiesToValidate = new List <string>() { "Date", "Total", "Details" }; InitializeCommands(); HouseList = new ObservableCollection <HenHouse>(houseService.GetAll()); ConsumableList = new ObservableCollection <Consumable>(consumableService.GetAll()); SubscribeMessages(); }
private async Task LoadChromecasts() { try { LoadingChromecasts = true; var ip = LocalIPAddress().ToString(); var foundChromecasts = await _chromecastService.StartLocatingDevices(ip); foreach (var foundChromecast in foundChromecasts) { Chromecasts.Add(foundChromecast); } LoadingChromecasts = false; AnyChromecast = Chromecasts.Any(); } catch (Exception ex) { LoadingChromecasts = false; AnyChromecast = false; Logger.Error(ex); Messenger.Default.Send( new UnhandledExceptionMessage( new PopcornException(LocalizationProviderHelper.GetLocalizedValue <string>("CastFailed")))); CancelCommand.Execute(null); CloseCommand.Execute(null); } }
private void InvalidateCommands() { SaveCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); RoleChangedCommand.RaiseCanExecuteChanged(); GenPersonCodeCommand.RaiseCanExecuteChanged(); }
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e) { _changeProvided = true; Trace.WriteLine("Value of property has changed"); SaveCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); }
private void Button_Click(object sender, RoutedEventArgs e) { if (e.OriginalSource is Button button) { switch (button.Name) { case "buttonEdit": EditCommand?.Execute(null); break; case "buttonDelete": DeleteCommand?.Execute(null); break; case "buttonCancel": CancelCommand?.Execute(null); break; case "buttonSave": SaveCommand?.Execute(null); break; case "buttonAdd": AddCommand?.Execute(null); break; } } }
public async Task SupportsCooperativeCancellation() { using (CancellationTokenSource cts = new()) { CommandBase command = new CancellationCommand(); cts.Cancel(); OperationCanceledException exception = await Assert.ThrowsAsync <OperationCanceledException>(() => command.ExecuteAsync(cts.Token)); Assert.Equal(cts.Token, exception.CancellationToken); } using (CancellationTokenSource cts = new()) { CommandBase command = new CancelCommand(); cts.Cancel(); Task <CommandResult> task = command.ExecuteAsync(cts.Token); TaskCanceledException exception = await Assert.ThrowsAsync <TaskCanceledException>(() => task); Assert.Equal(cts.Token, exception.CancellationToken); Assert.Same(task, exception.Task); Assert.Equal(TaskStatus.Canceled, task.Status); Assert.Null(task.Exception); } }
public EmployeeCostEntryViewModel( IMessageBroker messageBroker, IEmployeeCostService costService, IEmployeeService employeeService, SaveEmployeeCostCommand saveCostCommand, CancelCommand cancelCommand, ShowEmployeeCostCommand showListCommand ) { this.messageBroker = messageBroker; this.costService = costService; this.employeeService = employeeService; ActualSaveCommand = saveCostCommand; CancelCommand = cancelCommand; ShowCostListCommand = showListCommand; InitializeCommands(); NavigationCommands = new List <CommandBase> { SaveCommand, CancelCommand }; CancelCommand.Action = broker => showListCommand.Execute(null); PropertiesToValidate = new List <string>() { "Date", "Total", "Details" }; Employees = new ObservableCollection <Employee>(employeeService.GetAll()); SubscribeMessages(); }
/// <summary> /// Requests cancellation of the command. /// </summary> public void Cancel() { if (CancelCommand.CanExecute()) { CancelCommand.Execute(); } }
public MainWindowViewModel() { EdgeLocalStateFilePath.SetValidateNotifyError(IsExitisFile); EdgeCookiesFilePath.SetValidateNotifyError(IsExitisFile); ChromeLocalStateFilePath.SetValidateNotifyError(IsExitisFile); ChromeCookiesFilePath.SetValidateNotifyError(IsExitisFile); ObsCookiesFilePath.SetValidateNotifyError(IsExitisFile); EdgeCommand = new[] { EdgeLocalStateFilePath.ObserveHasErrors, EdgeCookiesFilePath.ObserveHasErrors, ObsCookiesFilePath.ObserveHasErrors }.CombineLatestValuesAreAllFalse().ToReactiveCommand <Models.CommandParameter>(); ChromeCommand = new[] { ChromeLocalStateFilePath.ObserveHasErrors, ChromeCookiesFilePath.ObserveHasErrors, ObsCookiesFilePath.ObserveHasErrors }.CombineLatestValuesAreAllFalse().ToReactiveCommand <Models.CommandParameter>(); LocalStateFilePath.SetValidateNotifyError(IsExitisFile); SrcCookieFilePath.SetValidateNotifyError(IsExitisFile); DestCookieFilePath.SetValidateNotifyError(IsExitisFile); HostKey.SetValidateNotifyError(host => { if (String.IsNullOrWhiteSpace(host)) { return("Empty"); } return(null); }); ParamCommand = new[] { LocalStateFilePath.ObserveHasErrors, SrcCookieFilePath.ObserveHasErrors, HostKey.ObserveHasErrors, DestCookieFilePath.ObserveHasErrors }.CombineLatestValuesAreAllFalse().ToReactiveCommand <Models.CommandParameter>(); EdgeCommand.Subscribe(ExecuteCommand.Execute); ChromeCommand.Subscribe(ExecuteCommand.Execute); ParamCommand.Subscribe(ExecuteCommand.Execute); OkCommand.Subscribe(async _ => { Executing.Value = true; try { await System.Threading.Tasks.Task.Run(() => { CookieManager.Converter.Convert(Environment.ExpandEnvironmentVariables(Param.LocalStateFilePath), Environment.ExpandEnvironmentVariables(Param.SrcCookieFilePath), Param.HostKey, Environment.ExpandEnvironmentVariables(Param.DestCookieFilePath)); }); } catch { IsErrorDialogOpen.Value = true; } Executing.Value = false; IsDialogOpen.Value = false; } ); ExecuteCommand.Subscribe(param => { IsDialogOpen.Value = true; Param = param; }); CancelCommand.Subscribe(_ => IsDialogOpen.Value = false); ErrorOkCommand.Subscribe(_ => IsErrorDialogOpen.Value = false); }
void ConfigurationPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "HasChanges": CommandManager.InvalidateRequerySuggested(); SaveCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); ClearErrorsCommand.RaiseCanExecuteChanged(); if (Configuration.HasChanges) { SaveSuccess = false; } break; case "HasError": CommandManager.InvalidateRequerySuggested(); SaveCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); ClearErrorsCommand.RaiseCanExecuteChanged(); break; default: break; } }
public override void PrivateChatProcessing(Message message, ref bool continuation) { try { base.PrivateChatProcessing(message, ref continuation); long chatId = message.Chat.Id; if (message.Text != null && message.Text.ToLower().Equals(CancelCommand.ToLower())) { ClearUnderChatMenu(chatId, "Принято!"); SendDefaultMenu(chatId); mods.TryRemove(chatId, out Mode m); return; } if (mods.TryGetValue(chatId, out Mode mode)) { Match TokenChecking = TokenParsing.Match(message.Text); if (TokenChecking.Success) { logger.Info("Добавляем бота с токеном " + TokenChecking.Groups[1].Value); AddBot(TokenChecking.Groups[1].Value, mode); ClearUnderChatMenu(message.Chat.Id, "Бот успешно создан!"); SendDefaultMenu(message.Chat.Id); return; } else { sender_to_tg.Put(factory.CreateMessage(message.Chat.Id, "Пришлите пожалуйста корректный токен в формате\n\n 1234567:AAAAAAAdsdd")); return; } } SendDefaultMenu(chatId); } catch (Exception ex) { logger.Error(ex); } }
private async void Start() { try { CancellationTokenSource = new CancellationTokenSource(); RunTask = true; StartCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); var tasks = new List <Task>(); tasks.AddRange(new List <Task>() { InitializeProgressBar(ProgressBarOneText, new Progress <int>(p => ProgressBarOneValue = p), CancellationTokenSource.Token), InitializeProgressBar(ProgressBarTwoText, new Progress <int>(p => ProgressBarTwoValue = p), CancellationTokenSource.Token), InitializeProgressBar(ProgressBarThreeText, new Progress <int>(p => ProgressBarThreeValue = p), CancellationTokenSource.Token), }); await Task.WhenAll(tasks); } catch (OperationCanceledException) { } finally { RunTask = false; StartCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); } }
public async Task WrappedDelegateCompleted_EntersCanceledState() { var command = new CancelCommand(); var observedCancellationToken = new CancellationToken(); object observedSender = null; bool observedCanExecute = true; EventHandler subscription = (s, _) => { observedSender = s; observedCanExecute = ((ICommand)command).CanExecute(null); }; var ready = new TaskCompletionSource <object>(); var release = new TaskCompletionSource <object>(); var task = command.Wrap(async token => { observedCancellationToken = token; ready.SetResult(null); await release.Task; })(); await ready.Task; ((ICommand)command).CanExecuteChanged += subscription; release.SetResult(null); await task; Assert.True(observedCancellationToken.IsCancellationRequested); Assert.False(((ICommand)command).CanExecute(null)); Assert.AreSame(command, observedSender); Assert.False(observedCanExecute); ((ICommand)command).CanExecuteChanged -= subscription; }
private async Task DoExecuteAsync(object parameter) { await Task.Factory.StartNew(p => { // Invoke the action. InvokeAction(p); ReportProgress(() => { // We are no longer executing. IsExecuting = false; // If we were cancelled, invoke the cancelled event - otherwise invoke executed. if (IsCancellationRequested) { InvokeCancelled(new CommandEventArgs { Parameter = p }); } else { InvokeExecuted(new CommandEventArgs { Parameter = p }); } CancelCommand.NotifyCanExecuteChanged(); }); }, parameter, _token); }
private static Message Convert(string exchangeCode, CancelCommand cancelCommand) { CancelMessage cancelMessage = new CancelMessage(exchangeCode,cancelCommand.TransactionID, (TransactionError)cancelCommand.ErrorCode, (iExchange.Common.CancelReason)cancelCommand.CancelReason); return cancelMessage; }