Exemple #1
0
        public static async Task <Exception> BusyTask(this IBusy busy, Action action, string busyMessage = null, bool alertOnException = true)
        {
            Debug.AssertNotNull(busy);
            Debug.AssertNotNull(action);
            if (busy.IsBusy)
            {
                //Debug.Fail("Can not perfotm another busy task while in busy state");
                return(null);
            }

            busy.StartBusy(busyMessage);
            try {
                action();
                return(null);
            }
            catch (Exception exc) {
                Debug.ExceptionCaught(exc);
                if (alertOnException)
                {
                    await Alerts.ExceptionAlert(exc);
                }
                return(exc);
            }
            finally {
                busy.EndBusy();
            }
        }
Exemple #2
0
        public static async Task <Exception> BusyTask(this IBusy busy, Func <Task> task, string busyMessage = null, bool alertOnException = true)
        {
            Debug.AssertNotNull(busy);
            Debug.AssertNotNull(task);
            if (busy.IsBusy)
            {
                //Debug.Fail("BusyTask called with other BusyTask in progress");
                return(null);
            }

            busy.StartBusy(busyMessage);
            try {
                await task();

                return(null);
            }
            catch (Exception exc) {
                Debug.ExceptionCaught(exc);
                if (alertOnException)
                {
                    await Alerts.ExceptionAlert(exc);
                }
                return(exc);
            }
            finally {
                busy.EndBusy();
            }
        }
 void ISafeMessagingCenter.SubscribeAny(
     object subscriber,
     string message,
     Func <object, Task> asyncCallback,
     IBusy viewModel,
     Action <Exception> onException,
     bool isBlocking)
 => InnerSubscribe(null, null, subscriber, message, asyncCallback, viewModel, onException, null, isBlocking);
 /// <summary>
 /// Subscribe to a specified message from any Sender, and register an asynchronous callback to execute when the message is recieved
 /// </summary>
 /// <param name="subscriber">The subscriber. Usually <c>this</c>.</param>
 /// <param name="message">Will only execute the callback when the specified message is recieved</param>
 /// <param name="asyncCallback">Callback to execute</param>
 /// <param name="onException">Callback to execute if Exception is caught</param>
 /// <param name="isBlocking">Will block execution of the callback if the callback is already busy executing.</param>
 /// <param name="viewModel">Will update <see cref="IBusy"/>'s <c>IsBusy</c></param>
 /// property.
 public static void SubscribeAny(
     object subscriber,
     string message,
     Func <object, Task> asyncCallback,
     IBusy viewModel = null,
     Action <Exception> onException = null,
     bool isBlocking = true)
 => Instance.SubscribeAny(subscriber, message, asyncCallback, viewModel, onException, isBlocking);
 void ISafeMessagingCenter.SubscribeAny <TArgs>(
     object subscriber,
     string message,
     Action <object, TArgs> callback,
     IBusy viewModel,
     Action <Exception> onException,
     bool isBlocking)
 => InnerSubscribe(null, typeof(TArgs), subscriber, message, callback, viewModel, onException, null, isBlocking);
 /// <summary>
 /// Subscribe to a specified message from any Sender, and register a callback to execute when the message is recieved
 /// </summary>
 /// <typeparam name="TArgs">Arguments Type. Callback expects arguements of type <typeparamref name="TArgs"/></typeparam>
 /// <param name="subscriber">The subscriber. Usually <c>this</c>.</param>
 /// <param name="message">Will only execute the callback when the specified message is recieved</param>
 /// <param name="callback">Callback to execute</param>
 /// <param name="onException">Callback to execute if Exception is caught</param>
 /// <param name="isBlocking">Will block execution of the callback if the callback is already busy executing.</param>
 /// <param name="viewModel">Will update <see cref="IBusy"/>'s <c>IsBusy</c></param>
 /// property.
 public static void SubscribeAny <TArgs>(
     object subscriber,
     string message,
     Action <object, TArgs> callback,
     IBusy viewModel = null,
     Action <Exception> onException = null,
     bool isBlocking = true)
 => Instance.SubscribeAny(subscriber, message, callback, viewModel, onException, isBlocking);
Exemple #7
0
 public static async Task <T> BusyTask <T>(this IBusy busy, Func <Task <T> > task, string busyMessage = null, bool alertOnException = true)
 {
     Debug.AssertNotNull(busy);
     Debug.AssertNotNull(task);
     if (busy.IsBusy)
     {
         //Debug.Fail("BusyTask called with other BusyTask in progress");
         return(default);
 public AsyncCommand(IBusy busy, Action command)
 {
     this.busy    = busy;
     this.command = () =>
     {
         command();
         return(Task.CompletedTask);
     };
 }
 void ISafeMessagingCenter.Subscribe <TSender, TArgs>(
     object subscriber,
     string message,
     Action <TSender, TArgs> callback,
     IBusy viewModel,
     Action <Exception> onException,
     TSender source,
     bool isBlocking) where TSender : class
 => InnerSubscribe(typeof(TSender), typeof(TArgs), subscriber, message, callback, viewModel, onException, source, isBlocking);
 /// <summary>
 /// Subscribe to a specified message, and register an asynchronous callback to execute when the message is recieved
 /// </summary>
 /// <typeparam name="TSender">Sender Type. Callback will only execute if recieved
 /// from sender of type <typeparamref name="TSender"/></typeparam>
 /// <param name="subscriber">The subscriber. Usually <c>this</c>.</param>
 /// <param name="message">Will only execute the callback when the specified message is recieved</param>
 /// <param name="asyncCallback">Callback to execute</param>
 /// <param name="onException">Callback to execute if Exception is caught</param>
 /// <param name="source">Instance of the source that will send the message.
 /// If specified, callback will only execute if the sender is from the
 /// specified source. If not, callback will execute if the sender's type is equal to <typeparamref name="TSender"/></param>
 /// <param name="isBlocking">Will block execution of the callback if the callback is already busy executing.</param>
 /// <param name="viewModel">Will update <see cref="IBusy"/>'s <c>IsBusy</c></param>
 /// property.
 public static void Subscribe <TSender>(
     object subscriber,
     string message,
     Func <TSender, Task> asyncCallback,
     IBusy viewModel = null,
     Action <Exception> onException = null,
     TSender source  = null,
     bool isBlocking = true) where TSender : class
 => Instance.Subscribe(subscriber, message, asyncCallback, viewModel, onException, source, isBlocking);
 void ISafeMessagingCenter.Subscribe <TSender>(
     object subscriber,
     string message,
     Func <TSender, Task> asyncCallback,
     IBusy viewModel,
     Action <Exception> onException,
     TSender source,
     bool isBlocking) where TSender : class
 => InnerSubscribe(typeof(TSender), null, subscriber, message, asyncCallback, viewModel, onException, source, isBlocking);
        async static public Task ExecuteActionAsync(IBusy model, Action action)
        {
            model.IsBusy = true;
            await System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                action();
            });

            model.IsBusy = false;
        }
 public MenuViewModel(
     IProjectData projectData,
     IBusy busy, IReportFactory reportFactory,
     IProcess processApi, IDialogs dialogs)
 {
     this.busy          = busy;
     this.projectData   = projectData;
     this.processApi    = processApi;
     this.dialogs       = dialogs;
     this.reportFactory = reportFactory;
 }
Exemple #14
0
        public MainViewModel(IBusy status)
        {
            Messenger.Default.Register <PropertyChangedMessage <IBusy> >(this, _message => Set(_message.NewValue));
            Status          = status;
            Status.Busy     = true;
            ShutdownCommand = new RelayCommand(Shutdown);

            ChangeTab   = new RelayCommand <object>(OnChangeScreenCommand);
            MenuClicked = new RelayCommand <string>(OnMenuClicked);
            Status.Busy = false;
        }
 public LibraryViewModel(Func <ILibraryRepository> libraryRepo, IBusy status)
 {
     _libraryRepo = libraryRepo;
     Status       = status;
     Status.Busy  = true;
     Task.Factory.StartNew(() =>
     {
         Libraries   = libraryRepo().GetAll().ToObservable();
         Status.Busy = false;
     });
 }
        async static public Task <TResult> ExecuteFuncAsync(Func <TResult> func, IBusy model)
        {
            model.IsBusy = true;
            var tsk = await System.Threading.Tasks.Task <TResult> .Factory.StartNew(() =>
            {
                return(func());
            });

            model.IsBusy = false;
            return(tsk);
        }
 public StudentViewModel(Func <IStudentRepository> studentRepo, IBusy status)
 {
     _studentRepo = studentRepo;
     Status       = status;
     Status.Busy  = true;
     Task.Factory.StartNew(() =>
     {
         Students    = studentRepo().GetAll().ToObservable();
         Status.Busy = false;
     });
 }
Exemple #18
0
        public MainViewModel(IBusy status)
        {
            Messenger.Default.Register<PropertyChangedMessage<IBusy>>(this, _message => Set(_message.NewValue));
            Status = status;
            Status.Busy = true;
            ShutdownCommand = new RelayCommand(Shutdown);

            ChangeTab = new RelayCommand<object>(OnChangeScreenCommand);
            MenuClicked = new RelayCommand<string>(OnMenuClicked);
            Status.Busy = false;
        }
 public StudentViewModel(Func<IStudentRepository> studentRepo, IBusy status)
 {
     _studentRepo = studentRepo;
     Status = status;
     Status.Busy = true;
     Task.Factory.StartNew(() =>
         {
             Students = studentRepo().GetAll().ToObservable();
             Status.Busy = false;
         });
 }
 public LibraryViewModel(Func<ILibraryRepository> libraryRepo, IBusy status)
 {
     _libraryRepo = libraryRepo;
     Status = status;
     Status.Busy = true;
     Task.Factory.StartNew(() =>
         {
             Libraries = libraryRepo().GetAll().ToObservable();
             Status.Busy = false;
         });
 }
Exemple #21
0
        public ShellViewModel(
            IProjectData projectData,
            IBusy busy,
            IMenuViewModel menu,
            IFullJournalViewModel fullJournal,
            IAccountJournalViewModel accountJournal,
            IAccountsViewModel accounts,
            IApplicationUpdate applicationUpdate)
        {
            this.ProjectData       = projectData;
            this.Busy              = busy;
            this.Menu              = menu;
            this.FullJournal       = fullJournal;
            this.AccountJournal    = accountJournal;
            this.Accounts          = accounts;
            this.applicationUpdate = applicationUpdate;

            this.version = this.GetType().GetInformationalVersion();

            // TODO SVM is too much responsible
            this.ProjectData.DataLoaded += (sender, args) =>
            {
                this.Accounts.OnDataLoaded();
                this.Menu.OnDataLoaded();
            };
            this.ProjectData.YearChanged += (_, __) =>
            {
                this.UpdateDisplayName();
                this.FullJournal.Rebuild();
                this.Accounts.SelectFirstAccount();
            };
            this.ProjectData.JournalChanged += (_, args) =>
            {
                this.FullJournal.Rebuild();
                this.FullJournal.Select(args.ChangedBookingId);

                if (this.Accounts.SelectedAccount == null ||
                    !args.AffectedAccounts.Contains(this.Accounts.SelectedAccount.Identifier))
                {
                    return;
                }

                this.AccountJournal.Rebuild(this.Accounts.SelectedAccount.Identifier);
                this.AccountJournal.Select(args.ChangedBookingId);
            };
            this.Accounts.PropertyChanged += (_, args) =>
            {
                if (args.PropertyName == nameof(this.Accounts.SelectedAccount))
                {
                    this.AccountJournal.Rebuild(this.Accounts.SelectedAccount?.Identifier ?? 0);
                }
            };
        }
Exemple #22
0
 public UserViewModel(Func <IUserRepository> userRepo, IBusy status)
 {
     _userRepo   = userRepo;
     Status      = status;
     Status.Busy = true;
     Messenger.Default.Register <string>(this, "menuaction", d => MessageBox.Show("Ariti"));
     Task.Factory.StartNew(() =>
     {
         Users       = userRepo().GetAll().ToObservable();
         Status.Busy = false;
     });
 }
        public AuthorViewModel(Func<IAuthorRepository> authorRepo, IBusy status)
        {
            _authorRepo = authorRepo;
            Status = status;
            Status.Busy = true;
            Messenger.Default.Register<string>(this, "menuaction", d => MessageBox.Show("Ariti"));

            Task.Factory.StartNew(() =>
                {
                    Authors = authorRepo().GetAll().ToObservable();
                    Status.Busy = false;
                });
        }
Exemple #24
0
        public static IDisposable BusyIn(this IBusy busy, string message = null)
        {
            busy.AssertNotNull(nameof(busy));

            if (busy.BusyState.IsBusy)
            {
                throw Exceptions.ReentrancyCheckFailed();
            }

            busy.BusyState.Message = message;
            busy.BusyState.IsBusy  = true;

            return(new BusyScope(busy.BusyState));
        }
        static public vCommandAsync <TResult> Create(IBusy model, Func <TResult> command, Predicate <object> canExecute)
        {
            var asyncCommand = new vCommandAsync <TResult>(async(cmd) =>
            {
                model.IsBusy = true;
                var tsk      = await System.Threading.Tasks.Task <TResult> .Factory.StartNew(() =>
                {
                    return(command());
                });
                model.IsBusy = false;
                return(tsk);
            }, canExecute);

            return(asyncCommand);
        }
        static public vCommandAsync Create(IBusy model, Action command, Predicate <object> canExecute)
        {
            var asyncCommand = new vCommandAsync((cmd) =>
            {
                model.IsBusy = true;
                var tsk      = System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    command();
                    model.IsBusy = false;
                });
                return(tsk);
            }, canExecute);

            return(asyncCommand);
        }
 public AsynchronousCommand(IBusy target, Action activity, Action onComplete, Func<bool> canExecute)
 {
     _canExecute = canExecute;
     _busyObject = target;
     _worker = new BackgroundWorker();
     _worker.DoWork += (x, y) => activity.Invoke();
     _worker.RunWorkerCompleted += (x, y) =>
     {
         if (onComplete != null)
         {
             onComplete();
         }
         _busyObject.IsBusy = false;
     };
 }
Exemple #28
0
 public BookViewModel(Func<IBookRepository> _bookRepo, IBusy status)
 {
     bookRepo = _bookRepo;
     Status = status;
     Status.Busy = true;
     Messenger.Default.Register<string>(this, "menuaction", d =>
         {
             if (d == "New book")
                 selected = new Book();
             Messenger.Default.Send(d, "DialogBook");
         });
     Task.Factory.StartNew(() =>
         {
             Books = bookRepo().GetAll().ToObservable();
             Status.Busy = false;
         });
 }
Exemple #29
0
 public BookViewModel(Func <IBookRepository> _bookRepo, IBusy status)
 {
     bookRepo    = _bookRepo;
     Status      = status;
     Status.Busy = true;
     Messenger.Default.Register <string>(this, "menuaction", d =>
     {
         if (d == "New book")
         {
             selected = new Book();
         }
         Messenger.Default.Send(d, "DialogBook");
     });
     Task.Factory.StartNew(() =>
     {
         Books       = bookRepo().GetAll().ToObservable();
         Status.Busy = false;
     });
 }
        void InnerSubscribe(
            Type senderType,
            Type argsType,
            object subscriber,
            string message,
            Delegate callback,
            IBusy viewModel = null,
            Action <Exception> onException = null,
            object source   = null,
            bool isBlocking = true)
        {
            ThrowIfNull(subscriber, message, callback);

            var key   = new Sender(message, senderType, argsType);
            var value = new Subscription(subscriber, callback.Target, callback.GetMethodInfo())
            {
                OnException = onException, Source = source, ViewModel = viewModel, IsBlocking = isBlocking
            };

            AddSubscription(key, value);
        }
Exemple #31
0
        public SafeCommand(
            Func <T, Task> executeFunction,
            TaskScheduler scheduler,
            IBusy viewModel = null,
            Action <Exception> onException = null,
            Func <T, bool> canExecute      = null,
            //bool mustRunOnCurrentSyncContext is moot
            bool isBlocking = true
            )
            : base(
                o =>
        {
            if (!IsValidParameter(o))
            {
                throw new InvalidCommandParameterException(typeof(T));
            }

            return(executeFunction((T)o));
        },
                scheduler,
                viewModel,
                onException,
                o =>
        {
            if (canExecute is null)
            {
                return(true);
            }

            return(IsValidParameter(o) && canExecute((T)o));
        },
                isBlocking)
        {
            if (executeFunction is null)
            {
                throw new ArgumentNullException(nameof(executeFunction)
                                                , $"{nameof(executeFunction)} cannot be null");
            }
        }
        public BorrowerViewModel(
            Func<IBorrowerRepository> _borrowerRepository,
            Func<IStudentRepository> _studentRepository,
            Func<IBookCopysRepository> _bookCopyRepository,
            ICurrent _current, IBusy status)
        {
            Status = status;
            Status.Busy = true;
            borrowerRepository = _borrowerRepository;
            studentRepository = _studentRepository;
            bookCopyRepository = _bookCopyRepository;
            current = _current;

            Task.Factory.StartNew(() =>
                {
                    Borrowers =
                        borrowerRepository().GetAll(
                            c => !c.Return.HasValue && c.BookCopy.LibraryID == current.CurrentUser.LibraryID).
                            ToObservable();
                    Status.Busy = false;
                });
        }
        public BorrowerViewModel(
            Func <IBorrowerRepository> _borrowerRepository,
            Func <IStudentRepository> _studentRepository,
            Func <IBookCopysRepository> _bookCopyRepository,
            ICurrent _current, IBusy status)
        {
            Status             = status;
            Status.Busy        = true;
            borrowerRepository = _borrowerRepository;
            studentRepository  = _studentRepository;
            bookCopyRepository = _bookCopyRepository;
            current            = _current;


            Task.Factory.StartNew(() =>
            {
                Borrowers =
                    borrowerRepository().GetAll(
                        c => !c.Return.HasValue && c.BookCopy.LibraryID == current.CurrentUser.LibraryID).
                    ToObservable();
                Status.Busy = false;
            });
        }
Exemple #34
0
        /// <summary>
        /// Initializes an instance of the <see cref="ICommand"/> class
        /// </summary>
        /// <remarks>Warning! If <paramref name="executeAction"/> is set to a lambda expression <c>() =&gt; { }</c>,
        /// the compiler will choose the wrong <c>Func&lt;T,Task&gt;</c> overload instead.
        /// To be explicit, either abstract the lambda into a separate method
        /// (where it will be obvious to the compiler, or specify the parameter name before the lambda
        /// as so: <c>executeAction: () =&gt; { }</c>.
        /// The compiler's logic is that a delegate with a return type is a better match
        /// than a delegate without a return type.</remarks>
        /// <param name="executeAction">The function executed when
        /// <see cref="ICommand.Execute(object)"/> is called.</param>
        /// <param name="viewModel"> Option to pass the calling ViewModel
        /// via <c>this</c>. Will set <see cref="IBusy.IsBusy"/>
        /// to <c>true</c> while <paramref name="executeAction"/> is
        /// executing</param>
        /// <param name="canExecute">The function that verifies whether or
        /// not <see cref="SafeCommand"/>
        /// should execute</param>
        /// <param name="onException">If an exception is thrown,
        /// <paramref name="onException"/> will execute.</param>
        /// <param name="mustRunOnCurrentSyncContext"><c>false</c> by default
        /// , causing <paramref name="executeAction"/> to run on a background
        /// thread. If set to <c>true</c>, will run on the current thread.
        /// In Xamarin.Forms this will be the Main (UI) thread.</param>
        /// <param name="isBlocking">Execution will be blocked if the callback is already executing</param>
        public SafeCommand(
            Action <T> executeAction,
            IBusy viewModel = null,
            Action <Exception> onException   = null,
            Func <T, bool> canExecute        = null,
            bool mustRunOnCurrentSyncContext = false,
            bool isBlocking = true)
            : base(
                internalExecuteAction: o =>
        {
            if (!IsValidParameter(o))
            {
                throw new InvalidCommandParameterException(typeof(T));
            }

            executeAction((T)o);
        },
                viewModel,
                onException,
                o =>
        {
            if (canExecute is null)
            {
                return(true);
            }

            return(IsValidParameter(o) && canExecute((T)o));
        },
                mustRunOnCurrentSyncContext,
                isBlocking)
        {
            if (executeAction is null)
            {
                throw new ArgumentNullException(nameof(executeAction)
                                                , $"{nameof(executeAction)} cannot be null");
            }
        }
 public AsyncCommand(IBusy busy, Func <Task> command)
 {
     this.busy    = busy;
     this.command = command;
 }
Exemple #36
0
 void Set(IBusy busy)
 {
     Status = busy;
 }
 public AsynchronousCommand(IBusy target, Action activity)
     : this(target, null, activity, null)
 {
 }
 public AsynchronousCommand(IBusy target, Action activity, Action onComplete)
     : this(target, activity, onComplete, null)
 {
 }
 public AsynchronousCommand(IBusy target, Action activity, Func<bool> canExecute)
     : this(target, activity, null, canExecute)
 {
 }
Exemple #40
0
 void Set(IBusy busy)
 {
     Status = busy;
 }
Exemple #41
0
 public BusyState(IBusy target)
 {
     this.target   = target;
     target.IsBusy = true;
 }