public void SaveViewCommand(object key) { bool isSaved = false; _reservationRequest.Value = DataObject; NotifyTaskCompletion.Create(_dataReservationService.SaveAsync(_reservationRequest), (sender, args) => { if (sender is INotifyTaskCompletion <bool> taskCompletion) { if (taskCompletion.IsFaulted) { DialogService?.ShowErrorMessage("Error during saving: " + taskCompletion.ErrorMessage); } if (taskCompletion.IsSuccessfullyCompleted) { isSaved = true; } } }); if (isSaved) { var dataPayLoad = new DataPayLoad { Sender = ViewModelUri.ToString(), PayloadType = DataPayLoad.Type.UpdateView }; EventManager.NotifyObserverSubsystem("ReservationRequests", dataPayLoad); DialogService?.ShowErrorMessage("Data saved with success!"); } }
public GetSurveysViewModel(string authToken) { var surveys = DependencyService .Get <ISurveysService>(); _surveysList = new NotifyTaskCompletion <IEnumerable <SurveyDetailsEntity> >(surveys.RetrieveAsync(authToken)); }
protected override async Task OnRefreshAsync(CancellationToken ct) { try { this.ShowBusyStatus(Strings.Resources.TextLoading, true); this.RecommendedItemsTask = new NotifyTaskCompletion <IEnumerable <ContentItemBase> >(DataSource.Current.GetRecommendedItemsAsync(ct)); this.FriendsWatchedItemsTask = new NotifyTaskCompletion <IEnumerable <ContentItemBase> >(DataSource.Current.GetFriendsWatchedItemsAsync(ct)); // Load queue data var list = new QueueCollection(); list.AddRange(await DataSource.Current.GetQueueItemsAsync(Platform.Current.AuthManager.User?.ID, ct)); this.Queue = list; ct.ThrowIfCancellationRequested(); this.ShowBusyStatus("Updating tiles..."); await Platform.Current.Notifications.CreateOrUpdateTileAsync(this); this.ClearStatus(); } catch (OperationCanceledException) { this.ShowTimedStatus(Strings.Resources.TextCancellationRequested, 3000); } catch (Exception ex) { this.ShowTimedStatus(Strings.Resources.TextErrorGeneric); Platform.Current.Logger.LogError(ex, "Error during RefreshAsync"); } }
public CompanyModule(IRepository repository) { _repository = repository; // LoadPublishers(); CompanyLoading = NotifyTaskCompletion.Create(() => LoadCompaniesAsync()); }
public CategoriesListViewModel(IProductService service, INavigationService navi, IScanner scanner) { _service = service; _navi = navi; _scanner = scanner; Items = new NotifyTaskCompletion<List<Product>>(_service.GetProducts()); Categories = new NotifyTaskCompletion<List<string>>(_service.GetCategories()); NavigateToCategory = new RelayCommand<string>(async cat => { var items = (await _service.GetProductsForCategory(cat)) .OrderByDescending(i => i.Rating) .ToList(); if (items != null && items.Any()) { var page = App.GetProductsListPage(items, cat); await _navi.PushAsync(page); } else { await _navi.DisplayAlert("Error", "There are no items in the category " + cat); } }); _searchCommand = new RelayCommand(Search, () => !string.IsNullOrWhiteSpace(SearchTerm)); ScanCommand = new RelayCommand(async () => { var result = await _scanner.Scan(); SearchTerm = result.Text; Search(); }); }
public MainViewModel() { _client = new WebServiceRepositoryClient(); Services = new NotifyTaskCompletion<Service[]>(_client.GetServicesAsync()); Companies = new NotifyTaskCompletion<Company[]>(_client.GetCompaniesAsync()); }
protected override void DeleteItem(DataPayLoad payLoad) { bool isDeleted = false; NotifyTaskCompletion.Create(DeleteAsync(payLoad), (sender, args) => { if (sender is INotifyTaskCompletion <bool> taskCompletion) { if (taskCompletion.IsFaulted) { DialogService?.ShowErrorMessage("Error during aving: " + taskCompletion.ErrorMessage); } if (!taskCompletion.IsSuccessfullyCompleted) { return; } isDeleted = true; } }); if (isDeleted) { var dataPayLoad = new DataPayLoad { Sender = ViewModelUri.ToString(), PayloadType = DataPayLoad.Type.UpdateView }; EventManager.NotifyObserverSubsystem("ReservationRequests", dataPayLoad); UnregisterToolBar(payLoad.PrimaryKeyValue); DeleteRegion(); DialogService?.ShowErrorMessage("Data deleted with success!"); } }
public void ResultFromFinishedTask() { var fromResult = Task.FromResult(1); var completion = new NotifyTaskCompletion(fromResult); AssertCompletion.AreEqual(fromResult, completion); }
public void OnNavigatedTo(NavigationParameters parameters) { // Load all countries on load seems fine AllCountries = NotifyTaskCompletion.Create(async() => (await VkApi.GetAllCountriesAsync()) .Select(x => new SearchableCountry(x)) .ToLookup(x => char.ToUpperInvariant(x.DisplayName[0]))); }
private bool ToBool(object arg) { if (arg is bool) { return((bool)arg); } if (arg is int) { return((int)arg >= 0); } if (arg is Visibility) { return((Visibility)arg == Visibility.Visible); } NotifyTaskCompletion <object> completion = arg as NotifyTaskCompletion <object>; if (completion != null) { return(completion.IsCompleted); } return(false); }
public void StartAndNotify() { _incidentCompletion = NotifyTaskCompletion.Create <IEnumerable <BookingIncidentSummaryViewObject> >( _incidentService.GetPagedSummaryDoAsync(1, DefaultPageSize), (task, ev) => { if (task is INotifyTaskCompletion <IEnumerable <BookingIncidentSummaryViewObject> > summaryCollection) { if (summaryCollection.IsSuccessfullyCompleted) { var collection = summaryCollection.Result; if (SummaryView is IncrementalList <BookingIncidentSummaryViewObject> summary) { var maxItems = _incidentService.NumberItems; PageCount = _incidentService.NumberPage; var summaryList = new IncrementalList <BookingIncidentSummaryViewObject>(LoadMoreItems) { MaxItemCount = (int)maxItems }; summaryList.LoadItems(collection); SummaryView = summaryList; } } else { DialogService?.ShowErrorMessage("Cannot load more pages"); } } }); }
/// <summary> /// cached data is loaded on demand, but may take a while to load on initial reference /// so we force loading early while waiting for user to type in user name and password so they don't notice /// </summary> private void preloadCache() { var cache = DataRepository.GetDataRepository.ReferenceData; var t = new Task <bool>(() => { try { foreach (var item in ReferenceDataCache.ReferenceDataTypes) { var dummy = cache[item.TypeName]; } // if we didn't complete before user logged in and MainWindow created, then notify MainWindow we are done Mediator.InvokeCallback(nameof(LoadingCompletedMessage), null); return(true); } catch (Exception e) { errorTracking?.logger?.Fatal(e, "Failed to load cached reference data!"); return(false); } }); t.ConfigureAwait(false); t.Start(); LoadingCacheCompletion = new NotifyTaskCompletion <bool>(t); }
public MainViewModel(IFileService fileService, IDialogService dialogService) { _fileService = fileService ?? throw new ArgumentNullException(nameof(fileService)); _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService)); Users = new NotifyTaskCompletion <IList <User> >(_fileService.GetUsersStatistic()); }
public void StartAndNotify() { _reservationCompletion = NotifyTaskCompletion.Create <IEnumerable <ReservationRequestSummary> >( _reservationRequestDataService.GetPagedSummaryDoAsync(1, DefaultPageSize), (task, ev) => { if (task is INotifyTaskCompletion <IEnumerable <ReservationRequestSummary> > reservations) { if (reservations.IsSuccessfullyCompleted) { var collection = reservations.Result; if (SummaryView is IncrementalList <ReservationRequestSummary> summary) { var maxItems = _reservationRequestDataService.NumberItems; PageCount = _reservationRequestDataService.NumberPage; var summaryList = new IncrementalList <ReservationRequestSummary>(LoadMoreItems) { MaxItemCount = (int)maxItems }; summaryList.LoadItems(collection); SummaryView = summaryList; } } else { DialogService?.ShowErrorMessage("No puedo cargar datos de peticiones : " + reservations.ErrorMessage); } } }); }
private void RefreshPeople() { _nextPage = null; LoadPeopleTask = NotifyTaskCompletion.Create(LoadPeople); RaisePropertyChanged(() => LoadPeopleTask); }
public override void StartAndNotify() { _incidentCompletion = NotifyTaskCompletion.Create <IEnumerable <UsersSummary> >( _incidentService.GetPagedSummaryDoAsync(1, DefaultPageSize), (task, ev) => { if (task is INotifyTaskCompletion <IEnumerable <UsersSummary> > summaryCollection) { if (summaryCollection.IsSuccessfullyCompleted) { var collection = summaryCollection.Result; if (SummaryView is IncrementalList <UsersSummary> summary) { var maxItems = _incidentService.NumberItems; PageCount = __incidentService.NumberPage; var summaryList = new IncrementalList <UsersSummary>(LoadMoreItems) { MaxItemCount = (int)maxItems }; summaryList.LoadItems(collection); SummaryView = summaryList; } } else { DialogService?.ShowErrorMessage(ErrorConstants.DataLoadError + " : " + reservations.ErrorMessage); } } }); }
public PreferencesViewModel(IMvxNavigationService navigationService, IAuthService authService, IUserDialogs userDialogs, ITopNavigationViewModelService topNavigationViewModelService, IBottomNavigationViewModelService bottomNavigationViewModelService) { _navigationService = navigationService; _topNavigationViewModelService = topNavigationViewModelService; _bottomNavigationViewModelService = bottomNavigationViewModelService; _authService = authService; _userDialogs = userDialogs; ShowAddAlbumViewModelCommand = new MvxAsyncCommand(async() => await _navigationService.Navigate <ChangeAlbumViewModel>()); ShowAddArtistViewModelCommand = new MvxAsyncCommand(async() => await _navigationService.Navigate <ChangeArtistViewModel>()); ShowAddGenreViewModelCommand = new MvxAsyncCommand(async() => await _navigationService.Navigate <ChangeGenreViewModel>()); ShowAddPlaylistViewModelCommand = new MvxAsyncCommand(async() => await _navigationService.Navigate <ChangePlaylistViewModel>()); ShowAddSongViewModelCommand = new MvxAsyncCommand(async() => await _navigationService.Navigate <ChangeSongViewModel>()); LogOutCommand = new MvxCommand(() => { if (!IsTaskExecutedValueConverter.Convert(LogOutTask.Value)) { LogOutTask.Value = NotifyTaskCompletion.Create(AttemptLogOutAsync); } }); }
/// <summary> /// StartAndNotify. /// </summary> public void StartAndNotify() { _bookingSummaryCompletion = NotifyTaskCompletion.Create <IEnumerable <BookingSummaryViewObject> >( _bookingDataService.GetPagedSummaryDoAsync(1, DefaultPageSize), (sender, ev) => { if (sender is INotifyTaskCompletion <IEnumerable <BookingSummaryViewObject> > bookingSummary) { if (bookingSummary.IsFaulted) { DialogService?.ShowErrorMessage("Cannot load booking summary: " + bookingSummary.ErrorMessage); return; } var booking = bookingSummary.Result; var maxItems = _bookingDataService.NumberItems; PageCount = _bookingDataService.NumberPage; ItemCounts = maxItems.ToString(); var bookingList = new IncrementalList <BookingSummaryViewObject>(LoadMoreItems) { MaxItemCount = (int)maxItems }; bookingList.LoadItems(booking); SummaryView = bookingList; } }); }
/// <summary> /// Searches for a given word. /// </summary> /// <param name="word">The word to search for.</param> public void SearchForWord(string word) { // TODO: the dictionary search is recorded in the first call. Perhaps find a better design? this.SearchResultsStands4 = NotifyTaskCompletion.Create(SearchForWordStands4Async(word)); this.SearchResultsCollins = NotifyTaskCompletion.Create(SearchForWordCollinsAsync(word)); this.SearchResultsNetSpeakPreceding = NotifyTaskCompletion.Create(SearchForWordNetSpeakPrecedingAsync(word)); this.SearchResultsNetSpeakFollowing = NotifyTaskCompletion.Create(SearchForWordNetSpeakFollowingAsync(word)); this.SearchResultsStringNet = NotifyTaskCompletion.Create(SearchForWordStringNetAsync(word)); Task.Run(async() => { try { await SaveDictionarySearchAsync(word); } catch (AggregateException ae) { ae.Handle(ex => { Tools.Logger.Log("SaveDictionaryExternalHandler", ex); return(true); // Handled }); } }); }
/// <summary> /// Generic method used for navigating. Retrieve an unique id for the new view and generate a view payload to be sent. /// </summary> /// <typeparam name="Entity">Entity Type of the view (same name as db column) </typeparam> /// <typeparam name="Dto">Data transfer object to be used.</typeparam> /// <param name="e">Entity</param> /// <param name="viewName">Name of the view</param> private void NewHelperView <Entity, Dto>(Entity e, string viewName, Uri viewModelUri) where Dto : BaseViewObject where Entity : class { var helperDataService = _dataService.GetHelperDataServices(); var id = string.Empty; NotifyTaskCompletion.Create <string>(helperDataService.GetUniqueId(e), (task, ev) => { if (task is INotifyTaskCompletion <string> result) { if (result.IsSuccessfullyCompleted) { id = result.Task.Result; } else { _dialogService?.ShowErrorMessage("Error in identifier generation"); } } }); var currentUri = new Uri(viewModelUri.ToString() + id); var factory = DataPayloadFactory.GetInstance(); var helperDto = Activator.CreateInstance <Dto>(); helperDto.Code = id; var dataPayload = factory.BuildInsertPayLoadDo <Dto>(viewName, helperDto, DataSubSystem.HelperSubsytsem, currentUri.ToString(), currentUri.ToString(), currentUri); NavigateView.Navigate(_regionManager, viewName); }
public ChangeArtistViewModel(IMvxNavigationService navigationService, IUserDialogs userDialogs, IValidator validator, IArtistService artistService, IBottomNavigationViewModelService bottomNavigationViewModelService, ITopNavigationViewModelService topNavigationViewModelService) { _navigationService = navigationService; _topNavigationViewModelService = topNavigationViewModelService; _bottomNavigationViewModelService = bottomNavigationViewModelService; _userDialogs = userDialogs; _validationHelper = new ValidationHelper(validator, this, Errors.Value, (propertyName) => { FocusName.Value = propertyName; }); _artistService = artistService; ValidateNameCommand = new MvxCommand(() => _validationHelper.Validate(() => Name)); InitValidationCommand = new MvxCommand(() => { _validationHelper.ResetValidation(); }); ChangeCommand = new MvxCommand(() => { if (!IsTaskExecutedValueConverter.Convert(ChangeTask.Value)) { ChangeTask.Value = NotifyTaskCompletion.Create(AttemptChangeAsync); } }); }
protected override void DeleteItem(DataPayLoad payLoad) { NotifyTaskCompletion.Create <bool>(this.DeleteAsync(payLoad), ev: (sender, args) => { if (!(sender is INotifyTaskCompletion <bool> taskCompletion)) { return; } if (taskCompletion.IsFaulted) { DialogService?.ShowErrorMessage("Error during deleting the invoice"); } if (!taskCompletion.IsSuccessfullyCompleted) { return; } var dataPayLoad = new DataPayLoad() { Sender = ViewModelUri.ToString(), PayloadType = DataPayLoad.Type.UpdateView }; EventManager.NotifyObserverSubsystem(InvoiceModule.InvoiceSubSystem, dataPayLoad); UnregisterToolBar(payLoad.PrimaryKey); DeleteRegion(); }); }
public override void ExecutePayload(IDataServices services, IEventManager manager, ref DataPayLoad payLoad) { DataServices = services; EventManager = manager; CurrentPayload = payLoad; ToolbarInitializationNotifier = NotifyTaskCompletion.Create <DataPayLoad>(HandleSaveOrUpdate(payLoad), ExecutedPayloadHandler); }
public MainViewModel(IBillCalculator billCalculator, Task<IUserRepository> userRepositoryTask, IFuelPriceAccesser fuelPriceAccesser, ITaksariDialogService messageBoxes) { //Register messengers IMvxMessenger messenger = Mvx.Resolve<IMvxMessenger>(); messenger.Subscribe<ToggleUserActivityMessage>(OnToggleUserActivityMessageReceived, MvxReference.Strong); messenger.Subscribe<DeleteUserMessage>(OnDeleteUserMessageReceived, MvxReference.Strong); messenger.Subscribe<PaymentRequestedMessage>(OnPaymentRequestedMessageReceived, MvxReference.Strong); //FuelPriceAccesser. PropertyChangedEvent is handled for setting new fuelprices to _appsettings AppSettings.FuelPricesAreUpToDate = false; fuelPriceAccesser.FuelPricesUpdated += OnFuelPricesUpdated; //UserRepository _userRepositoryTask = userRepositoryTask; //Init SortingObservableCollections ActiveUserViewModelsTask = new NotifyTaskCompletion<ObservableCollection<IUserViewModel>>(InitActiveUserViewModelsAsync()); ActiveUserViewModelsTask.PropertyChanged += OnActiveUsersTaskPropertyChanged; InActiveUserViewModelsTask = new NotifyTaskCompletion<ObservableCollection<IUserViewModel>>(InitInActiveUserViewModelsAsync()); //BillCalculator _billCalculator = billCalculator; _billCalculator.CostsPerKm = AppSettings.FinalCostsPerKm; _billCalculator.BillsChanged += OnBillsChanged; _billCalculator.LocatorStatusChanged += OnLocatorStatusChanged; //Message boxes _dialogService = messageBoxes; //Default LocatorStatus LocatorStatus = new BindablePositionStatus(WrappedPositionStatus.Ready); }
public async Task <IAssistResult <T1> > HandleAssist <T, T1>(IAssist assist) where T : class where T1 : class { var list = await HelperDataServices.GetPagedQueryDoAsync <T>(assist.Query, 1, 100); var count = await HelperDataServices.GetItemsCount <T>(); var resultMapped = _mapper.Map <IEnumerable <T>, IEnumerable <T1> >(list); IncrementalList <T1> valueList = new IncrementalList <T1>(LoadItems); valueList.LoadItems(resultMapped); valueList = new IncrementalList <T1>((x, index) => { NotifyTaskCompletion.Create(HelperDataServices.GetPagedQueryDoAsync <T>(assist.Query, index, 100), (sender, arg) => { if (sender is INotifyTaskCompletion <IEnumerable <T> > taskCompleted) { if (taskCompleted.IsSuccessfullyCompleted) { var resultValue = _mapper.Map <IEnumerable <T>, IEnumerable <T1> >(taskCompleted.Result); valueList.LoadItems(resultValue); } } }); }) { MaxItemCount = count }; T1 assistResult = valueList.FirstOrDefault(); IAssistResult <T1> result = new AssistResult <T1>(assistResult, valueList); return(result); }
private void RemoveSessionProc() { var result = MessageBox.Show("Are you sure you want to delete selected session?", "Session", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { try { var enrollments = _repository.Enrollment.GetRange(c => c.SessionCode == SelectedSession.Model.SessionId); if (enrollments.Count > 0) { MessageBox.Show("Unable to delete sessions with enrollees"); } else { NotifyTaskCompletion.Create(RemoveSessionAsync); } } catch (Exception e) { MessageBox.Show("Unable to delete opening"); } } }
public void NotifierT_TaskCompletesSuccessfully_NotifiesProperties() { var tcs = new TaskCompletionSource <object>(); var notifier = NotifyTaskCompletion.Create(tcs.Task); var taskNotification = PropertyNotified(notifier, n => n.Task); var statusNotification = PropertyNotified(notifier, n => n.Status); var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted); var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted); var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled); var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted); var exceptionNotification = PropertyNotified(notifier, n => n.Exception); var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException); var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage); var resultNotification = PropertyNotified(notifier, n => n.Result); tcs.SetResult(null); Assert.IsFalse(taskNotification()); Assert.IsTrue(statusNotification()); Assert.IsTrue(isCompletedNotification()); Assert.IsTrue(isSuccessfullyCompletedNotification()); Assert.IsFalse(isCanceledNotification()); Assert.IsFalse(isFaultedNotification()); Assert.IsFalse(exceptionNotification()); Assert.IsFalse(innerExceptionNotification()); Assert.IsFalse(errorMessageNotification()); Assert.IsTrue(resultNotification()); }
public AddStations(MainWindow mainWindow) { GetAllStationsAsync = new NotifyTaskCompletion <List <Stations> >(client.GetAllStationsAsync(new System.Net.Http.HttpClient())); this.mainWindow = mainWindow; DataContext = this; InitializeComponent(); }
public void Notifier_TaskFaulted_NotifiesProperties() { var tcs = new TaskCompletionSource(); var notifier = NotifyTaskCompletion.Create(tcs.Task); var taskNotification = PropertyNotified(notifier, n => n.Task); var statusNotification = PropertyNotified(notifier, n => n.Status); var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted); var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted); var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled); var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted); var exceptionNotification = PropertyNotified(notifier, n => n.Exception); var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException); var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage); tcs.SetException(new NotImplementedException()); Assert.IsFalse(taskNotification()); Assert.IsTrue(statusNotification()); Assert.IsTrue(isCompletedNotification()); Assert.IsFalse(isSuccessfullyCompletedNotification()); Assert.IsFalse(isCanceledNotification()); Assert.IsTrue(isFaultedNotification()); Assert.IsTrue(exceptionNotification()); Assert.IsTrue(innerExceptionNotification()); Assert.IsTrue(errorMessageNotification()); }
private void RemoveCandidateProc() { var result = MessageBox.Show("Are you sure you want to delete selected candidate?", "Candidate", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { try { var history = _repository.History.GetRange(c => c.CandidateId == SelectedCandidate.Model.CandidateId); var canQual = _repository.CanQualify.GetRange(c => c.CandidateId == SelectedCandidate.Model.CandidateId); if (history.Count > 0) { MessageBox.Show("Unable to delete candidates with history"); } else if (canQual.Count > 0) { MessageBox.Show("Unable to delete candidates with qualifications."); } else { NotifyTaskCompletion.Create(RemoveCandidateAsync); } } catch (Exception e) { MessageBox.Show("Unable to delete opening"); } } }
/// <summary> /// This enable incremental load of the data. /// </summary> /// <param name="count"></param> /// <param name="baseIndex"></param> protected override void LoadMoreItems(uint count, int baseIndex) { var brokerDataService = DataServices.GetCommissionAgentDataServices(); NotifyTaskCompletion.Create <IEnumerable <CommissionAgentSummaryViewObject> >( brokerDataService.GetPagedSummaryDoAsync(baseIndex, DefaultPageSize), PagingEvent); }
public LoginViewModel(IMvxNavigationService navigationService, IAuthService authService, IUserDialogs userDialogs, IValidator validator, IBottomNavigationViewModelService bottomNavigationViewModelService, ITopNavigationViewModelService topNavigationViewModelService) { _navigationService = navigationService; _topNavigationViewModelService = topNavigationViewModelService; _bottomNavigationViewModelService = bottomNavigationViewModelService; _authService = authService; _userDialogs = userDialogs; _validationHelper = new ValidationHelper(validator, this, Errors.Value, (propertyName) => { FocusName.Value = propertyName; }); ValidateEmailCommand = new MvxCommand(() => _validationHelper.Validate(() => Email)); ValidatePasswordCommand = new MvxCommand(() => _validationHelper.Validate(() => Password)); InitValidationCommand = new MvxCommand(() => { _validationHelper.ResetValidation(); }); LogInCommand = new MvxCommand(() => { if (!IsTaskExecutedValueConverter.Convert(LogInTask.Value)) { LogInTask.Value = NotifyTaskCompletion.Create(AttemptLogInAsync); } }); ShowRegistrationViewModelCommand = new MvxAsyncCommand(async() => { await _navigationService.Navigate <RegistrationViewModel>(); }); }
public async Task Test() { var notifyTask = new NotifyTaskCompletion <bool>(async() => await Task.Run(() => true)); await notifyTask; Assert.IsTrue(notifyTask); }
public DashboardViewModel(IServiceFactory serviceFactory) { _serviceFactory = serviceFactory; RecalculateCostsForAssemblyCommand = new DelegateCommand<string>(OnRecalculateCostsForAssemblyCommand); RecalculateCommand = new DelegateCommand<string>(OnRecalculateCommand); LatestVersion = new NotifyTaskCompletion<string>(getLatestVersionNumberAsync("https://github.com/AlexZhidkov/BedfordHarbourBOM/releases/latest")); }
protected override async Task OnLoadStateAsync(LoadStateEventArgs e, bool isFirstRun) { if(this.View != null) this.View.GotFocus += View_GotFocus; this.AppCacheTask = new NotifyTaskCompletion<string>(Platform.Current.Storage.GetAppDataCacheFolderSizeAsync()); await base.OnLoadStateAsync(e, isFirstRun); }
public ViewModel (IFeeder feeder) { _feeder = feeder; ScheduleEntries = new NotifyTaskCompletion<ObservableCollection<ScheduleEntryViewModel>> (GetSchedule ()); ScheduleEntries.PropertyChanged += (object sender, PropertyChangedEventArgs e) => { if(e.PropertyName == "Result") { AddMealCommand = new RelayCommand (o => { ScheduleEntries.Result.Add (new ScheduleEntryViewModel ()); }); CommitScheduleCommand = new RelayCommand (async o => await SetSchedule (ScheduleEntries.Result)); } }; RunCommand = new RelayCommand (o => _feeder.Feed ()); }
public CategoriesListViewModel(IProductService service, IAppNavigation navi, IScanner scanner, LogOutCommand logOut) { _service = service; _navi = navi; _scanner = scanner; _logOut = logOut; MessagingCenter.Subscribe<Category>(this, Messages.NavigateTo, NavigateToCategory); _searchCommand = new Command(Search, () => !string.IsNullOrWhiteSpace(SearchTerm)); ScanCommand = new Command(async () => { var result = await _scanner.Scan(); SearchTerm = result.Text; Search(); }); AboutCommand = new Command(async () => await _navi.ShowAbout()); Categories = new NotifyTaskCompletion<List<CategoryViewModel>>(GetCategories()); }
protected override async Task OnRefreshAsync(CancellationToken ct) { try { this.ShowBusyStatus(Strings.Resources.TextLoading, true); this.RecommendedItemsTask = new NotifyTaskCompletion<IEnumerable<ContentItemBase>>(DataSource.Current.GetRecommendedItemsAsync(ct)); this.FriendsWatchedItemsTask = new NotifyTaskCompletion<IEnumerable<ContentItemBase>>(DataSource.Current.GetFriendsWatchedItemsAsync(ct)); // Load queue data var list = new QueueCollection(); list.AddRange(await DataSource.Current.GetQueueItemsAsync(Platform.Current.AuthManager.User?.ID, ct)); this.Queue = list; ct.ThrowIfCancellationRequested(); this.ShowBusyStatus("Updating tiles..."); await Platform.Current.Notifications.CreateOrUpdateTileAsync(this); this.ClearStatus(); } catch (OperationCanceledException) { this.ShowTimedStatus(Strings.Resources.TextCancellationRequested, 3000); } catch (Exception ex) { this.ShowTimedStatus(Strings.Resources.TextErrorGeneric); Platform.Current.Logger.LogError(ex, "Error during RefreshAsync"); } }
/// <summary> /// Calls the ILineService with submitted points. /// </summary> private async Task AddLine(Point startPoint, Point endPoint) { // Clear error message this.State = CanvasState.BusyState; this.ErrorMessage = null; this.TimeMessage = null; // Query the ILineService with selected start and end points. this.AddLineTask = new NotifyTaskCompletion<LineQueryResult>( this.lineService.AddLineAsync(startPoint, endPoint, PathAlgorithm, cancelToken.Token)); LineQueryResult result = await this.AddLineTask.Task; // Process the query result. if (this.AddLineTask.IsSuccessfullyCompleted && result.Success) { this.Lines.Add(result.Result); this.TimeMessage = result.Time + " MS"; this.State = CanvasState.ReadyState; } else { this.ErrorMessage = result.Message; this.State = CanvasState.ErrorState; } }
private void RefreshPurchaseCollection() { PurchaseTicketsTask = new NotifyTaskCompletion<ObservableCollection<PurchaseTicket>> (_customerOperationProvider.GetAllPurchaseTicketAsync()); }
public WelcomeViewModel(IAppNavigation navi) { _navi = navi; _slim = new SemaphoreSlim(0, 1); IsBusy = new NotifyTaskCompletion<int>(GoToFirstPage()); }
public MainViewModel() { UrlByteCount = new NotifyTaskCompletion<int>( MyStaticService.CountBytesInUrlAsync("http://www.example.com")); }
static BillHelper() { CateGoryItems = new NotifyTaskCompletion<ObservableCollection<BillCategoryItem>>(getCagegoryTask()); }
public InstagramExplorerViewModel( IViewModelNavigator navigator, InstagramExplorer instagramExplorer, SettingsProvider settings, ImagePrinter printer, PatternViewModelProvider patternVMProvider, ImageUtils imageUtils, IMappingEngine mappingEngine) { _navigator = navigator; _printer = printer; _patternVmProvider = patternVMProvider; _imageUtils = imageUtils; _mappingEngine = mappingEngine; _instagramExplorer = instagramExplorer; AppSettingsDto appSettings = settings.GetAppSettings(); if (appSettings != null) _printerName = appSettings.PrinterName; IsHashTag = true; SearchAsyncOperation= new NotifyTaskCompletion<ImageResponse>(Task.FromResult(default(ImageResponse))); _searchTokenSource= new CancellationTokenSource(); }
private void Search(string text) { if (!string.IsNullOrEmpty(_previousSearch)) { if (string.Compare(text, _previousSearch, StringComparison.OrdinalIgnoreCase) != 0) { _nextUrl = null; Images.Clear(); } } _previousSearch = text; SearchCommand.RaiseCanExecuteChanged(); _searchTokenSource.Cancel(); _searchTokenSource= new CancellationTokenSource(); SearchAsyncOperation = new NotifyTaskCompletion<ImageResponse>(SearchUpdateImages(text, _searchTokenSource.Token)); }
public override async Task ExecuteAsync(object parameter) { if (!CanExecute(parameter)) { return; } Execution = new NotifyTaskCompletion(_execute()); RaiseCanExecuteChanged(); await Execution.TaskCompletion; RaiseCanExecuteChanged(); }
private async Task ClearAppDataCacheAsync() { await Platform.Current.Storage.ClearAppDataCacheFolderAsync(); this.AppCacheTask = new NotifyTaskCompletion<string>(Platform.Current.Storage.GetAppDataCacheFolderSizeAsync()); }