public LoginRouteViewModel(IScreen hostScreen)
 {
     HostScreen = hostScreen;
     var authentication = new Authentication();
     var canLogin = this.WhenAny(x => x.LoginName,
         x => x.Password,
         (l, p) => !String.IsNullOrWhiteSpace(l.Value) && !String.IsNullOrWhiteSpace(p.Value));
     LoginCommand = new ReactiveCommand(canLogin);
     var loggedIn = LoginCommand.RegisterAsync(_ => Observable.Start(() =>
     {
         var authenticationResult = authentication.AuthenticateAsync(LoginName,
             Password).
                                                   Result;
         return authenticationResult == AuthenticationResult.Authenticated
             ? "Přihlášen"
             : "Nepřihlášen";
     }));
     loggedIn.Subscribe(s =>
     {
         if (s == "Přihlášen")
             HostScreen.Router.Navigate.Execute(new PersonListViewModel(HostScreen));
     });
     message = new ObservableAsPropertyHelper<string>(loggedIn,
         s => raisePropertyChanged("Message"));
 }
Exemple #2
0
        public BudgetsViewModel(IBudgetService budgetService, INavigationService navigationService, IBudgetSynchronizationService budgetSynchronizationService)
        {
            this._budgetService = budgetService;
            this._navigationService = navigationService;
            this._budgetSynchronizationService = budgetSynchronizationService;

            var canOpenBudget = this.WhenAny(f => f.SelectedBudget, budget => budget.Value != null);
            this.OpenBudget = ReactiveCommand.CreateAsyncTask(canOpenBudget, async _ =>
            {
                await this._budgetSynchronizationService.SynchronizeBudgetInBackground(this.SelectedBudget);

                this._navigationService.NavigateToViewModel<BudgetsViewModel>();
            });

            this.ReloadBudgets = ReactiveCommand.CreateAsyncTask(async _ =>
            {
                IReadOnlyCollection<Budget> budgets = await this._budgetService.GetBudgetsAsync();

                var result = new ReactiveObservableCollection<Budget>();
                result.AddRange(budgets);

                return result;
            });
            this.ReloadBudgets.ToProperty(this, f => f.Budgets, out this._budgetsHelper);
        }
Exemple #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CoreEntityVM"/> class.
        /// </summary>
        protected CoreEntityVM()
        {
            #region Register Commands

            //Can save or discard when context has changes and is not submitting
            var canSaveDiscardCommand =
                DataManager.DomainContextHasChangesObservable.CombineLatest(DataManager.DomainContextIsSubmittingObservable,
                (hasChanges, isSubmitting) => hasChanges && !isSubmitting);

            SaveCommand = new ReactiveCommand(canSaveDiscardCommand);
            SaveCommand.ObserveOnDispatcher().Subscribe(param =>
            {
                if (!BeforeSaveCommand()) return;

                DataManager.EnqueueSubmitOperation(OnSave);
            });

            DiscardCommand = new ReactiveCommand(canSaveDiscardCommand);
            DiscardCommand.ObserveOnDispatcher().Subscribe(param =>
            {
                if (!BeforeDiscardCommand()) return;
                DomainContext.RejectChanges();
                AfterDiscard();
                DiscardSubject.OnNext(true);
            });

            #endregion
        }
Exemple #4
0
        void SetConfigurationMenu(MainWindowViewModel viewModel)
        {
            ConfigurationContextMenu.Items.Clear();
            foreach (var item in viewModel.Configrations)
            {
                ConfigurationContextMenu.Items.Add(new MenuItem { FontSize = 12, Header = item.Item1, Command = item.Item2 });
            }
            ConfigurationContextMenu.Items.Add(new Separator());
            var saveCommand = new ReactiveCommand();
            saveCommand.Subscribe(_ =>
            {
                var dialog = new Microsoft.Win32.SaveFileDialog();
                dialog.FilterIndex = 1;
                dialog.Filter = "JSON Configuration|*.json";
                dialog.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "configuration");

                if (dialog.ShowDialog() == true)
                {
                    var fName = dialog.FileName;
                    if (!fName.EndsWith(".json")) fName = fName + ".json";
                    viewModel.SaveCurrentConfiguration(fName);
                    viewModel.LoadConfigurations();
                    SetConfigurationMenu(viewModel); // reset
                }
            });
            ConfigurationContextMenu.Items.Add(new MenuItem { FontSize = 12, Header = "Save...", Command = saveCommand });
        }
        public RepositoryOutlinerVm(RepositoryVm repos)
            : base(string.Empty, RepositoryOutlinerItemType.Root, null, repos, null)
        {
            Debug.Assert(repos != null);
            _repos = repos;

            SelectedItem = new ReactiveProperty<RepositoryOutlinerItemVm>()
                .AddTo(MultipleDisposable);

            // 各項目のルートノードを配置する
            _localBranch =
                new RepositoryOutlinerItemVm("Local", RepositoryOutlinerItemType.LocalBranchRoot, null, repos, this)
                    .AddTo(MultipleDisposable);

            _remoteBranch =
                new RepositoryOutlinerItemVm("Remote", RepositoryOutlinerItemType.RemoteBranchRoot, null, repos, this)
                    .AddTo(MultipleDisposable);

            Children.AddOnScheduler(_localBranch);
            Children.AddOnScheduler(_remoteBranch);

            UpdateBranchNodes(_localBranch, repos.LocalBranches, false);
            UpdateBranchNodes(_remoteBranch, repos.RemoteBranches, true);

            repos.LocalBranches.CollectionChangedAsObservable()
                .Subscribe(_ => UpdateBranchNodes(_localBranch, repos.LocalBranches, false))
                .AddTo(MultipleDisposable);

            repos.RemoteBranches.CollectionChangedAsObservable()
                .Subscribe(_ => UpdateBranchNodes(_remoteBranch, repos.RemoteBranches, true))
                .AddTo(MultipleDisposable);

            SwitchBranchCommand = new ReactiveCommand().AddTo(MultipleDisposable);
            SwitchBranchCommand.Subscribe(_ => SwitchBranch()).AddTo(MultipleDisposable);
        }
        public IndexViewModel(IRepository repo)
        {
            this.repo = repo;
            this.refreshCommand = ReactiveCommand.Create();

            this.repositoryStatus = this.refreshCommand.Select(u =>
            {
                return repo.RetrieveStatus(new StatusOptions() { Show = StatusShowOption.IndexAndWorkDir });
            }).ToProperty(this, vm => vm.RepositoryStatus);

            this.statusEntries = this
                .WhenAny(vm => vm.RepositoryStatus, change =>
                {
                    var status = change.GetValue();

                    return status.CreateDerivedCollection(s => s, null, null, null, this.refreshCommand);
                }).ToProperty(this, vm => vm.StatusEntries);

            var resetSignal = this.WhenAny(vm => vm.StatusEntries, change =>
             {
                 return 0;
             });

            var allEntries = this.WhenAny(vm => vm.StatusEntries, change => change.GetValue());

            this.unstagedEntries = allEntries.Select(s =>
            {
                return s.CreateDerivedCollection(i => i, i => Unstaged(i.State), null, resetSignal);
            }).ToProperty(this, vm => vm.UnstagedEntries);

            this.stagedEntries = allEntries.Select(s =>
            {
                return s.CreateDerivedCollection(i => i, i => Staged(i.State), null, resetSignal);
            }).ToProperty(this, vm => vm.StagedEntries);
        }
        public MainWindowViewModel(ISentenceFactory sentenceFactory)
        {
            _sentenceFactory = sentenceFactory;

              CreateSentenceCommand = new ReactiveCommand(this.WhenAny(x => x.NewSentence, x => !string.IsNullOrEmpty(x.Value)));
              CreateSentenceCommand.Subscribe(_ => CreateSentence());
        }
        public MainWindowViewModel()
        {
            var whenAnyColorChanges = this.WhenAny(x => x.Red, x => x.Green, x => x.Blue,
                    (r, g, b) => Tuple.Create(r.Value, g.Value, b.Value))
                .Select(intsToColor);

            _FinalColor = whenAnyColorChanges
                .Where(x => x != null)
                .Select(x => x.Value)
                .ToProperty(this, x => x.FinalColor);

            Ok = ReactiveCommand.Create(whenAnyColorChanges.Select(x => x != null));

            _Images = this.WhenAny(x => x.FinalColor, x => x.Value)
                .Throttle(TimeSpan.FromSeconds(0.7), RxApp.MainThreadScheduler)
                .Do(_ => IsBusy = true)
                .Select(x => imagesForColor(x))
                .Switch()
                .SelectMany(imageListToImages)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Do(_ => IsBusy = false)
                .ToProperty(this, x => x.Images);

            _Images.ThrownExceptions.Subscribe(ex => this.Log().WarnException("Can't load images", ex));
        }
        public ViewModel2()
        {
            SearchResults = new ReactiveList<FlickrPhoto>();
            var canSearch = this.WhenAny(x => x.SearchTerm, x => !String.IsNullOrWhiteSpace(x.Value));

            Search = ReactiveCommand.CreateAsyncTask(canSearch, async _ =>  {  return await GetSearchResultFromBing(this.SearchTerm); });
            LoadMoreItems = ReactiveCommand.CreateAsyncTask(canSearch, async x => { return await LoadMore((int)x);  });

            Search.Subscribe(results =>
            {
                SearchResults.Clear();
                foreach (var item in results)
                {
                    SearchResults.Add(item);
                }
            });

            LoadMoreItems.Subscribe(results =>
            {
                foreach (var item in results)
                {
                    SearchResults.Add(item);
                }
            });

            Search.ThrownExceptions.Subscribe(ex => { UserError.Throw("Potential network connectivity Error", ex); });
            LoadMoreItems.ThrownExceptions.Subscribe(ex => { UserError.Throw("Problem when downloading additional items", ex); });

            this.WhenAnyValue(x => x.SearchTerm)
                .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
                .InvokeCommand(this, x => x.Search);

            //SearchTerm = "british cat";
        }
        public void ReactiveCommandAllFlow()
        {
            var testScheduler = new TestScheduler();
            var @null = (object)null;
            var recorder1 = testScheduler.CreateObserver<object>();
            var recorder2 = testScheduler.CreateObserver<object>();

            var cmd = new ReactiveCommand();
            cmd.Subscribe(recorder1);
            cmd.Subscribe(recorder2);

            cmd.CanExecute().Is(true);
            cmd.Execute(); testScheduler.AdvanceBy(10);
            cmd.Execute(); testScheduler.AdvanceBy(10);
            cmd.Execute(); testScheduler.AdvanceBy(10);

            cmd.Dispose();
            cmd.CanExecute().Is(false);

            cmd.Dispose(); // dispose again

            recorder1.Messages.Is(
                OnNext(0, @null),
                OnNext(10, @null),
                OnNext(20, @null),
                OnCompleted<object>(30));

            recorder2.Messages.Is(
                OnNext(0, @null),
                OnNext(10, @null),
                OnNext(20, @null),
                OnCompleted<object>(30));
        }
        public LogInViewModel(IScreen host, IGitHubClient ghClient)
        {
            this.HostScreen = host;
            this.GHClient = ghClient;

            // Only allow a submit when the user name is valid
            var validStuffTyped = this.WhenAny(x => x.UserName, x => x.Password,
                (user, pass) => !string.IsNullOrWhiteSpace(user.Value) && !string.IsNullOrWhiteSpace(pass.Value));

            Submit = new ReactiveCommand(validStuffTyped);

            //todo: better make a cancel or else you'll get very mad!
            //Submit.Subscribe(_ =>
            //{
            //    GHClient.Authorization.Create();
            //    //try
            //    //{
            //    //    //if (user != null)
            //    //    //{
            //    //    // Insert the user into the cache
            //    //    BlobCache.UserAccount.InsertObject<User>("MyUser", user);
            //    //    //}
            //    //}
            //    //catch (AuthorizationException authEx)
            //    //{
            //    //    Debug.Print("CRAP!");
            //    //    Debug.Print(authEx.Message);
            //    //    Debug.Print(authEx.StackTrace);
            //    //}
            //});

            MessageBus.Current.RegisterMessageSource(Submit);
        }
        public InsertGistViewModel()
        {
            //var client = new GitHubClient() { Username = "******", Password = "******" };

            var privateImage = new BitmapImage(new Uri(@"pack://*****:*****@"pack://application:,,,/data/public.png"));

            _PublicPrivateIcon = this.WhenAny(x => x.IsPrivateGist, x => x.Value)
                .Select(x => x ? privateImage : publicImage)
                .ToProperty(this, x => x.PublicPrivateIcon);

            CreateGist = new ReactiveAsyncCommand();

            CreateGist.RegisterAsyncObservable(_ => client.CreateGist(SelectionText, !IsPrivateGist))
                .Select(x => x.html_url)
                .BindTo(this, x => x.LastGistUrl);

            CopyToClipboard = new ReactiveCommand(
                this.WhenAny(x => x.LastGistUrl, x => !String.IsNullOrWhiteSpace(x.Value)));

            CopyToClipboard.Subscribe(_ => Clipboard.SetText(LastGistUrl));

            this.WhenAny(x => x.SelectionText, x => x.Value)
                .Where(_ => LastGistUrl != null)
                .Subscribe(_ => LastGistUrl = null);
        }
 public PersonListViewModel(IScreen hostScreen, IPersonRepository personRepository = null)
 {
     HostScreen = hostScreen;
     personRepository = personRepository ?? new PersonRepository();
     Persons = new ReactiveList<PersonItemViewModel>();
     NewPersonCommand = new ReactiveCommand(null);
     NewPersonCommand.RegisterAsyncAction(_ => { }).Subscribe(_ => HostScreen.Router.Navigate.Execute(new PersonAddViewModel(HostScreen)));
     RefreshCommand = new ReactiveCommand(null);
     var refresh = RefreshCommand.RegisterAsync<List<Person>>(_ => Observable.Start(() => personRepository.RetrievePersonsAsync().
                                                                                                           Result));
     refresh.Subscribe(list =>
     {
         using (Persons.SuppressChangeNotifications())
         {
             Persons.Clear();
             Persons.AddRange(personRepository.RetrievePersonsAsync().
                                               Result.Select(d => new PersonItemViewModel(d.FirstName,
                                                                      d.LastName,
                                                                      d.Age)));
         }
     });
     MessageBus.Current.Listen<Person>().
                Subscribe(p =>
                {
                    personRepository.AddPerson(p);
                    RefreshCommand.Execute(null);
                });
 }
        public SerializationViewModel()
        {
            // Observable sequence to ObservableCollection
            Items = Observable.Interval(TimeSpan.FromSeconds(1))
                .Take(30)
                .ToReactiveCollection();
            IsChecked = new ReactiveProperty<bool>();
            SelectedIndex = new ReactiveProperty<int>();
            Text = new ReactiveProperty<string>();
            SliderPosition = new ReactiveProperty<int>();

            var serializedString = new ReactiveProperty<string>(mode: ReactivePropertyMode.RaiseLatestValueOnSubscribe);
            Serialize = serializedString.Select(x => x == null).ToReactiveCommand();
            Deserialize = serializedString.Select(x => x != null).ToReactiveCommand();

            // Click Serialize Button
            Serialize.Subscribe(_ =>
            {
                // Serialize ViewModel's all ReactiveProperty Values.
                // return value is string that Serialize by DataContractSerializer.
                serializedString.Value = SerializeHelper.PackReactivePropertyValue(this); // this = ViewModel
            });

            // Click Deserialize Button
            Deserialize.Subscribe(_ =>
            {
                // Deserialize to target ViewModel.
                // Deseirlization order is same as DataContract.
                // Can control DataMemberAttribute's Order Property.
                // more info see http://msdn.microsoft.com/en-us/library/ms729813.aspx
               SerializeHelper.UnpackReactivePropertyValue(this, serializedString.Value);

                serializedString.Value = null; // push to command canExecute
            });
        }
 public OpenFileTabContentViewModel(IDialogService dialogService)
 {
     this.dialogService = dialogService;
     
     openFileCommand = ReactiveCommand.Create();
     openFileCommand.Subscribe(_ => OpenFile());
 }
        public MainViewModel()
        {
            _informationEngine = new InformationEngine();
            _sessionViewModels =
                _informationEngine.Sessions.CreateDerivedCollection(x => new SessionViewModel(x) as ISessionViewModel);
            ((IEditableCollectionView) (CollectionViewSource.GetDefaultView(_sessionViewModels)))
                .NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtEnd;

            _showInitializationErrorMessage = () => MessageBox.Show(
                "Bei der Initialisierung des Receivers ist ein Fehler aufgetreten.\n" +
                "Bitte schließen Sie die Session und starten den Receiver neu.",
                "Fehler");

            _showCloseSessionErrorMessage = () => MessageBox.Show(
                "Beim Schließen der Session trat ein Fehler auf.",
                "Fehler");

            StartNewSessionCommand = new ReactiveCommand();
            StartNewSessionCommand.Subscribe(_ => StartNewSession());

            InitializeReceiverCommand = new ReactiveAsyncCommand();
            InitializeReceiverCommand.RegisterAsyncAction(x => InitializeReceiver((Tuple<Guid, IReceiver>) x));
            InitializeReceiverCommand.ThrownExceptions.Subscribe(
                ex => _showInitializationErrorMessage());

            CloseSessionCommand = new ReactiveCommand();
            CloseSessionCommand.Subscribe(x => CloseSession((ISessionViewModel) x));
            CloseSessionCommand.ThrownExceptions.Subscribe(ex => _showCloseSessionErrorMessage());
        }
        public OpenCacheViewModel(IScreen hostScreen, IAppState appState)
        {
            HostScreen = hostScreen;

            var isCachePathValid = this.WhenAny(
                    x => x.CachePath, x => x.OpenAsEncryptedCache, x => x.OpenAsSqlite3Cache,
                    (cp, _, sql) => new { Path = cp.Value, Sqlite3 = sql.Value })
                .Throttle(TimeSpan.FromMilliseconds(250), RxApp.MainThreadScheduler)
                .Select(x => x.Sqlite3 ? File.Exists(x.Path) : Directory.Exists(x.Path));

            OpenCache = new ReactiveCommand(isCachePathValid);

            OpenCache.SelectMany(_ => openAkavacheCache(CachePath, OpenAsEncryptedCache, OpenAsSqlite3Cache))
                .LoggedCatch(this, Observable.Return<IBlobCache>(null))
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(x => {
                    if (x == null) {
                        UserError.Throw("Couldn't open this cache");
                        return;
                    }

                    appState.CurrentCache = x;
                    hostScreen.Router.Navigate.Execute(new CacheViewModel(hostScreen, appState));
                });
        }
        public MainVM()
        {
            var bobbyJoe = new Person("Bobby Joe", new[] { new Pet("Fluffy") });
            var bob = new Person("Bob", new[] { bobbyJoe });
            var littleJoe = new Person("Little Joe");
            var joe = new Person("Joe", new[] { littleJoe });
            Family = new ReactiveList<TreeItem> { bob, joe };

            _addPerson = ReactiveCommand.Create();
            _addPerson.Subscribe(_ =>
            {
                if (SelectedItem == null) return;
                var p = new Person(NewName);
                SelectedItem.AddChild(p);
                p.IsSelected = true;
                p.ExpandPath();
            });
            _addPet = ReactiveCommand.Create();
            _addPet.Subscribe(_ =>
            {
                if (SelectedItem == null) return;
                var p = new Pet(PetName);
                SelectedItem.AddChild(p);
                p.IsSelected = true;
                p.ExpandPath();
            });
            _collapse = ReactiveCommand.Create();
            _collapse.Subscribe(_ =>
            {
                SelectedItem?.CollapsePath();
            });
        }
        public TwoFactorViewModel(IScreen host)
        {
            HostScreen = host;

            var codeHasBeenInput = this.WhenAny(x => x.Code, code => !string.IsNullOrWhiteSpace(code.Value));
            Submit = new ReactiveCommand(codeHasBeenInput);
        }
Exemple #20
0
        public MyPageViewModel(ITicketService ticketService, ITicketMapper mapper)
        {
            _ticketService = ticketService;
            _mapper = mapper;

            LoadTickets = new ReactiveAsyncCommand(null, 1, RxApp.DeferredScheduler);

            LoadTickets.RegisterAsyncFunction(x => loadTickets())
                .ToProperty(this, x => x.Tickets);

            Observable.Interval(TimeSpan.FromSeconds(10), RxApp.DeferredScheduler)
                    .InvokeCommand(LoadTickets);
            LoadTickets.Execute(null);

            _redmineBaseUrl = ConfigurationManager.AppSettings["Redmine.BaseRedmineUrl"];

            SortBy = new List<SortByModel>()
            {
                new SortByModel("Project", c => c.Project),
                new SortByModel("Due date", c=> c.DueDate),
                new SortByModel("Priority", c => c.Priority),
            };

            SortByCommand = new ReactiveCommand(this.WhenAny(c => c.Tickets,
                                                                                                            ((tickets) => tickets.Value != null && tickets.Value.Count > 0)));

            SortByCommand.Subscribe(c => sortTickets((SortByModel)c));
        }
        public OpenDatabaseViewModel(
            INavigationService navigationService,
            IDatabaseInfoRepository databaseInfoRepository,
            ICanSHA256Hash hasher,
            IDialogService dialogService,
            IPWDatabaseDataSource databaseSource,
            ICache cache)
        {
            _cache = cache;
            _databaseSource = databaseSource;
            _dialogService = dialogService;
            _databaseInfoRepository = databaseInfoRepository;
            _hasher = hasher;
            _navigationService = navigationService;
            var canHitOpen = this.WhenAny(
                vm => vm.Password, 
                vm => vm.KeyFileName,
                (p, k) => !string.IsNullOrEmpty(p.Value) || !string.IsNullOrEmpty(k.Value));

            OpenCommand = new ReactiveCommand(canHitOpen);
            OpenCommand.Subscribe(OpenDatabase);

            GetKeyFileCommand = new ReactiveCommand();
            GetKeyFileCommand.Subscribe(GetKeyFile); 
            
            ClearKeyFileCommand = new ReactiveCommand();
            ClearKeyFileCommand.Subscribe(ClearKeyFile);

            IObservable<string> keyFileNameChanged = this.WhenAny(vm => vm.KeyFileName, kf => kf.Value);
            keyFileNameChanged.Subscribe(v => ClearKeyFileButtonIsVisible = !string.IsNullOrWhiteSpace(v));
            keyFileNameChanged.Subscribe(v => GetKeyFileButtonIsVisible = string.IsNullOrWhiteSpace(v));
        }
            public SelectedToolViewModel(UIView toolboxView, AvailableToolsContainerViewController container, MeetingViewModel meeting, IReactiveList<IToolViewModel> selectedTools, NavigationPaneViewModel navigationPane)
            {
                SelectedTools = selectedTools;

                IsEmpty = SelectedTools.Count == 0;
                SelectedTools.Changed.ObserveOn(RxApp.MainThreadScheduler)
                             .Subscribe(p =>
                                        {
                                            IsEmpty = SelectedTools.Count == 0;
                                        });

                var showAvailableToolsCommand = new ReactiveCommand();
                showAvailableToolsCommand.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
                {
                    UIView.BeginAnimations(null);
                    UIView.SetAnimationDuration(0.25);
                    toolboxView.Alpha = 1.0f;
                    UIView.CommitAnimations();
                });

                container.CloseToolboxRequested += (s, e) =>
                                                   {
                                                       UIView.BeginAnimations(null);
                                                       UIView.SetAnimationDuration(0.25);
                                                       toolboxView.Alpha = 0.0f;
                                                       UIView.CommitAnimations();
                                                   };
                ShowAvailableToolsCommand = showAvailableToolsCommand;
                navigationPane.ShowToolLibraryAction = () => ShowAvailableToolsCommand.Execute(null);

                var setActiveToolsCommand = new ReactiveCommand();
                setActiveToolsCommand.ObserveOn(RxApp.MainThreadScheduler)
                    .Subscribe(tool => meeting.ActiveTool = (IToolViewModel)tool);
                SetActiveToolCommand = setActiveToolsCommand;
            }
        public CreateActivityViewModel()
        {
            int result = 0;
            var canSave = this.WhenAny(
                x => x.Name,
                x => x.ExpectedEffort,
                (n, e) => !string.IsNullOrWhiteSpace(n.Value) && int.TryParse(e.Value, out result));
            SaveCommand = new ReactiveCommand(canSave, DispatcherScheduler.Instance);
            SaveCommand.Subscribe(o => Save());

            var prototypeActivity = this.Changed
                .Where(c => c.PropertyName == "Name")
                .Throttle(TimeSpan.FromMilliseconds(500))
                .Select(c => Name)
                .ObserveOnDispatcher()
                // Access to the ActivityRepository synchronized on the main thread... maybe not the best idea
                .Select(n => DomainContext.Activities.Where(a => a.Name == n).OrderByDescending(a => a.CreationTime).FirstOrDefault())
                .Where(a => a != null);

            prototypeActivity
                .Select(a => a.Tags.Select(t => t.Name).ToArray())
                .ObserveOnDispatcher()
                .Subscribe(t => Tags = t);

            prototypeActivity
                .Where(a => string.IsNullOrWhiteSpace(ExpectedEffort))
                .Select(a => a.ExpectedEffort.ToString())
                .ObserveOnDispatcher()
                .Subscribe(ee => ExpectedEffort = ee);

            CancelCommand = new RelayCommand(Cancel);
        }
        public ServiceViewModel(ServiceBase service)
        {
            Name = service.ServiceName;

            //Get an observable for the current state
            var currentStateObs = this.ObservableForProperty(x => x.CurrentState).Value().StartWith(ServiceState.Stopped);

            //Map an observable to IsBusy that is True if the current state is *ing
            currentStateObs.Select
            (
                s => s == ServiceState.Pausing ||
                     s == ServiceState.Starting ||
                     s == ServiceState.Stopping
            )
            .Subscribe(busy => IsBusy = busy);

            StartCommand    = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Stopped));
            StopCommand     = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started || s == ServiceState.Paused));
            PauseCommand    = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started && service.CanPauseAndContinue));
            ContinueCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Paused && service.CanPauseAndContinue));

            AssignmentSubscription(StartCommand,    () => ServiceBaseHelpers.StartService(service));
            AssignmentSubscription(StopCommand,     () => ServiceBaseHelpers.StopService(service));
            AssignmentSubscription(PauseCommand,    () => ServiceBaseHelpers.PauseService(service));
            AssignmentSubscription(ContinueCommand, () => ServiceBaseHelpers.ContinueService(service));

            //
            // Start on start time
            //
            StartCommand.Execute(null);
        }
        public ReactivePropertyBasicsPageViewModel()
        {
            // mode is Flags. (default is all)
            // DistinctUntilChanged is no push value if next value is same as current
            // RaiseLatestValueOnSubscribe is push value when subscribed
            var allMode = ReactivePropertyMode.DistinctUntilChanged | ReactivePropertyMode.RaiseLatestValueOnSubscribe;

            // binding value from UI Control
            // if no set initialValue then initialValue is default(T). int:0, string:null...
            InputText = new ReactiveProperty<string>(initialValue: "", mode: allMode);

            // send value to UI Control
            DisplayText = InputText
                .Select(s => s.ToUpper())       // rx query1
                .Delay(TimeSpan.FromSeconds(1)) // rx query2
                .ToReactiveProperty();          // convert to ReactiveProperty

            ReplaceTextCommand = InputText
                .Select(s => !string.IsNullOrEmpty(s))   // condition sequence of CanExecute
                .ToReactiveCommand(); // convert to ReactiveCommand

            // ReactiveCommand's Subscribe is set ICommand's Execute
            // ReactiveProperty.Value set is push(& set) value
            ReplaceTextCommand.Subscribe(_ => InputText.Value = "Hello, ReactiveProperty!");
        }
 public FolderBrowserTabContentViewModel(IDialogService dialogService)
 {
     this.dialogService = dialogService;
     
     browseFolderCommand = ReactiveCommand.Create();
     browseFolderCommand.Subscribe(_ => BrowseFolder());
 }
        public OrderViewModel()
        {
            this.DisplayName = "Add/Edit Order";

            context = new LittleTravellerDataContext();
            var CanSave = this.Changed.Select(_ => ValidateFields()).StartWith(false);
            SaveCommand = new ReactiveCommand(CanSave);
            SaveCommand.Subscribe(_ => SaveOrder());
            NewOrderNumCommand = new ReactiveCommand();
            NewOrderNumCommand.Subscribe(_ => NewOrderNum());
            CloseTabCommand = new ReactiveCommand();
            CloseTabCommand.Subscribe(_ => TabClosing());
            SaveCommand.Subscribe(_ => SaveOrder());
            var CanAddItem = this.Changed.Select(_ => CanAddItemValidate()).StartWith(false);
            AddItemCommand = new ReactiveCommand(CanAddItem);
            AddItemCommand.Subscribe(_ => AddItem());
            DeleteItemCommand = new ReactiveCommand();
            DeleteItemCommand.OfType<ItemOptionsClass>().Subscribe(item => DeleteItem(item));

            CustomerOptions = (from cs in context.Customers select cs.CompanyName).ToList();
            SeasonOptions = context.Seasons.ToList();
            SizeTypeOptions = context.SizeTypes.ToList();
            ItemOptions = new ReactiveCollection<ItemOptionsClass>();
            _orderItems = new ObservableCollection<ItemOptionsClass>();
            AllSeasonsChecked = true;
            AllSizeTypesChecked = true;

            FillItemOptions();
        }
        public void AllowConcurrentExecutionTest()
        {
            (new TestScheduler()).With(sched => {
                var fixture = new ReactiveCommand(null, true, sched);

                Assert.True(fixture.CanExecute(null));

                var result = fixture.RegisterAsync(_ => Observable.Return(4).Delay(TimeSpan.FromSeconds(5), sched))
                    .CreateCollection();
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(25);
                Assert.Equal(0, result.Count);

                fixture.Execute(null);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(2500);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(5500);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(1, result.Count);
            });
        }
        public CategoryListViewModel(IThemeService themeService,
            IRssReader rssReader,
            IAsyncDownloadManager downloadManager,
            INavigationService navigationService,
            ILockscreenHelper lockscreen,
            IDownloadHelper downloadHelper)
        {
            _themeService = themeService;
            _rssReader = rssReader;
            _downloadManager = downloadManager;
            _navigationService = navigationService;
            _lockscreen = lockscreen;
            _downloadHelper = downloadHelper;

            AddMorePicturesCommand = Items.CountChanged
                                          .Select(_ => Items.Count < imageMetaData.Count())
                                          .ToCommand();

            AddMorePicturesCommand
                .RegisterAsyncTask(value => GetImages((int)value));

            FullScreenCommand = new ReactiveCommand();

            SetLockScreenCommand = new ReactiveCommand();
            SetLockScreenCommand
                .RegisterAsyncTask(value => SetLockscreen(value as CategoryItem));

            DownloadImageCommand = new ReactiveCommand();
            DownloadImageCommand
                .RegisterAsyncTask(value => DownloadImage(value as CategoryItem));
        }
        public PostListViewModel()
        {
            service = new PostService();

            var filters = MessageBus.Current.Listen<PostFilter>(MessageTypes.CurrentPostFilter)
                .Throttle(TimeSpan.FromSeconds(0.7), RxApp.DeferredScheduler);

            var refreshRequests = new ReactiveCommand();
            GlobalCommands.RefreshCommand.RegisterCommand(refreshRequests);

            var filtersToRefresh = refreshRequests
                .Select((_, i) => i)
                .CombineLatest(filters, (i, f) => new {CommandId = i, Filter = f})
                .DistinctUntilChanged(x => x.CommandId)
                .Select(x => x.Filter);

            var results = filters.Merge(filtersToRefresh)
                .ObserveOn(RxApp.TaskpoolScheduler)
                .Select(x => new { TargetFilter = x, Value = service.GetPosts(x) });

            var latestResults = filters
                .CombineLatest(results, (f, r) => new { LatestFilter = f, LatestResult = r })
                .Where(x => Equals(x.LatestFilter, x.LatestResult.TargetFilter))
                .Select(x => x.LatestResult);

            latestResults
                .Select(x => x.Value.Select(p => new PostViewModel
                {
                    Title = p.Title,
                    FeedName = p.FeedName,
                    FeedImage = new Uri(p.FeedImage),
                    PublicationDate = p.PublicationDate
                }).ToList())
                .ToProperty(this, x => x.Posts);
        }