public ActionResult About() { ViewBag.Message = "Your application description page."; BackgroundTaskManager.Run(async() => { try { Logger.Current.Info("- Background task started"); var j = new Jobs.SampleJob(); await j.DoSomething(3, BackgroundTaskManager.Shutdown); } //catch (OperationCanceledException ex) //{ // Logger.Current.Error(new Exception("- Operation cancelled", ex)); //} catch (Exception ex) { Logger.Current.Error(ex); } finally { Logger.Current.Info("- Background task ended"); } }); return(View()); }
/// <summary> /// Відправити асинхронно електронний лист, не чикаючи результату відправки. /// </summary> /// <param name="to">адресат</param> /// <param name="viewPath">вигляд/шаблон, по якому потрібно згенерувати лист</param> /// <param name="model">модель даних, які потрібно відобразити в листі</param> protected void StartEmailSending(string to, string viewPath, object model = null) { SetCurrentCulture(); var mail = this.RenderMail(viewPath, model); // http://blog.stephencleary.com/2012/12/returning-early-from-aspnet-requests.html BackgroundTaskManager.Run(() => { try { mail.Send(to); } catch (Exception ex) { Trace.TraceError("Email sending to {0} error! {1}", to, ex); } finally { try { mail.Dispose(); } catch { } } }); }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (!Program.busy && !BackgroundTaskManager.IsBusy()) { return; } string reason = ""; if (BackgroundTaskManager.IsBusy()) { reason = "Some background tasks have not finished yet."; } if (Program.busy) { reason = "The program is still busy."; } DialogResult dialog = MessageBox.Show($"Are you sure you want to exit the program?\n\n{reason}", "Are you sure?", MessageBoxButtons.YesNo); if (dialog == DialogResult.No) { e.Cancel = true; } }
private void OnSettingsChanged(DataGrid dataGrid, IFieldMapperGridViewModel fmgvm) { if (_updatePending) { return; } _updatePending = true; BackgroundTaskManager.DelayedPostIfPossible( () => { _updatePending = false; foreach (var column in dataGrid.Columns) { var matchingViewModelColumn = fmgvm.Columns.Where(col => col.Header == column.SortMemberPath).FirstOrDefault(); if (matchingViewModelColumn != null) { var pfd = new PrivateFieldData(); pfd.DisplayIndex = column.DisplayIndex; pfd.SortDirection = column.SortDirection; pfd.Visibility = column.Visibility; matchingViewModelColumn.InternalProperties = pfd; } } fmgvm.RaiseColumnSettingsChanged(); return(true); }); }
private void setUpBackgroundWorker() { Action <List <FileListViewItemViewModel> > updateSubEntries = (result) => { List <FileListViewItemViewModel> delList = new List <FileListViewItemViewModel>(SubEntriesInternal.ToArray()); List <FileListViewItemViewModel> addList = new List <FileListViewItemViewModel>(); foreach (FileListViewItemViewModel model in result) { if (delList.Contains(model)) { delList.Remove(model); } else { addList.Add(model); } } foreach (FileListViewItemViewModel model in delList) { SubEntriesInternal.Remove(model); } foreach (FileListViewItemViewModel model in addList) { SubEntriesInternal.Add(model); } DirectoryCount = (uint)(from model in SubEntriesInternal where model.EmbeddedModel is DirectoryModel select model).Count(); FileCount = (uint)(SubEntriesInternal.Count - DirectoryCount); HasSubEntries = SubEntriesInternal.Count > 0; }; bgWorker_LoadSubEntries = new BackgroundTaskManager <List <FileListViewItemViewModel> >( () => { IsLoading = true; return(getEntries()); }, (result) => { updateSubEntries(result); IsLoading = false; }); bgWorker_FilterSubEntries = new BackgroundTaskManager <List <FileListViewItemViewModel> >( () => { IsLoading = true; return(filterEntries()); }, (result) => { updateSubEntries(result); IsLoading = false; }); }
public void setupBgWorker() { bgWorker_updateItems = new BackgroundTaskManager <object, NotificationItemViewModel[]>( (x) => { var vmEnum = from m in _embeddedSourceModel.GetNotificationItems() where !_removedList.Contains(m.ID) select m.ToViewModel(); return(new List <NotificationItemViewModel>(vmEnum).ToArray()); }, (vms) => { _notificationItemList.Clear(); foreach (var vm in vms) { vm.ParentModel = this; _notificationItemList.Add(vm); } HasNotification = _notificationItemList.Count > 0; }); bgWorker_updateItems.RunBackgroundTask(); }
public void Execute(int databaseId) { try { Logger.Info($"{GetType().Name} - [Common Background Tasks] Starting job for organization with database id: {databaseId}"); //should get older background tasks with status new and one by one to try processing it before processing try to change status and after processing update status //processing itself should happen like listener.Process method var org = _orgManager.GetById(databaseId); if (!string.IsNullOrEmpty(org.ConnectionString)) { IBackgroundTaskManager taskManager = new BackgroundTaskManager(org.ConnectionString, Process.GetCurrentProcess().ProcessName); var repo = new Common.Repository.PricingRepository(org.ConnectionString, Constants.TIMEOUT_MSMQ_EXEC_STOREDPROC); var engine = new PriceEngine(repo, Logger); var tasks = taskManager.ListTasks(Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.New, null, null, false, 100, 0); BackgroundTaskProcessor processor = new BackgroundTaskProcessor(databaseId, org.ConnectionString, _databaseManager, engine, Logger); foreach (var t in tasks) { try { Logger.Info($"Task {t.Id} Processing"); var res = taskManager.UpdateTaskStatus(t.Id, t.Status, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.InProgress, string.Empty).Result; processor.ProcessMessage(t); res = taskManager.UpdateTaskStatus(t.Id, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.InProgress, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.Completed, string.Empty).Result; Logger.Info($"Task {t.Id} Processing Complete"); } catch (Exception ex) { var res = taskManager.UpdateTaskStatus(t.Id, null, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.Failed, ex.Message).Result; } } } else { Logger.Warn($"OrganizationId {databaseId} not found"); } Logger.Info($"{GetType().Name} - [Common Background Tasks] Finishing job for organization with database id: {databaseId}"); } catch (Exception ex) { var errorMessage = new StringBuilder(); errorMessage.AppendFormat($"{GetType().Name} - [Common Background Tasks] error for organization with database id: {databaseId} "); if (!string.IsNullOrEmpty(ex.Message)) { errorMessage.AppendFormat($"Exception message is: {ex.Message} "); } if (ex.InnerException != null && (!string.IsNullOrEmpty(ex.InnerException.Message))) { errorMessage.AppendFormat($"Inner Exception message is: {ex.InnerException.Message}"); } Logger.Error(errorMessage.ToString()); } }
/// <summary> /// Setup backgrounder worker Task/Completion action /// to fetch Orders for Customers /// </summary> private void SetUpBackgroundWorker() { bgWorker = new BackgroundTaskManager <DispatcherNotifiedObservableCollection <OrderModel> >( () => { return(new DispatcherNotifiedObservableCollection <OrderModel>( DataAccess.DataService.FetchAllOrders( CurrentCustomer.CustomerId.DataValue).ConvertAll( new Converter <Order, OrderModel>( OrderModel.OrderToOrderModel)))); }, (result) => { CurrentCustomer.Orders = result; if (customerOrdersView != null) { customerOrdersView.CurrentChanged -= CustomerOrdersView_CurrentChanged; } customerOrdersView = CollectionViewSource.GetDefaultView(CurrentCustomer.Orders); customerOrdersView.CurrentChanged += CustomerOrdersView_CurrentChanged; customerOrdersView.MoveCurrentToPosition(-1); HasOrders = CurrentCustomer.Orders.Count > 0; }); }
/// <summary> /// Async version of DeleteContentsOfDir, won't block main thread. /// </summary> public static async Task <bool> DeleteContentsOfDirAsync(string path) { ulong taskId = BackgroundTaskManager.Add($"DeleteContentsOfDirAsync {path}"); bool returnVal = await Task.Run(async() => { return(DeleteContentsOfDir(path)); }); BackgroundTaskManager.Remove(taskId); return(returnVal); }
public LocationAlarmModel(IRepository <Alarm> repository, IGeofenceService geofenceService, BackgroundTaskManager <GeofenceTask> backgroundTaskManager, GeofenceBuilder builder) { _repository = repository; _geofenceService = geofenceService; _backgroundTaskManager = backgroundTaskManager; _builder = builder; _backgroundTaskManager.TaskCompleted += BackgroundTaskManagerOnTaskCompleted; GeolocationAlarms = new ObservableCollection <Alarm>(); }
private async void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs s) { D("Application suspending"); var deferral = s.SuspendingOperation.GetDeferral(); try { try { await Core.SuspendAsync(); D($"{nameof(Core)} suspended"); } catch (Exception e) { D($"Core suspending error: {e.Message}"); } try { var cacheFile = await GetCacheFileAsync(); var props = await cacheFile.GetBasicPropertiesAsync(); D($"Database file obtained, size {((long)props.Size).SizedString()}"); if (props.Size > 0) { await cacheFile.DeleteAsync(); cacheFile = await GetCacheFileAsync(); D("Database file refreshed"); } await FileIO.WriteBytesAsync( cacheFile, Core.ToPersistentByteArray() ); D("Database written"); } catch (Exception e) { D($"Database writting failed: {e.Message}"); } PActionManager.Save(); D($"{nameof(PActionManager)} saved"); BackgroundTaskManager.UnregisterTasks(); BackgroundTaskManager.RegisterTasks(); } finally { D("Application suspended"); deferral.Complete(); } }
private async Task RegisterBackgroundTaskAsync() { if (_backgroundTaskManager == null) { _backgroundTaskManager = Container.Resolve <BackgroundTaskManager <GeofenceTask> >(); } await _backgroundTaskManager.RegisterBackgroundTaskAsync().ConfigureAwait(false); }
/// <summary> /// Async (background thread) version of TryDeleteIfExists. Safe to run without awaiting. /// </summary> public static async Task <bool> TryDeleteIfExistsAsync(string path, int retries = 10) { string renamedPath = path; try { if (IsPathDirectory(path)) { while (Directory.Exists(renamedPath)) { renamedPath += "_"; } if (path != renamedPath) { Directory.Move(path, renamedPath); } } else { while (File.Exists(renamedPath)) { renamedPath += "_"; } if (path != renamedPath) { File.Move(path, renamedPath); } } path = renamedPath; ulong taskId = BackgroundTaskManager.Add($"TryDeleteIfExistsAsync {path}"); bool returnVal = await Task.Run(async() => { return(TryDeleteIfExists(path)); }); BackgroundTaskManager.Remove(taskId); return(returnVal); } catch (Exception e) { Logger.Log($"TryDeleteIfExistsAsync Move Exception: {e.Message} [{retries} retries left]", true); if (retries > 0) { await Task.Delay(2000); retries -= 1; return(await TryDeleteIfExistsAsync(path, retries)); } else { return(false); } } }
static void Main(string[] args) { while (true) { Console.WriteLine("\nSend Message: "); var message = Console.ReadLine(); BackgroundTaskManager.Run(() => { Send.Message(message); }); } }
/// <summary> /// Initializes BackgroundEngine. /// </summary> public async Task InitializeAsync() { await SdkEngine.InitializeAsync(); AppSettings = await ServiceManager.SettingsManager.GetSettings(); //TODO verfiy if (BackgroundTaskManager.CheckIfBackgroundFilterUpdateIsRequired()) { ToastNotification toastNotification = NotificationUtils.CreateToastNotification("New beacon signature available", "Launch the application to update"); NotificationUtils.ShowToastNotification(toastNotification); } }
public LazyLoader(Func <T> loadFunc, Func <T> loadFunc2) { _loadFunc = loadFunc; _loadFunc2 = loadFunc2; bgWorker = new BackgroundTaskManager <Func <T>, T>( (func) => { return(func()); }, (result) => { Value = result; }); }
protected async void Connect(string uri) { if (WebSocket != null) { if (WebSocket.State == WebSocketState.Open) { sendReceiveCancellationTokenSource?.Cancel(); Disconnect(); } WebSocket = null; sendReceiveCancellationTokenSource = null; sendReceiveCancellationToken = CancellationToken.None; } WebSocket = new ClientWebSocket(); WebSocket.Options.KeepAliveInterval = new TimeSpan(0, 0, 10); SendQueue = null; SendQueue = new BlockingCollection <byte[]>(); sendReceiveCancellationTokenSource = new CancellationTokenSource(); sendReceiveCancellationToken = sendReceiveCancellationTokenSource.Token; await WebSocket.ConnectAsync(new Uri(uri), sendReceiveCancellationToken) .ContinueWith( task => { if (WebSocket.State != WebSocketState.Open) { OnError(new Exception("Cannot open Premise Connection!")); return; } OnConnect(); BackgroundTaskManager.Run(() => { StartSending(sendReceiveCancellationToken); }); BackgroundTaskManager.Run(() => { StartReceiving(sendReceiveCancellationToken); }); }, sendReceiveCancellationToken).ConfigureAwait(false); }
public BackgroundTaskController( ShellSettings shellSettings, IAuthorizationService authorizationService, IEnumerable <IBackgroundTask> backgroundTasks, BackgroundTaskManager backgroundTaskManager, IShapeFactory shapeFactory, ISiteService siteService, IStringLocalizer <BackgroundTaskController> stringLocalizer) { _tenant = shellSettings.Name; _authorizationService = authorizationService; _backgroundTasks = backgroundTasks; _backgroundTaskManager = backgroundTaskManager; New = shapeFactory; _siteService = siteService; S = stringLocalizer; }
private void setUpBackgroundWorker() { bgWorker_findChild = new BackgroundTaskManager <DirectoryTreeItemViewModel>( () => { IsLoading = true; DirectoryTreeItemViewModel lookingUpModel = _selectedDirectoryModel; Func <bool> cancelNow = () => { bool cont = lookingUpModel != null && lookingUpModel.Equals(_selectedDirectoryModel); return(!cont); }; DirectoryTreeItemViewModel newSelectedModel = null; { DirectoryInfoEx newSelectedDir = _selectedDirectory; if (newSelectedDir != null) { foreach (DirectoryTreeItemViewModel rootModel in _rootDirectoryModelList) { newSelectedModel = rootModel.LookupChild(newSelectedDir, cancelNow); if (newSelectedModel != null) { return(newSelectedModel); } } } } return(_rootDirectoryModelList.Count == 0 ? null : _rootDirectoryModelList[0]); }, (result) => { if (result != null) { if (result.Equals(_selectedDirectoryModel)) { result.IsSelected = true; } } IsLoading = false; }); }
private BackgroundTaskManager InitBackgroundTaskManager() { lock (_staticLocker) { if (_backgroundTaskManager != null) { return(_backgroundTaskManager); } _backgroundTaskManager = new BackgroundTaskManager(ViewManager); _backgroundTaskManager.RegisterDiscardable(Constants.Tasks.LoadChangesetsTaskKey); _backgroundTaskManager.RegisterDiscardable(Constants.Tasks.LoadWorkItemsTaskKey); _backgroundTaskManager.RegisterDiscardable(Constants.Tasks.LoadRootQueryTaskKey); _backgroundTaskManager.RegisterDiscardable(Constants.Tasks.LoadCompleteBranchListTaskKey); _backgroundTaskManager.RegisterDiscardable(Constants.Tasks.LoadAllAssociatedChangesetsIncludingMergesKey); _backgroundTaskManager.RegisterDiscardable(Constants.Tasks.CheckTfsUserTaskKey); return(_backgroundTaskManager); } }
public static void StartDelSubscriptionNotification(string mandatorId, int subscriptionId) { LoggerManager.GetLogger().Trace("Calling async method to perform notifications"); BackgroundTaskManager.Run(() => { try { LoggerManager.GetLogger().Trace("EventSite notifications started."); Notification notification = new Notification(mandatorId); notification.BeginDelSubscriptionNotification(subscriptionId); } catch (Exception ex) { LoggerManager.GetLogger().ErrorException($"Error occured while executing async notification for {nameof(StartDelSubscriptionNotification)}", ex); } }); LoggerManager.GetLogger().Trace("Called async method to perform notifications"); }
public static void StartLiftSaveNotification(string mandatorId, string action, string definition, int eventId, int contactIdToNotify, int liftContactId) { LoggerManager.GetLogger().Trace("Calling async method to perform notifications"); BackgroundTaskManager.Run(() => { try { LoggerManager.GetLogger().Trace("EventSite notifications started."); Notification notification = new Notification(mandatorId); notification.BeginLiftSaveNotification(action, definition, eventId, contactIdToNotify, liftContactId); } catch (Exception ex) { LoggerManager.GetLogger().ErrorException($"Error occured while executing async notification for {nameof(StartLiftSaveNotification)}", ex); } }); LoggerManager.GetLogger().Trace("Called async method to perform notifications"); }
public void DispatchIndeterminateTest() { var uiDispatcher = new MockUiDispatcher(); var manager = new BackgroundTaskManager(uiDispatcher); var countdown = new CountdownEvent(4); var state = "State"; manager.TaskStarted += (t, s) => { Assert.IsTrue(t.IsIndeterminate); Assert.AreEqual(s, state); Assert.AreEqual(uiDispatcher.ThreadId, Thread.CurrentThread.ManagedThreadId); Assert.AreEqual(4, countdown.CurrentCount); countdown.Signal(); }; manager.TaskCompleted += (t, s) => { Assert.IsTrue(t.IsIndeterminate); Assert.AreEqual(s, state); Assert.AreEqual(uiDispatcher.ThreadId, Thread.CurrentThread.ManagedThreadId); Assert.AreEqual(1, countdown.CurrentCount); countdown.Signal(); }; manager.Dispatch(s => { Assert.AreEqual(state, s); Assert.AreNotEqual(uiDispatcher.ThreadId, Thread.CurrentThread.ManagedThreadId); Assert.AreEqual(3, countdown.CurrentCount); countdown.Signal(); return("Result"); }, (r, s) => { Assert.AreEqual("Result", r); Assert.AreEqual(uiDispatcher.ThreadId, Thread.CurrentThread.ManagedThreadId); Assert.AreEqual(2, countdown.CurrentCount); countdown.Signal(); }, state); Assert.IsTrue(countdown.Wait(5000)); }
private async Task InitializeBackgroundTaskAsync() { switch (BackgroundExecutionManager.GetAccessStatus()) { case BackgroundAccessStatus.AllowedSubjectToSystemPolicy: case BackgroundAccessStatus.AlwaysAllowed: break; default: BackgroundExecutionManager.RemoveAccess(); await BackgroundExecutionManager.RequestAccessAsync(); break; } D("Background execution access checked"); BackgroundTaskManager.UnregisterTasks(); BackgroundTaskManager.RegisterTasks(); D("Background task reregistered"); }
private void setUpBackgroundWorker() { bgWorker_loadSub = new BackgroundTaskManager <DispatcherNotifiedObservableCollection <DirectoryTreeItemViewModel> >( () => { IsLoading = true; return(getDirectories()); }, (result) => { List <DirectoryTreeItemViewModel> delList = new List <DirectoryTreeItemViewModel>(SubDirectories.ToArray()); List <DirectoryTreeItemViewModel> addList = new List <DirectoryTreeItemViewModel>(); foreach (DirectoryTreeItemViewModel model in result) { if (delList.Contains(model)) { delList.Remove(model); } else { addList.Add(model); } } foreach (DirectoryTreeItemViewModel model in delList) { SubDirectories.Remove(model); } foreach (DirectoryTreeItemViewModel model in addList) { SubDirectories.Add(model); } HasSubDirectories = SubDirectories.Count > 0; IsLoading = false; }); }
public static void ApplicationStart() { try { SqlSettings.AutoQuotedIdentifiers = true; Serenity.Web.CommonInitialization.Run(); var registrar = Dependency.Resolve <IDependencyRegistrar>(); registrar.RegisterInstance <IAuthorizationService>(new Administration.AuthorizationService()); registrar.RegisterInstance <IAuthenticationService>(new Administration.AuthenticationService()); registrar.RegisterInstance <IPermissionService>(new LogicOperatorPermissionService(new Administration.PermissionService())); registrar.RegisterInstance <IUserRetrieveService>(new Administration.UserRetrieveService()); registrar.RegisterInstance <ISMSService>(new Administration.FakeSMSService()); if (!ConfigurationManager.AppSettings["LDAP"].IsTrimmedEmpty()) { registrar.RegisterInstance <IDirectoryService>(new LdapDirectoryService()); } if (!ConfigurationManager.AppSettings["ActiveDirectory"].IsTrimmedEmpty()) { registrar.RegisterInstance <IDirectoryService>(new ActiveDirectoryService()); } InitializeExceptionLog(); BackgroundTaskManager.Register(new MailingBackgroundTask()); BackgroundTaskManager.Initialize(); } catch (Exception ex) { ex.Log(); throw; } foreach (var databaseKey in databaseKeys) { EnsureDatabase(databaseKey); RunMigrations(databaseKey); } }
protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; Window.Current.Activate(); } AppListProvider.Init(); manager = BackgroundTaskManager.Instance; }
string ExecuteAPI(ApiObject apiObject, object data = null) { string result = string.Empty; string url = HttpHelper.UrlPathCombine(API, Username); if (string.IsNullOrWhiteSpace(apiObject.Path) == false) { url = HttpHelper.UrlPathCombine(url, apiObject.Path); } url += string.Format("?password={0}", Password); if (apiObject.AsyncNoResponse) { BackgroundTaskManager.Run(() => Execute(apiObject.Method, url, data, null, 100)); } else { result = Execute(apiObject.Method, url, data, null, 100); } return(result); }
public static async Task RegisterBackgroundTasks() { //BackgroundExecutionManager.RemoveAccess(); //foreach (var t in BackgroundTaskRegistration.AllTasks) //{ // if (t.Value.Name == "NotificationTask") // { // t.Value.Unregister(false); // } //} var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.DeniedByUser || access == BackgroundAccessStatus.DeniedBySystemPolicy) { return; } // TODO: remove the "new" when releasing to the store BackgroundTaskManager.Register("NewNotificationTask", "Unigram.Native.Tasks.NotificationTask", new PushNotificationTrigger()); BackgroundTaskManager.Register("InteractiveTask", "Unigram.Tasks.InteractiveTask", new ToastNotificationActionTrigger()); }
private void setupBackgroundWorker() { bgWorker_loadCommands = new BackgroundTaskManager <object, CommandViewModel[]>( (x) => { var vms = from m in EmbeddedModel.GetCommands() select m.ToViewModel(); return(vms.ToArray()); }, (vms) => { lock (_commands) { _commands.Clear(); var vmsList = new List <CommandViewModel>(vms); vmsList.Sort(); foreach (var vm in vmsList) { //vm.ToString(); _commands.Add(vm); } } }); }
private void setUpBackgroundWorker() { bgWorker_loadSub = new BackgroundTaskManager<DispatcherNotifiedObservableCollection<DirectoryTreeItemViewModel>>( () => { IsLoading = true; return getDirectories(); }, (result) => { List<DirectoryTreeItemViewModel> delList = new List<DirectoryTreeItemViewModel>(SubDirectories.ToArray()); List<DirectoryTreeItemViewModel> addList = new List<DirectoryTreeItemViewModel>(); foreach (DirectoryTreeItemViewModel model in result) if (delList.Contains(model)) delList.Remove(model); else addList.Add(model); foreach (DirectoryTreeItemViewModel model in delList) SubDirectories.Remove(model); foreach (DirectoryTreeItemViewModel model in addList) SubDirectories.Add(model); HasSubDirectories = SubDirectories.Count > 0; IsLoading = false; }); }
private void setUpBackgroundWorker() { Action<List<FileListViewItemViewModel>> updateSubEntries = (result) => { List<FileListViewItemViewModel> delList = new List<FileListViewItemViewModel>(SubEntriesInternal.ToArray()); List<FileListViewItemViewModel> addList = new List<FileListViewItemViewModel>(); foreach (FileListViewItemViewModel model in result) if (delList.Contains(model)) delList.Remove(model); else addList.Add(model); foreach (FileListViewItemViewModel model in delList) SubEntriesInternal.Remove(model); foreach (FileListViewItemViewModel model in addList) SubEntriesInternal.Add(model); DirectoryCount = (uint)(from model in SubEntriesInternal where model.EmbeddedModel is DirectoryModel select model).Count(); FileCount = (uint)(SubEntriesInternal.Count - DirectoryCount); HasSubEntries = SubEntriesInternal.Count > 0; }; bgWorker_LoadSubEntries = new BackgroundTaskManager<List<FileListViewItemViewModel>>( () => { IsLoading = true; return getEntries(); }, (result) => { updateSubEntries(result); IsLoading = false; }); bgWorker_FilterSubEntries = new BackgroundTaskManager<List<FileListViewItemViewModel>>( () => { IsLoading = true; return filterEntries(); }, (result) => { updateSubEntries(result); IsLoading = false; }); }
private void setUpBackgroundWorker() { bgWorker_findChild = new BackgroundTaskManager<DirectoryTreeItemViewModel>( () => { IsLoading = true; DirectoryTreeItemViewModel lookingUpModel = _selectedDirectoryModel; Func<bool> cancelNow = () => { bool cont = lookingUpModel != null && lookingUpModel.Equals(_selectedDirectoryModel); return !cont; }; DirectoryTreeItemViewModel newSelectedModel = null; { DirectoryInfoEx newSelectedDir = _selectedDirectory; if (newSelectedDir != null) { foreach (DirectoryTreeItemViewModel rootModel in _rootDirectoryModelList) { newSelectedModel = rootModel.LookupChild(newSelectedDir, cancelNow); if (newSelectedModel != null) return newSelectedModel; } } } return _rootDirectoryModelList.Count == 0 ? null : _rootDirectoryModelList[0]; }, (result) => { if (result != null) { if (result.Equals(_selectedDirectoryModel)) result.IsSelected = true; } IsLoading = false; }); }
/// <summary> /// Setup backgrounder worker Task/Completion action /// to fetch Orders for Customers /// </summary> private void SetUpBackgroundWorker() { bgWorker = new BackgroundTaskManager<DispatcherNotifiedObservableCollection<OrderModel>>( () => { return new DispatcherNotifiedObservableCollection<OrderModel>( DataAccess.DataService.FetchAllOrders( CurrentCustomer.CustomerId.DataValue).ConvertAll( new Converter<Order, OrderModel>( OrderModel.OrderToOrderModel))); }, (result) => { CurrentCustomer.Orders = result; if (customerOrdersView != null) customerOrdersView.CurrentChanged -= CustomerOrdersView_CurrentChanged; customerOrdersView = CollectionViewSource.GetDefaultView(CurrentCustomer.Orders); customerOrdersView.CurrentChanged += CustomerOrdersView_CurrentChanged; customerOrdersView.MoveCurrentToPosition(-1); HasOrders = CurrentCustomer.Orders.Count > 0; }); }