示例#1
0
        public void RAOShouldActuallyRunOnTheTaskpool()
        {
            var deferred = RxApp.DeferredScheduler;
            var taskpool = RxApp.TaskpoolScheduler;

            try {
                var testDeferred = new CountingTestScheduler(Scheduler.Immediate);
                var testTaskpool = new CountingTestScheduler(Scheduler.NewThread);
                RxApp.DeferredScheduler = testDeferred; RxApp.TaskpoolScheduler = testTaskpool;

                var fixture = new ReactiveAsyncCommand();
                var result  = fixture.RegisterAsyncObservable(x =>
                                                              Observable.Return((int)x * 5).Delay(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler));

                fixture.Execute(1);
                Assert.Equal(5, result.First());

                this.Log().InfoFormat("Scheduled {0} items on deferred, {1} items on Taskpool",
                                      testDeferred.ScheduledItems.Count, testTaskpool.ScheduledItems.Count);

                Assert.True(testDeferred.ScheduledItems.Count >= 1);
                Assert.True(testTaskpool.ScheduledItems.Count >= 1);
            } finally {
                RxApp.DeferredScheduler = deferred;
                RxApp.TaskpoolScheduler = taskpool;
            }
        }
        public void SpinnerShouldSpinWhileAppIsSearching()
        {
            (new TestScheduler()).With(sched => {
                // Here, we're going to create a dummy Observable that mocks
                // a web service call - mocking things that happen over time is
                // often tricky, but not with Rx!
                var searchObservable = Observable.Return(createSampleResults())
                                       .Delay(TimeSpan.FromMilliseconds(5000), RxApp.TaskpoolScheduler);

                var command = new ReactiveAsyncCommand();
                command.RegisterAsyncObservable(x => searchObservable);

                var fixture = new AppViewModel(command, searchObservable);

                // The spinner should be hidden on startup
                Assert.AreNotEqual(Visibility.Visible, fixture.SpinnerVisibility);

                // Invoke the command
                fixture.ExecuteSearch.Execute("Robot");

                // Once we run the command, we should be showing the spinner
                sched.RunToMilliseconds(100);
                Assert.AreEqual(Visibility.Visible, fixture.SpinnerVisibility);

                // Fast forward to 6sec, the spinner should now be gone
                sched.RunToMilliseconds(6 * 1000);
                Assert.AreNotEqual(Visibility.Visible, fixture.SpinnerVisibility);
            });
        }
示例#3
0
        public TrackReporter(IObservable <Mix> currentMixObservable, IObservable <double> currentPositionObservable, IRequestExecutor requestExecutor)
        {
            this.requestExecutor = new RequestExecutionAdapter(requestExecutor);
            IObservable <bool> reportingMarkReached = currentPositionObservable
                                                      .BufferWithCount(2, 1)
                                                      .Select(positions => (positions[0] < reportingMark && positions[1] > reportingMark));

            currentMixObservable.Subscribe(mix =>
            {
                currentMix = mix;
            });

            ReactiveAsyncCommand reportTrack = new ReactiveAsyncCommand();

            reportTrack.Subscribe(_ =>
            {
                int mixId   = currentMix.MixId;
                Track track = currentMix.GetCurrentTrack();
                Report(track, mixId);
            });

            reportingMarkReached
            .Where(x => x)                                        // we crossed the mark
            .Where(_ => !currentMix.GetCurrentTrack().IsReported) //it's not previously reported
            .Subscribe(_ => reportTrack.Execute(null));
        }
        public void ChangingSearchTermShouldResultInSearchResults()
        {
            (new TestScheduler()).With(sched => {
                // Create a dummy Observable representing the actual query
                var searchObservable = Observable.Return(createSampleResults())
                                       .Delay(TimeSpan.FromMilliseconds(5 * 1000), RxApp.TaskpoolScheduler);

                // Create a dummy command to pass to the ViewModel that returns
                // our Observable
                var command = new ReactiveAsyncCommand();
                command.RegisterAsyncObservable(x => searchObservable);

                var fixture = new AppViewModel(command, searchObservable);
                Assert.IsTrue(fixture.SearchResults.Count == 0);

                fixture.SearchTerm = "Foo";

                // At 2 seconds in, we shouldn't have results yet
                sched.RunToMilliseconds(2 * 1000);
                Assert.IsTrue(fixture.SearchResults.Count == 0);

                // At 10 seconds, we should have the sample results
                var sampleData = createSampleResults();
                sched.RunToMilliseconds(10 * 1000);
                Assert.AreEqual(sampleData.Count, fixture.SearchResults.Count);

                // Make sure the two sequences are identical
                foreach (var item in sampleData.Zip(fixture.SearchResults, (expected, actual) => new { expected, actual }))
                {
                    Assert.AreEqual(item.expected.Title, item.actual.Title);
                    Assert.AreEqual(item.expected.Description, item.actual.Description);
                    Assert.AreEqual(item.expected.Url, item.actual.Url);
                }
            });
        }
示例#5
0
        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 void AsyncCommandSmokeTest()
        {
            var sched = new TestScheduler();
            IObservable<int> async_data;
            ReactiveAsyncCommand fixture;

            using (TestUtils.WithTestScheduler(sched)) {
                fixture = new ReactiveAsyncCommand(null, 1);
                async_data = fixture
                    .Delay(TimeSpan.FromSeconds(5), RxApp.TaskpoolScheduler)
                    .Select(_ => 5)
                    .Do(_ => fixture.AsyncCompletedNotification.OnNext(new Unit()));
            }

            var inflight_results = new List<int>();
            fixture.ItemsInflight.Subscribe(inflight_results.Add);

            var output = new List<int>();
            async_data.Subscribe(output.Add);

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

            fixture.Execute(null);

            sched.RunToMilliseconds(1005);
            Assert.IsFalse(fixture.CanExecute(null));

            sched.RunToMilliseconds(5005);
            Assert.IsTrue(fixture.CanExecute(null));

            new[] {0,1,0}.AssertAreEqual(inflight_results);
            new[] {5}.AssertAreEqual(output);
        }
        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 void AsyncCommandSmokeTest()
        {
            var inflight_results = new List<int>();
            var fixture = new ReactiveAsyncCommand(null, 1, Scheduler.Immediate);

            var async_data = fixture
                .ObserveOn(Scheduler.NewThread)
                .Delay(new TimeSpan(0, 0, 5))
                .Select(_ => 5)
                .Do(_ => fixture.AsyncCompletedNotification.OnNext(new Unit()));

            fixture.ItemsInflight.Subscribe(x => inflight_results.Add(x));

            async_data.Subscribe();

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

            fixture.Execute(null);
            Assert.IsFalse(fixture.CanExecute(null));

            Thread.Sleep(5500);
            Assert.IsTrue(fixture.CanExecute(null));

            new[] {0,1,0}.Zip(inflight_results, (expected, actual) => new {expected, actual})
                         .Run(x => Assert.AreEqual(x.expected, x.actual));
        }
        public MainWindowViewModel()
        {
            TorrentSelected = new ReactiveCommand();
            DownloadAll = new ReactiveAsyncCommand();
            DeleteSelected = new ReactiveAsyncCommand();

            DeleteSelected.Subscribe(new AnonymousObserver<object>(x =>
            {
                App.streamza.RemoveTorrent(_selectedTorrent.id);
            }));

            DownloadAll.Subscribe(new AnonymousObserver<object>(x =>
            {
                var sel = _selectedTorrent;
                var s = new VistaFolderBrowserDialog();
                var res = s.ShowDialog();
                if (!res.HasValue || res.Value != true) return;

                var files = App.streamza.GetTorrentFiles(sel);
                foreach (var file in files)
                {
                    var uri = App.streamza.GetDownloadLink(file);
                    var cl = new WebClient();
                    var path = Path.Combine(s.SelectedPath, file.path);
                    if (!Directory.Exists(Path.GetDirectoryName(path)))
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                    cl.DownloadFile(new Uri(uri), path);
                }

                // This probably works best when there are lots of small files; doesn't
                // offer any improvement when there are only a couple of large files.
                // TODO: Check file count and set parallelism appropriately
                //Parallel.ForEach(files,
                //    new ParallelOptions { MaxDegreeOfParallelism = 4 },
                //    (file) =>
                //    {
                //        var uri = App.streamza.GetDownloadLink(file);
                //        var cl = new WebClient();
                //        var path = Path.Combine(s.SelectedPath, file.path);
                //        if (!Directory.Exists(Path.GetDirectoryName(path)))
                //            Directory.CreateDirectory(Path.GetDirectoryName(path));
                //        cl.DownloadFile(new Uri(uri), path);
                //    });
            }));

            _torrents = App.streamza.Torrents;

            Observable
                .Start(() =>
                {
                    Observable
                         .Interval(TimeSpan.FromSeconds(10))
                         .Subscribe(i =>
                         {
                             if (FetchingFiles) return;
                             _torrents = App.streamza.Torrents;
                             raisePropertyChanged("Torrents");
                         });
                });
        }
示例#10
0
        public MainWindowViewModel()
        {
            var noneInFlight = new BehaviorSubject<bool>(false);
            var updateManager = default(UpdateManager);

            this.WhenAny(x => x.UpdatePath, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler)
                .Subscribe(x => {
                    if (updateManager != null)  updateManager.Dispose();
                    updateManager = new UpdateManager(UpdatePath, "SampleUpdatingApp", FrameworkVersion.Net40);
                });

            CheckForUpdate = new ReactiveAsyncCommand(noneInFlight);
            CheckForUpdate.RegisterAsyncObservable(_ => updateManager.CheckForUpdate())
                .Subscribe(x => { UpdateInfo = x; DownloadedUpdateInfo = null; });

            DownloadReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => UpdateInfo != null));
            DownloadReleases.RegisterAsyncObservable(_ => updateManager.DownloadReleases(UpdateInfo.ReleasesToApply))
                .Subscribe(_ => DownloadedUpdateInfo = UpdateInfo);

            ApplyReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => DownloadedUpdateInfo != null));
            ApplyReleases.RegisterAsyncObservable(_ => updateManager.ApplyReleases(DownloadedUpdateInfo));

            Observable.CombineLatest(
                CheckForUpdate.ItemsInflight.StartWith(0),
                DownloadReleases.ItemsInflight.StartWith(0),
                ApplyReleases.ItemsInflight.StartWith(0),
                this.WhenAny(x => x.UpdatePath, _ => 0),
                (a, b, c, _) => a + b + c
            ).Select(x => x == 0 && UpdatePath != null).Multicast(noneInFlight).Connect();
        }
示例#11
0
        public SettingsViewModel(
            IScreen screen,
            ISettingsProvider settingsProvider,
            IFolderHelper folderHelper, 
            IAppContext appContext)
        {
            HostScreen = screen;

            BackCommand = new ReactiveAsyncCommand();
            BackCommand.RegisterAsyncAction(_ => HostScreen.Router.NavigateBack.Execute(null));

            SelectFolder = new ReactiveAsyncCommand();
            SelectFolder.RegisterAsyncAction(_ =>
            {
                var result = folderHelper.SelectFolder();
                if (result.Result == true) {
                    UpdateLocation = result.Folder;
                }
            }, appContext.DispatcherScheduler);

            UpdateLocation = settingsProvider.UpdateLocation;

            _IsError = this.WhenAny(vm => vm.UpdateLocation, vm => vm.Value)
                           .DistinctUntilChanged()
                           .Throttle(TimeSpan.FromMilliseconds(500))
                           .ObserveOn(appContext.DispatcherScheduler)
                           .Select(text => !IsUrlOrFolder(text))
                           .Do(error => {
                                if (!error) {
                                    settingsProvider.UpdateLocation = UpdateLocation;
                                }
                            })
                            .ToProperty(this, vm => vm.IsError, setViaReflection: false);
        }
示例#12
0
        public ShellViewModel(
            IScreen screen,
            Func<SettingsViewModel> getSettings,
            Func<CheckForUpdatesViewModel> getForegroundUpdater,
            Func<BackgroundUpdaterViewModel> getBackgroundUpdater)
        {
            HostScreen = screen;

            SettingsCommand = new ReactiveAsyncCommand();
            SettingsCommand.RegisterAsyncAction(o => {
                var viewModel = getSettings();
                HostScreen.Navigate(viewModel);
            });

            UpdateBasicsCommand = new ReactiveAsyncCommand();
            UpdateBasicsCommand.RegisterAsyncAction(o => {
                var viewModel = getForegroundUpdater();
                HostScreen.Navigate(viewModel);
            });

            BackgroundUpdaterCommand = new ReactiveAsyncCommand(Observable.Return(false));
            BackgroundUpdaterCommand.RegisterAsyncAction(o => {
                var viewModel = getBackgroundUpdater();
                HostScreen.Navigate(viewModel);
            });
        }
示例#13
0
        public void MultipleSubscribersShouldntDecrementRefcountBelowZero()
        {
            (new TestScheduler()).With(sched => {
                var fixture        = new ReactiveAsyncCommand();
                var results        = new List <int>();
                bool[] subscribers = new[] { false, false, false, false, false };

                var output = fixture.RegisterAsyncObservable(_ =>
                                                             Observable.Return(5).Delay(TimeSpan.FromMilliseconds(5000), sched));
                output.Subscribe(x => results.Add(x));

                Enumerable.Range(0, 5).Run(x => output.Subscribe(_ => subscribers[x] = true));

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

                fixture.Execute(null);
                sched.AdvanceToMs(2000);
                Assert.False(fixture.CanExecute(null));

                sched.AdvanceToMs(6000);
                Assert.True(fixture.CanExecute(null));

                Assert.True(results.Count == 1);
                Assert.True(results[0] == 5);
                Assert.True(subscribers.All(x => x));
            });
        }
示例#14
0
        public void RAFShouldActuallyRunOnTheTaskpool()
        {
            var deferred = RxApp.DeferredScheduler;
            var taskpool = RxApp.TaskpoolScheduler;

            try {
                var testDeferred = new CountingTestScheduler(Scheduler.Immediate);
                var testTaskpool = new CountingTestScheduler(Scheduler.NewThread);
                RxApp.DeferredScheduler = testDeferred;
                RxApp.TaskpoolScheduler = testTaskpool;

                var fixture = new ReactiveAsyncCommand();
                var result  = fixture.RegisterAsyncFunction(x => {
                    Thread.Sleep(1000);
                    return((int)x * 5);
                });

                fixture.Execute(1);
                Assert.Equal(5, result.First());

                Assert.True(testDeferred.ScheduledItems.Count >= 1);
                Assert.True(testTaskpool.ScheduledItems.Count >= 1);
            } finally {
                RxApp.DeferredScheduler = deferred;
                RxApp.TaskpoolScheduler = taskpool;
            }
        }
        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 CalculatorViewModel()
        {
            _reactiveHelper = new MakeObjectReactiveHelper(this);
            _cache = new MemoizingMRUCache<int, int>((x, ctx) =>
            {
                Thread.Sleep(1000);
                // Pretend this calculation isn’t cheap
                return x*10;
            }, 5);

            CalculateCommand = new ReactiveAsyncCommand(this.WhenAny(x => x.Number, x => x.Value > 0));
            (CalculateCommand as ReactiveAsyncCommand).RegisterAsyncTask<object>(o =>
            {
                return Task.Factory.StartNew(() =>
                {
                    int top;
                    bool cached = _cache.TryGet(    Number, out top);
                    if (cached)
                    {
                        Result = 0;
                        Thread.Sleep(1000);
                        Result = top;
                    }
                    else
                    {
                        top = _cache.Get(Number);
                        for (int i = 0; i <= top; i++)
                        {
                            Result = i;
                            Thread.Sleep(100);
                        }
                    }
                });
            });
        }
        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());
        }
示例#18
0
        public void ChangingSearchTermShouldResultInSearchResults()
        {
            (new TestScheduler()).With(sched => {
                // Create a dummy Observable representing the actual query
                var searchObservable = Observable.Return(createSampleResults())
                    .Delay(TimeSpan.FromMilliseconds(5 * 1000), RxApp.TaskpoolScheduler);

                // Create a dummy command to pass to the ViewModel that returns
                // our Observable
                var command = new ReactiveAsyncCommand();
                command.RegisterAsyncObservable(x => searchObservable);

                var fixture = new AppViewModel(command, searchObservable);
                Assert.IsTrue(fixture.SearchResults.Count == 0);

                fixture.SearchTerm = "Foo";

                // At 2 seconds in, we shouldn't have results yet
                sched.RunToMilliseconds(2 * 1000);
                Assert.IsTrue(fixture.SearchResults.Count == 0);

                // At 10 seconds, we should have the sample results
                var sampleData = createSampleResults();
                sched.RunToMilliseconds(10 * 1000);
                Assert.AreEqual(sampleData.Count, fixture.SearchResults.Count);

                // Make sure the two sequences are identical
                foreach(var item in sampleData.Zip(fixture.SearchResults, (expected, actual) => new { expected, actual })) {
                    Assert.AreEqual(item.expected.Title, item.actual.Title);
                    Assert.AreEqual(item.expected.Description, item.actual.Description);
                    Assert.AreEqual(item.expected.Url, item.actual.Url);
                }
            });
        }
示例#19
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));
        }
示例#20
0
        public SearchViewModel(IScreen hostScreen, ILoginMethods loginMethods)
        {
            HostScreen = hostScreen;
            SearchResults = new ReactiveCollection<ISongTileViewModel>();
            var playApi = loginMethods.CurrentAuthenticatedClient;

            if (playApi == null) {
                hostScreen.Router.Navigate.Execute(RxApp.GetService<IWelcomeViewModel>());
                return;
            }

            var canSearch = this.WhenAny(x => x.SearchQuery, x => !String.IsNullOrWhiteSpace(x.Value));
            PerformSearch = new ReactiveAsyncCommand(canSearch);

            this.ObservableForProperty(x => x.SearchQuery)
                .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler)
                .InvokeCommand(PerformSearch);

            var searchResults = PerformSearch.RegisterAsyncObservable(_ => playApi.Search(SearchQuery));

            SearchResults = searchResults
                .Do(_ => SearchResults.Clear())
                .SelectMany(list => list.ToObservable())
                .LoggedCatch(this, Observable.Empty<Song>())
                .CreateCollection(x => (ISongTileViewModel) new SongTileViewModel(x, playApi));

            PerformSearch.ItemsInflight.StartWith(0)
                .Select(x => x > 0 ? Visibility.Visible : Visibility.Collapsed)
                .ToProperty(this, x => x.SearchBusySpinner);

            PerformSearch.ThrownExceptions.Subscribe(_ => { });

            GoBack = new ReactiveCommand();
            GoBack.InvokeCommand(hostScreen.Router.NavigateBack);
        }
示例#21
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));
        }
示例#22
0
        public ErrorViewModel(IScreen screen,
            Func<ShellViewModel> getShellViewModel)
        {
            HostScreen = screen;

            Back = new ReactiveAsyncCommand();
            Back.Subscribe(_ => HostScreen.Router.NavigateAndReset.Execute(getShellViewModel()));
        }
示例#23
0
 public MainWindowViewModel()
 {
     DoIt = new ReactiveAsyncCommand();
     DoIt.RegisterAsyncObservable(_ => Observable.Timer(TimeSpan.FromSeconds(5.0), RxApp.TaskpoolScheduler))
     .Subscribe(_ => {
         Console.WriteLine("Boom");
     });
 }
示例#24
0
        public ErrorViewModel(IScreen screen,
                              Func <ShellViewModel> getShellViewModel)
        {
            HostScreen = screen;

            Back = new ReactiveAsyncCommand();
            Back.Subscribe(_ => HostScreen.Router.NavigateAndReset.Execute(getShellViewModel()));
        }
        public DownloadVM(
            IDiversityServiceClient Service,
            IConnectivityService Connectivity,
            IFieldDataService Storage,
            IKeyMappingService Mappings,
            EventHierarchyLoader HierarchyLoader,
            [Dispatcher] IScheduler Dispatcher
            ) {
            this.Service = Service;
            this.Connectivity = Connectivity;
            this.Storage = Storage;
            this.Mappings = Mappings;
            this.HierarchyLoader = HierarchyLoader;

            QueryResult = new ReactiveCollection<Event>();

            _IsOnlineAvailable = Connectivity.Status().Select(s => s == ConnectionStatus.Wifi).Do(_ => { this.GetType(); }, ex => { }, () => { })
                .ToProperty(this, x => x.IsOnlineAvailable);

            SearchEvents = new ReactiveAsyncCommand(this.WhenAny(x => x.IsOnlineAvailable, x => x.Value));
            SearchEvents.ShowInFlightNotification(Notifications, DiversityResources.Download_SearchingEvents);
            SearchEvents.ThrownExceptions
                    .ShowServiceErrorNotifications(Notifications)
                    .ShowErrorNotifications(Notifications)
                    .Subscribe();
            SearchEvents
                .RegisterAsyncObservable(query =>
                    Service.GetEventsByLocality(query as string ?? string.Empty)
                    .TakeUntil(this.OnDeactivation())
                )
                .Do(_ => QueryResult.Clear())
                .Subscribe(QueryResult.AddRange);

            CancelDownload = new ReactiveCommand();

            DownloadElement = new ReactiveAsyncCommand(this.WhenAny(x => x.IsOnlineAvailable, x => x.Value));
            DownloadElement.ThrownExceptions
                .ShowServiceErrorNotifications(Notifications)
                .ShowErrorNotifications(Notifications)
                .Subscribe();
            DownloadElement
                .RegisterAsyncObservable(ev => IfNotDownloadedYet(ev as Event)
                    .Select(HierarchyLoader.downloadAndStoreDependencies)
                    .SelectMany(dl => dl.TakeUntil(CancelDownload))
                    .Scan(0, (acc, _) => ++acc)
                    .Do(_ElementsDownloadedSubject.OnNext)
                    );

            _IsDownloading = DownloadElement.ItemsInflight
                .Select(x => x > 0)
                .ToProperty(this, x => x.IsDownloading);

            this.OnDeactivation()
                .Subscribe(_ => Messenger.SendMessage(EventMessage.Default, MessageContracts.INIT));

            _ElementsDownloadedSubject = new Subject<int>();
            _ElementsDownloaded = _ElementsDownloadedSubject.ToProperty(this, x => x.ElementsDownloaded, 0, Dispatcher);
        }
示例#26
0
        public void CanExecuteShouldChangeOnInflightOp()
        {
            (new TestScheduler()).With(sched => {
                var canExecute = sched.CreateHotObservable(
                    sched.OnNextAt(0, true),
                    sched.OnNextAt(250, false),
                    sched.OnNextAt(500, true),
                    sched.OnNextAt(750, false),
                    sched.OnNextAt(1000, true),
                    sched.OnNextAt(1100, false)
                    );

                var fixture           = new ReactiveAsyncCommand(canExecute);
                int calculatedResult  = -1;
                bool latestCanExecute = false;

                fixture.RegisterAsyncObservable(x =>
                                                Observable.Return((int)x * 5).Delay(TimeSpan.FromMilliseconds(900), RxApp.DeferredScheduler))
                .Subscribe(x => calculatedResult = x);

                fixture.CanExecuteObservable.Subscribe(x => latestCanExecute = x);

                // CanExecute should be true, both input observable is true
                // and we don't have anything inflight
                sched.AdvanceToMs(10);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);

                // Invoke a command 10ms in
                fixture.Execute(1);

                // At 300ms, input is false
                sched.AdvanceToMs(300);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // At 600ms, input is true, but the command is still running
                sched.AdvanceToMs(600);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // After we've completed, we should still be false, since from
                // 750ms-1000ms the input observable is false
                sched.AdvanceToMs(900);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
                Assert.Equal(-1, calculatedResult);

                sched.AdvanceToMs(1010);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);
                Assert.Equal(calculatedResult, 5);

                sched.AdvanceToMs(1200);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
            });
        }
        public void CanExecuteShouldChangeOnInflightOp()
        {
            (new TestScheduler()).With(sched => {
                var canExecute = sched.CreateHotObservable(
                    sched.OnNextAt(0, true),
                    sched.OnNextAt(250, false),
                    sched.OnNextAt(500, true),
                    sched.OnNextAt(750, false),
                    sched.OnNextAt(1000, true),
                    sched.OnNextAt(1100, false)
                );

                var fixture = new ReactiveAsyncCommand(canExecute);
                int calculatedResult = -1;
                bool latestCanExecute = false;

                fixture.RegisterAsyncObservable(x =>
                    Observable.Return((int)x * 5).Delay(TimeSpan.FromMilliseconds(900), RxApp.DeferredScheduler))
                    .Subscribe(x => calculatedResult = x);

                fixture.CanExecuteObservable.Subscribe(x => latestCanExecute = x);

                // CanExecute should be true, both input observable is true
                // and we don't have anything inflight
                sched.AdvanceToMs(10);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);

                // Invoke a command 10ms in
                fixture.Execute(1);

                // At 300ms, input is false
                sched.AdvanceToMs(300);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // At 600ms, input is true, but the command is still running
                sched.AdvanceToMs(600);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // After we've completed, we should still be false, since from
                // 750ms-1000ms the input observable is false
                sched.AdvanceToMs(900);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
                Assert.Equal(-1, calculatedResult);

                sched.AdvanceToMs(1010);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);
                Assert.Equal(calculatedResult, 5);

                sched.AdvanceToMs(1200);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
            });
        }
示例#28
0
        public LoginFormViewModel(IAuthenticator authenticator)
        {
            // push the initial values in the observables
            // so that everyone subscribing before the user logs in for the first time
            // sees that the user is not there

            bool initialCredentialsOK = authenticator.TryLoginFromStoredCredentials();

            if (initialCredentialsOK)
            {
                userDataSubject.OnNext(authenticator.UserData);
                UsernameField = authenticator.UserData.Username;
            }
            else
            {
                userDataSubject.OnNext(UserData.NoUser);
                UsernameField = "";
            }


            UserLoggedInObservable = UserDataObservable.Select(x => x != UserData.NoUser);
            _UserLoggedIn          = UserLoggedInObservable.ToProperty(this, x => x.UserLoggedIn);

            LogIn = new ReactiveAsyncCommand(UserLoggedInObservable.Select(x => !x), 1);
            LogIn.RegisterAsyncFunction(_ =>
            {
                bool logicSuccessful = authenticator.Login(UsernameField, PasswordField,
                                                           true);

                if (logicSuccessful)
                {
                    //collapse if the login was successfull
                    IsLoginFormExpanded = false;
                }
                else
                {
                    // if login failed, return the focus to the username field
                    IsUsernameFieldFocused = true;
                }

                return(authenticator.UserData);
            }).Subscribe(userDataSubject.OnNext);

            LogOut = new ReactiveAsyncCommand(UserLoggedInObservable, 1);
            LogOut.RegisterAsyncFunction(_ =>
            {
                authenticator.Logout();
                IsPasswordFieldFocused = true;
                return(authenticator.UserData);
            }).Subscribe(userDataSubject.OnNext);

            _UserData = UserDataObservable.ToProperty(this, x => x.UserData);
        }
示例#29
0
 public Manga(int IdOrder, Library owner, String Name)
 {
     this.Owner = owner;
     this.Name = Name;
     _MangaFromSources = new ObservableCollection<MangaFomSource>();
     MangaFromSources = new ReadOnlyObservableCollection<MangaFomSource>(_MangaFromSources);
     CreationDate = DateTime.Now;
     UpdateDate = DateTime.Now;
     GetDetailCmd = new ReactiveAsyncCommand();
     GetDetailCmd.RegisterAsyncAction(o => GetDetail(o as IList<MangaFomSource>));
     GetDetailCmd.ThrownExceptions.Subscribe(o => global::System.Windows.MessageBox.Show(o.Message));
 }
示例#30
0
 public ChapterFromSource(MangaFomSource owner, ChapterData chapterData)
 {
     this.Name = chapterData.Name;
     this.Source = chapterData.ChapterSource;
     Owner = owner;
     GetChapterCmd = new ReactiveAsyncCommand();
     GetChapterCmd.RegisterAsyncAction(o => Get());
     GetChapterCmd.ThrownExceptions.Subscribe(o => global::System.Windows.MessageBox.Show(o.Message));
     GoToLinkCmd = new ReactiveCommand();
     GoToLinkCmd.Subscribe((o) =>
     {
         App.Controller.NavigateTo(Source.Link);
     });
 }
        public MainViewModel()
        {
            DisplayCommand = new ReactiveCommand(this.WhenAny(x => x.Name, x => !string.IsNullOrEmpty(x.Value)));
            DisplayCommand.Subscribe(_ => MessageBox.Show("You clicked on DisplayCommand: Name is " + Name));

            StartAsyncCommand = new ReactiveAsyncCommand();
            StartAsyncCommand.RegisterAsyncAction(_ =>
            {
                Progress = 0;
                while (Progress <= 100)
                {
                    Progress += 10;
                    Thread.Sleep(100);
                }
            });
        }
        public ApplyUpdatesViewModel(
            IScreen screen,
            Func<UpdateManager> getUpdateManager)
        {
            this.getUpdateManager = getUpdateManager;
            HostScreen = screen;

            Apply = new ReactiveAsyncCommand();
            Apply.Subscribe(_ => applyUpdates());

            Restart = new ReactiveAsyncCommand();
            Restart.Subscribe(_ => restart());

            progress = new Subject<int>();
            progressObservable = progress.ToProperty(this, vm => vm.Progress);
        }
        public ApplyUpdatesViewModel(
            IScreen screen,
            Func <UpdateManager> getUpdateManager)
        {
            this.getUpdateManager = getUpdateManager;
            HostScreen            = screen;

            Apply = new ReactiveAsyncCommand();
            Apply.Subscribe(_ => applyUpdates());

            Restart = new ReactiveAsyncCommand();
            Restart.Subscribe(_ => restart());

            progress           = new Subject <int>();
            progressObservable = progress.ToProperty(this, vm => vm.Progress);
        }
示例#34
0
        public LoginViewModel(IScreen hostScreen, [Named("confirmUserPass")] [Optional] Func<IObservable<Unit>> confirmUserPassMock = null)
        {
            HostScreen = hostScreen;

            var canConfirm = this.WhenAny(x => x.User, x => x.Password,
                (u, p) => !String.IsNullOrWhiteSpace(u.Value) && !String.IsNullOrWhiteSpace(p.Value));

            Confirm = new ReactiveAsyncCommand(canConfirm);

            var confirmFunc = confirmUserPassMock ?? TestUserNameAndPassword;
            var result = Confirm.RegisterAsyncObservable(_ => confirmFunc());

            MessageBus.Current.RegisterMessageSource(result.Select(res => new Tuple<string, string>(User, Password)), "login");

            Confirm.ThrownExceptions.Subscribe(x => 
                UserError.Throw(new UserError("Couldn't Log In", x.Message, new[] {RecoveryCommand.Ok}, null, x)));
        }
示例#35
0
        public TranslatorViewModel()
        {
            TranslateText = new ReactiveAsyncCommand();

            this.ObservableForProperty(x => x.EnglishText)
                .Throttle(TimeSpan.FromMilliseconds(1200))
                .Subscribe(x => TranslateText.Execute(x.Value));

            var client = new LanguageServiceClient() as LanguageService;

            var translation_func = Observable.FromAsyncPattern<string, string>(
                client.BeginTranslateToGerman, client.EndTranslateToGerman);

            var results = TranslateText.RegisterAsyncObservable(x => translation_func((string)x));

            _TranslatedText = this.ObservableToProperty(results, x => x.TranslatedText);
        }
示例#36
0
        public LoginViewModel(IScreen hostScreen, [Named("confirmUserPass")][Optional] Func <IObservable <Unit> > confirmUserPassMock = null)
        {
            HostScreen = hostScreen;

            var canConfirm = this.WhenAny(x => x.User, x => x.Password,
                                          (u, p) => !String.IsNullOrWhiteSpace(u.Value) && !String.IsNullOrWhiteSpace(p.Value));

            Confirm = new ReactiveAsyncCommand(canConfirm);

            var confirmFunc = confirmUserPassMock ?? TestUserNameAndPassword;
            var result      = Confirm.RegisterAsyncObservable(_ => confirmFunc());

            MessageBus.Current.RegisterMessageSource(result.Select(res => new Tuple <string, string>(User, Password)), "login");

            Confirm.ThrownExceptions.Subscribe(x =>
                                               UserError.Throw(new UserError("Couldn't Log In", x.Message, new[] { RecoveryCommand.Ok }, null, x)));
        }
        public MainViewModel()
        {
            DisplayCommand = new ReactiveCommand(this.WhenAny(x => x.Name, x => !string.IsNullOrEmpty(x.Value)));
            DisplayCommand.Subscribe(_ => MessageBox.Show("You clicked on DisplayCommand: Name is " + Name));

            StartAsyncCommand = new ReactiveAsyncCommand();
            StartAsyncCommand.RegisterAsyncAction(_ =>
            {
                Progress = 0;
                while (Progress <= 100)
                {
                    Progress += 10;
                    Thread.Sleep(100);
                }
            });

        }
示例#38
0
        public TranslatorViewModel()
        {
            TranslateText = new ReactiveAsyncCommand();

            this.ObservableForProperty(x => x.EnglishText)
            .Throttle(TimeSpan.FromMilliseconds(1200))
            .Subscribe(x => TranslateText.Execute(x.Value));

            var client = new LanguageServiceClient() as LanguageService;

            var translation_func = Observable.FromAsyncPattern <string, string>(
                client.BeginTranslateToGerman, client.EndTranslateToGerman);

            var results = TranslateText.RegisterAsyncObservable(x => translation_func((string)x));

            _TranslatedText = this.ObservableToProperty(results, x => x.TranslatedText);
        }
示例#39
0
        public AppViewModel(ReactiveAsyncCommand reactiveAsyncCommand       = null,
                            IObservable <List <FlickrPhoto> > searchResults = null)
        {
            ExecuteSearch = reactiveAsyncCommand ?? new ReactiveAsyncCommand();
            ReactiveCommandMixins.InvokeCommand(this.ObservableForProperty(model => model.SearchTerm)
                                                .Throttle(TimeSpan.FromMilliseconds(800), RxApp.TaskpoolScheduler)
                                                .Select(x => x.Value)
                                                .DistinctUntilChanged()
                                                .Where(x => !string.IsNullOrWhiteSpace(x)), ExecuteSearch);
            _spinnerVisibility =
                ExecuteSearch.ItemsInflight.Select(x => x > 0 ? Visibility.Visible : Visibility.Collapsed)
                .ToProperty(this, model => model.SpinnerVisibility, Visibility.Hidden);
            var results = searchResults ??
                          ExecuteSearch.RegisterAsyncFunction(term => GetSearchResultFromFlickr((string)term));

            _searchResults = results.ToProperty(this, model => model.SearchResults, new List <FlickrPhoto>());
        }
示例#40
0
        public MainWindowViewModel()
        {
            this.Tools = new ReactiveCollection<IToolViewModel> { IoC.Instance.Resolve<ITestsTreeViewModel>() };
            this.Charts = new ObservableCollection<IChartViewModel>();

            MessageBus.Current.Listen<TestCheckChanged>().Subscribe(OnTestCheckChanged);

            var errorHandler = IoC.Instance.Resolve<ErrorHandler>();

            MessageBus.Current.Listen<LoadAssembly>()
                      .Subscribe(OnLoadAssembly);

            MessageBus.Current.Listen<ClearAssembliesList>().Subscribe(OnClearAssembliesList);

            DocClosed = new ReactiveAsyncCommand();
            DocClosed.RegisterAsyncAction(OnDocumentClosed, RxApp.DeferredScheduler);
            errorHandler.HandleErrors(this.DocClosed);
        }
示例#41
0
 public Library()
 {
     _Mangas = new ObservableCollection<Manga>();
     Mangas = new ReadOnlyObservableCollection<Manga>(_Mangas);
     _Source = new ObservableCollection<Source>();
     Sources = new ReadOnlyObservableCollection<Source>(_Source);
     _Source.Add(new Source("MangaHere", MangaHere.getMangas, MangaHere.getNews, MangaHere.getDetailManga, MangaHere.getChapters));
     _Source.Add(new Source("MangaReader", MangaReader.getMangas, MangaReader.getNews, MangaReader.getDetailManga, MangaReader.getChapters));
     dispatcher = Dispatcher.CurrentDispatcher;
     GetNewsCmd = new ReactiveAsyncCommand();
     GetNewsCmd.RegisterAsyncAction(o => GetNews(o as IList<Source>));
     GetNewsCmd.ThrownExceptions.Subscribe(o => global::System.Windows.MessageBox.Show(o.Message));
     GetMangasCmd = new ReactiveAsyncCommand();
     GetMangasCmd.RegisterAsyncAction(o => GetMangas(o as IList<Source>));
     GetMangasCmd.ThrownExceptions.Subscribe(o => global::System.Windows.MessageBox.Show(o.Message));
     //  if (!DesignTimeHelper.IsDesignTime())
     //GetNewsCmd.Execute(_Source);
 }
示例#42
0
        public void MultipleResultsFromObservableShouldntDecrementRefcountBelowZero()
        {
            (new TestScheduler()).With(sched => {
                int latestInFlight = 0;
                var fixture        = new ReactiveAsyncCommand(null, 1, sched);

                var results = fixture
                              .RegisterAsyncObservable(_ => new[] { 1, 2, 3 }.ToObservable())
                              .CreateCollection();
                fixture.ItemsInflight.Subscribe(x => latestInFlight = x);


                fixture.Execute(1);
                sched.Start();

                Assert.Equal(3, results.Count);
                Assert.Equal(0, latestInFlight);
            });
        }
        public MainWindowViewModel()
        {
            this.Tools = new ReactiveCollection <IToolViewModel> {
                IoC.Instance.Resolve <ITestsTreeViewModel>()
            };
            this.Charts = new ObservableCollection <IChartViewModel>();

            MessageBus.Current.Listen <TestCheckChanged>().Subscribe(OnTestCheckChanged);

            var errorHandler = IoC.Instance.Resolve <ErrorHandler>();

            MessageBus.Current.Listen <LoadAssembly>()
            .Subscribe(OnLoadAssembly);

            MessageBus.Current.Listen <ClearAssembliesList>().Subscribe(OnClearAssembliesList);

            DocClosed = new ReactiveAsyncCommand();
            DocClosed.RegisterAsyncAction(OnDocumentClosed, RxApp.DeferredScheduler);
            errorHandler.HandleErrors(this.DocClosed);
        }
        public MainWindowViewModel()
        {
            CalculateTheAnswer = new ReactiveAsyncCommand();

            CalculateTheAnswer.RegisterAsyncTask(_ => AnswerCalculator())
                .ToProperty(this, x => x.TheAnswer);

            CalculateTheAnswer.ThrownExceptions
                .SelectMany(ex => UserError.Throw(ex.Message))
                .Subscribe(result =>
                {
                    if (result == RecoveryOptionResult.RetryOperation)
                    {
                        _retryCalculate = true;
                        CalculateTheAnswer.Execute(null);
                    }
                    else
                        Application.Current.Shutdown();
                });
        }
示例#45
0
        public SearchViewModel(IScreen hostScreen, ILoginMethods loginMethods, [Named("UserAccount")] IBlobCache userCache)
        {
            HostScreen    = hostScreen;
            SearchResults = new ReactiveCollection <ISongTileViewModel>();
            var playApi = loginMethods.CurrentAuthenticatedClient;

            if (playApi == null)
            {
                hostScreen.Router.Navigate.Execute(RxApp.GetService <IWelcomeViewModel>());
                return;
            }

            var canSearch = this.WhenAny(x => x.SearchQuery, x => !String.IsNullOrWhiteSpace(x.Value));

            PerformSearch = new ReactiveAsyncCommand(canSearch);

            this.ObservableForProperty(x => x.SearchQuery)
            .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler)
            .InvokeCommand(PerformSearch);

            var searchResults = PerformSearch.RegisterAsyncObservable(_ =>
                                                                      userCache.GetOrFetchObject(
                                                                          "search__" + SearchQuery,
                                                                          () => playApi.Search(SearchQuery),
                                                                          RxApp.TaskpoolScheduler.Now + TimeSpan.FromMinutes(1.0)));

            SearchResults = searchResults
                            .Do(_ => SearchResults.Clear())
                            .SelectMany(list => list.ToObservable())
                            .LoggedCatch(this, Observable.Empty <Song>())
                            .CreateCollection(x => (ISongTileViewModel) new SongTileViewModel(x, playApi));

            PerformSearch.ItemsInflight.StartWith(0)
            .Select(x => x > 0 ? Visibility.Visible : Visibility.Hidden)
            .ToProperty(this, x => x.SearchBusySpinner);

            PerformSearch.ThrownExceptions.Subscribe(_ => { });

            GoBack = new ReactiveCommand();
            GoBack.InvokeCommand(hostScreen.Router.NavigateBack);
        }
示例#46
0
        public MainViewModel()
        {
            IsInProgress = Visibility.Collapsed;

            LoginCommand = new ReactiveAsyncCommand(this.WhenAny(t => t.UserName, t => t.Password, (x, y) => !string.IsNullOrEmpty(x.Value) && !string.IsNullOrEmpty(y.Value)));

            LoginCommand.ItemsInflight.Select(x => x > 0 ? Visibility.Visible : Visibility.Collapsed).Subscribe(x => IsInProgress = x);
            LoginCommand.RegisterAsyncFunction(_ => _gitHubService.Login(UserName, Password)).Subscribe(
                u => LoggedInUser = u);

            this.ObservableForProperty(x => x.LoggedInUser,
                                       user => user == null ? Visibility.Hidden : Visibility.Visible).Subscribe(v => IsUserLoggedIn = v);

            _cache = new MemoizingMRUCache<User, Repository[]>((user,_) =>
                                                                          _gitHubService.GetRepositories(user), 3);

            this.WhenAny(t => t.LoggedInUser, u => u.Value != null).Where(filter => filter).Subscribe(_ =>

                    Repositories = new ReactiveCollection<Repository>(_cache.Get(LoggedInUser))
            );
        }
示例#47
0
        public void ReactiveAsyncCommandInitialConditionDefaultBehavior()
        {
            (new TestScheduler()).With(sched => {
                var canExecute = sched.CreateHotObservable(
                    sched.OnNextAt(0, false),
                    sched.OnNextAt(250, true)
                    );

                var fixture = new ReactiveAsyncCommand(canExecute);

                fixture.RegisterAsyncTask(_ => DummyTestFunction());

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

                sched.AdvanceToMs(10);
                Assert.False(fixture.CanExecute(null));

                sched.AdvanceToMs(255);
                Assert.True(fixture.CanExecute(null));
            });
        }
示例#48
0
        public void MakeSureMemoizedReleaseFuncGetsCalled()
        {
            //Assert.True(false, "When an item gets evicted from the cache before it has a chance to complete, it deadlocks. Fix it.");
            var input = new[] { 1, 1, 2, 2, 1, 1, 3, 3 };

            var sched    = new EventLoopScheduler();
            var fixture  = new ReactiveAsyncCommand();
            var results  = new List <Timestamped <int> >();
            var released = new List <int>();

            fixture.RegisterMemoizedFunction(x => { Thread.Sleep(250); return(((int)x) * 5); }, 2, x => released.Add(x), sched)
            .Timestamp()
            .DebugObservable()
            .Subscribe(x => results.Add(x));

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

            var start = DateTimeOffset.Now;

            foreach (var i in input)
            {
                Assert.True(fixture.CanExecute(i));
                fixture.Execute(i);
            }

            Thread.Sleep(1000);

            this.Log().Info("Timestamp Deltas");
            results.Select(x => x.Timestamp - start)
            .Run(x => this.Log().Info(x));

            this.Log().Info("Release list");
            released.Run(x => this.Log().Info(x));

            Assert.True(results.Count == 8);

            Assert.True(released.Count == 1);
            Assert.True(released[0] == 2 * 5);
        }
        public CheckForUpdatesViewModel(
            IScreen screen,
            ISettingsProvider settingsProvider,
            Func <UpdateManager> getUpdateManager,
            Lazy <DownloadUpdatesViewModel> getDownloadViewModel)
        {
            HostScreen                = screen;
            this.settingsProvider     = settingsProvider;
            this.getUpdateManager     = getUpdateManager;
            this.getDownloadViewModel = getDownloadViewModel;

            CheckCommand = new ReactiveAsyncCommand();
            CheckCommand.Subscribe(_ => checkForUpdates());

            BackCommand = new ReactiveAsyncCommand();
            BackCommand.Subscribe(_ => HostScreen.Router.NavigateBack.Execute(null));

            progress           = new Subject <int>();
            progressObservable = progress.ToProperty(
                this,
                vm => vm.Progress);
        }
示例#50
0
        public MainWindowViewModel()
        {
            var noneInFlight  = new BehaviorSubject <bool>(false);
            var updateManager = default(UpdateManager);

            this.WhenAny(x => x.UpdatePath, x => x.Value)
            .Where(x => !String.IsNullOrWhiteSpace(x))
            .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler)
            .Subscribe(x => updateManager = new UpdateManager(UpdatePath, "SampleUpdatingApp", FrameworkVersion.Net40));

            CheckForUpdate = new ReactiveAsyncCommand(noneInFlight);
            CheckForUpdate.RegisterAsyncFunction(_ => {
                using (updateManager.AcquireUpdateLock()) {
                    return(updateManager.CheckForUpdate().Last());
                }
            }).Subscribe(x => { UpdateInfo = x; DownloadedUpdateInfo = null; });

            DownloadReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => UpdateInfo != null));
            DownloadReleases.RegisterAsyncFunction(_ => {
                using (updateManager.AcquireUpdateLock()) {
                    return(updateManager.DownloadReleases(UpdateInfo.ReleasesToApply).Last());
                }
            }).Subscribe(_ => DownloadedUpdateInfo = UpdateInfo);

            ApplyReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => DownloadedUpdateInfo != null));
            ApplyReleases.RegisterAsyncFunction(_ => {
                using (updateManager.AcquireUpdateLock()) {
                    return(updateManager.ApplyReleases(DownloadedUpdateInfo).Last());
                }
            });

            Observable.CombineLatest(
                CheckForUpdate.ItemsInflight.StartWith(0),
                DownloadReleases.ItemsInflight.StartWith(0),
                ApplyReleases.ItemsInflight.StartWith(0),
                this.WhenAny(x => x.UpdatePath, _ => 0),
                (a, b, c, _) => a + b + c
                ).Select(x => x == 0 && UpdatePath != null).Multicast(noneInFlight).Connect();
        }
示例#51
0
        public void CommandBinderBindsToButton()
        {
            var fixture = new CreatesCommandBindingViaCommandParameter();
            var origCmd = new ReactiveAsyncCommand();
            var cmd     = new ReactiveCommand();
            var input   = new Button {
                Command = origCmd, CommandParameter = 42
            };

            Assert.True(fixture.GetAffinityForObject(input.GetType(), true) <= 0);
            Assert.True(fixture.GetAffinityForObject(input.GetType(), false) > 0);

            var disp = fixture.BindCommandToObject(cmd, input, Observable.Return((object)5));

            Assert.Equal(cmd, input.Command);
            Assert.Equal(5, input.CommandParameter);

            disp.Dispose();

            Assert.Equal(origCmd, input.Command);
            Assert.Equal(42, input.CommandParameter);
        }
        public SongTileViewModel(Song model, IPlayApi playApi)
        {
            Model = model;

            playApi.FetchImageForAlbum(model)
            .LoggedCatch(this, Observable.Return(default(BitmapImage)))
            .ToProperty(this, x => x.AlbumArt);

            QueueSong  = new ReactiveAsyncCommand();
            QueueAlbum = new ReactiveAsyncCommand();

            QueueSong.RegisterAsyncObservable(_ => playApi.QueueSong(Model))
            .Subscribe(
                x => this.Log().Info("Queued {0}", Model.name),
                ex => this.Log().WarnException("Failed to queue", ex));

            QueueAlbum.RegisterAsyncObservable(_ => playApi.AllSongsOnAlbum(Model.artist, Model.album))
            .SelectMany(x => x.ToObservable())
            .Select(x => reallyTryToQueueSong(playApi, x)).Concat()
            .Subscribe(
                x => this.Log().Info("Queued song"),
                ex => this.Log().WarnException("Failed to queue album", ex));

            QueueAlbum.ThrownExceptions.Subscribe(x => { });

            IsStarred     = model.starred;
            ToggleStarred = new ReactiveAsyncCommand();

            ToggleStarred.RegisterAsyncObservable(_ => IsStarred ? playApi.Unstar(Model) : playApi.Star(Model))
            .Select(_ => true).LoggedCatch(this, Observable.Return(false))
            .Subscribe(result => {
                if (result)
                {
                    IsStarred = !IsStarred;
                }
            }, ex => this.Log().WarnException("Couldn't star/unstar song", ex));

            ToggleStarred.ThrownExceptions.Subscribe(x => { });
        }
示例#53
0
        public void RegisterMemoizedFunctionSmokeTest()
        {
            var input   = new[] { 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
            var output  = new[] { 5, 5, 5, 5, 5, 10, 10, 10, 10, 10 };
            var sched   = new EventLoopScheduler();
            var results = new List <Timestamped <int> >();

            var start = sched.Now;

            sched.With(_ => {
                var fixture = new ReactiveAsyncCommand(null, 5, sched);

                fixture.RegisterMemoizedFunction(x => {
                    Thread.Sleep(1000);
                    return(((int)x) * 5);
                }, 50, null, sched)
                .Timestamp()
                .Subscribe(x => results.Add(x));

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

                foreach (var i in input)
                {
                    Assert.True(fixture.CanExecute(i));
                    fixture.Execute(i);
                }

                Thread.Sleep(2500);
            });

            Assert.Equal(10, results.Count);

            results.Select(x => x.Timestamp - start)
            .Run(x => { });

            output.AssertAreEqual(results.Select(x => x.Value));

            Assert.False(results.Any(x => x.Timestamp - start > new TimeSpan(0, 0, 3)));
        }
示例#54
0
        public MainViewModel()
        {
            IsInProgress = Visibility.Collapsed;

            LoginCommand = new ReactiveAsyncCommand(this.WhenAny(t => t.UserName, t => t.Password, (x, y) => !string.IsNullOrEmpty(x.Value) && !string.IsNullOrEmpty(y.Value)));

            LoginCommand.ItemsInflight.Select(x => x > 0 ? Visibility.Visible : Visibility.Collapsed).Subscribe(x => IsInProgress = x);
            LoginCommand.RegisterAsyncFunction(_ => _gitHubService.Login(UserName, Password)).Subscribe(
                u => LoggedInUser = u);

            this.ObservableForProperty(x => x.LoggedInUser,
                                       user => user == null ? Visibility.Hidden : Visibility.Visible).Subscribe(v => IsUserLoggedIn = v);


            _cache = new MemoizingMRUCache <User, Repository[]>((user, _) =>
                                                                _gitHubService.GetRepositories(user), 3);

            this.WhenAny(t => t.LoggedInUser, u => u.Value != null).Where(filter => filter).Subscribe(_ =>

                                                                                                      Repositories = new ReactiveCollection <Repository>(_cache.Get(LoggedInUser))
                                                                                                      );
        }
        public CheckForUpdatesViewModel(
            IScreen screen,
            ISettingsProvider settingsProvider,
            Func<UpdateManager> getUpdateManager,
            Lazy<DownloadUpdatesViewModel> getDownloadViewModel)
        {
            HostScreen = screen;
            this.settingsProvider = settingsProvider;
            this.getUpdateManager = getUpdateManager;
            this.getDownloadViewModel = getDownloadViewModel;

            CheckCommand = new ReactiveAsyncCommand();
            CheckCommand.Subscribe(_ => checkForUpdates());

            BackCommand = new ReactiveAsyncCommand();
            BackCommand.Subscribe(_ => HostScreen.Router.NavigateBack.Execute(null));

            progress = new Subject<int>();
            progressObservable = progress.ToProperty(
                this,
                vm => vm.Progress);
        }
示例#56
0
        public void MakeSureMemoizedReleaseFuncGetsCalled()
        {
            var input = new[] { 1, 1, 2, 2, 1, 1, 3, 3 };
            var output = new[] { 5, 5, 10, 10, 5, 5, 15, 15 };

            var fixture = new ReactiveAsyncCommand(null, 0);
            var results = new List<Timestamped<int>>();
            var released = new List<int>();

            fixture.RegisterMemoizedFunction<int>(x => { Thread.Sleep(250); return ((int)x) * 5; }, 2, x => released.Add(x))
                   .Timestamp()
                   .DebugObservable()
                   .Subscribe(x => results.Add(x));

            Assert.IsTrue(fixture.CanExecute(1));

            var start = DateTimeOffset.Now;
            foreach(var i in input) {
                Assert.IsTrue(fixture.CanExecute(i));
                fixture.Execute(i);
            }

            Thread.Sleep(1000);

            this.Log().Info("Timestamp Deltas");
            results.Select(x => x.Timestamp - start)
                   .Run(x => this.Log().Info(x));

            this.Log().Info("Release list");
            released.Run(x => this.Log().Info(x));

            output.Zip(results.Select(x => x.Value), (expected, actual) => new { expected, actual })
                  .Run(x => Assert.AreEqual(x.expected, x.actual));

            Assert.IsTrue(results.Count == 8);

            Assert.IsTrue(released.Count == 1);
            Assert.IsTrue(released[0] == 2*5);
        }
        public DownloadUpdatesViewModel(
            IScreen screen,
            Func<UpdateManager> getUpdateManager,
            Lazy<ApplyUpdatesViewModel> getApplyViewModel)
        {
            HostScreen = screen;
            this.getUpdateManager = getUpdateManager;
            this.getApplyViewModel = getApplyViewModel;

            Download = new ReactiveAsyncCommand();
            Download.Subscribe(_ => downloadUpdates());

            progress = new Subject<int>();
            progressObs = progress.ToProperty(
                this,
                vm => vm.Progress);

            var updateInfoChanges = 
                this.WhenAny(vm => vm.UpdateInfo, x => x.Value)
                    .Where(info => info != null);

            updateCountObs =
                updateInfoChanges
                    .Select(info => info.ReleasesToApply.Count())
                    .ToProperty(this, vm => vm.UpdateCount);

            updateSizeObs =
                updateInfoChanges
                    .Select(info => info.ReleasesToApply.Sum(x => x.Filesize))
                    .Select(total => String.Format("({0:n0} bytes)", total))
                    .ToProperty(this, vm => vm.UpdateSize);

            latestVersionObs = updateInfoChanges
                .Select(info => info.FutureReleaseEntry.Version.ToString())
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .ToProperty(this, vm => vm.LatestVersion);
        }
        public DropRepoViewModel(IScreen hostScreen, IAppState appState, IRepoAnalysisProvider analyzeFunc)
        {
            HostScreen = hostScreen;

            AnalyzeRepo = new ReactiveAsyncCommand();

            CoreUtility.ExtractLibGit2();

            var scanResult = AnalyzeRepo.RegisterAsyncObservable(x => analyzeFunc.AnalyzeRepo((string)x));

            scanResult.Select(x => x.Item1).ToProperty(this, x => x.CurrentRepoPath);
            scanResult
            .Select(x => x.Item2.Select(y => (IBranchInformationViewModel) new BranchInformationViewModel(y.Key, y.Value)))
            .Select(x => new ReactiveCollection <IBranchInformationViewModel>(x))
            .ToProperty(this, x => x.BranchInformation);

            this.WhenAny(x => x.BranchInformation, x => x.Value != null ? Visibility.Visible : Visibility.Hidden)
            .ToProperty(this, x => x.RepairButtonVisibility);

            RepairButton = new ReactiveCommand();
            RepairButton.Subscribe(_ => {
                appState.BranchInformation           = BranchInformation.Where(x => x.BranchName != Constants.WorkingDirectory).ToArray();
                appState.WorkingDirectoryInformation = BranchInformation.First(x => x.BranchName == Constants.WorkingDirectory).Model;
                appState.CurrentRepo = CurrentRepoPath;

                HostScreen.Router.Navigate.Execute(RxApp.GetService <IRepairViewModel>());
            });

            var viewStates = Observable.Merge(
                AnalyzeRepo.ItemsInflight.Where(x => x > 0).Select(_ => "Analyzing"),
                scanResult.Select(_ => "RepoAdded"));

            MessageBus.Current.RegisterMessageSource(viewStates, "DropRepoViewState");

            this.WhenNavigatedTo(() =>
                                 MessageBus.Current.Listen <string>("DropFolder").Subscribe(path => AnalyzeRepo.Execute(path)));
        }
示例#59
-1
        public HyperCommand(JsonServiceClient client ,Grandsys.Wfm.Services.Outsource.ServiceModel.Link link)
        {
            Content = link.Name;
            Command = new ReactiveAsyncCommand();
            Method = link.Method;
            Request = link.Request;
            Response = Command.RegisterAsyncFunction(_ => {

                Model.EvaluationItem response;
                if (string.IsNullOrEmpty(Method))
                    return null;

                switch (Method)
                {
                    default:
                        response = client.Send<Model.EvaluationItem>(Method, Request.ToUrl(Method), _ ?? Request);
                        break;
                    case "GET":
                        response = client.Get<Model.EvaluationItem>(Request.ToUrl(Method));
                        break;
                }
                return response;
            });
            Command.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex.Message));
        }
示例#60
-1
        public WelcomeViewModel(MediaPicker picker)
        {
            TakeNewPhoto = new ReactiveAsyncCommand();
            ChooseExistingPhoto = new ReactiveAsyncCommand();
            StartEdit = new ReactiveCommand();

            var defaultCamera = new StoreCameraMediaOptions() { DefaultCamera = CameraDevice.Rear, Directory = "LeeMe", Name = "turnt.jpg", };

            Observable.Merge(
                    TakeNewPhoto.RegisterAsyncTask(_ => picker.TakePhotoAsync(defaultCamera)),
                    ChooseExistingPhoto.RegisterAsyncTask(_ => picker.PickPhotoAsync()))
                .Select(x => x.Path)
                .InvokeCommand(StartEdit);

            // TODO: Write a proper UserError handler for this
            TakeNewPhoto.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex));
            ChooseExistingPhoto.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex));
        }