Exemplo n.º 1
0
        public NeuronTreePaneViewModel(INeuronApplicationService neuronApplicationService = null, INeuronQueryService neuronQueryService = null, INotificationApplicationService notificationApplicationService = null,
                                       IStatusService statusService = null, IDialogService dialogService = null, IOriginService originService = null)
        {
            this.dialogService                  = dialogService ?? Locator.Current.GetService <IDialogService>();
            this.neuronApplicationService       = neuronApplicationService ?? Locator.Current.GetService <INeuronApplicationService>();
            this.neuronQueryService             = neuronQueryService ?? Locator.Current.GetService <INeuronQueryService>();
            this.notificationApplicationService = notificationApplicationService ?? Locator.Current.GetService <INotificationApplicationService>();
            this.statusService                  = statusService ?? Locator.Current.GetService <IStatusService>();
            this.originService                  = originService ?? Locator.Current.GetService <IOriginService>();

            this.statusService.WhenPropertyChanged(s => s.Message)
            .Subscribe(s => this.StatusMessage = s.Sender.Message);

            bool DefaultPredicate(Node <Neuron, int> node) => node.IsRoot;

            var cache = new SourceCache <Neuron, int>(x => x.UIId);

            this.AddCommand       = ReactiveCommand.Create <object>(async(parameter) => await this.OnAddClicked(cache, parameter));
            this.SetRegionCommand = ReactiveCommand.Create <object>(async(parameter) => await this.OnSetRegionIdClicked(parameter));
            this.ReloadCommand    = ReactiveCommand.Create(async() => await this.OnReloadClicked(cache));

            this.cleanUp = cache.AsObservableCache().Connect()
                           .TransformToTree(child => child.CentralUIId, Observable.Return((Func <Node <Neuron, int>, bool>)DefaultPredicate))
                           .Transform(e =>
                                      e.Item.Type == RelativeType.Postsynaptic ?
                                      (NeuronViewModelBase)(new PostsynapticViewModel(this, e.Item.Tag, e, cache)) :
                                      (NeuronViewModelBase)(new PresynapticViewModel(this, e.Item.Tag, e, cache)))
                           .Bind(out this.children)
                           .DisposeMany()
                           .Subscribe();

            this.Target         = null;
            this.Loading        = false;
            this.IconSourcePath = @"pack://application:,,,/d23-wpf;component/images/hierarchy.ico";
        }
Exemplo n.º 2
0
        public LineScroller(FileInfo file,
                IObservable<ILineProvider> latest,
                IObservable<ScrollRequest> scrollRequest,
                ILogger logger,
                IScheduler scheduler = null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (latest == null) throw new ArgumentNullException(nameof(latest));
            if (logger == null) throw new ArgumentNullException(nameof(logger));

            logger.Info($"Constructing file tailer for {file.FullName}");

            var lines = new SourceCache<Line, LineKey>(l=>l.Key);
            Lines = lines.AsObservableCache();

            var locker = new object();
            scrollRequest = scrollRequest.Synchronize(locker);


            var aggregator = latest.CombineLatest(scrollRequest, (currentLines, scroll) => currentLines.ReadLines(scroll).ToArray())
                .Subscribe(currentPage =>
                {
                    var previous = lines.Items.ToArray();
                    var added = currentPage.Except(previous,Line.TextStartComparer).ToArray();
                    var removed = previous.Except(currentPage, Line.TextStartComparer).ToArray();

                    lines.Edit(innerCache =>
                    {
                        if (removed.Any()) innerCache.Remove(removed);
                        if (added.Any()) innerCache.AddOrUpdate(added);
                    });
                });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
Exemplo n.º 3
0
 protected DataServiceBase(
     ISettingsService settingsService,
     INotificationCenterService notificationCenter)
 {
     _readOnlyCache = cache.AsObservableCache();
     this.cache.DisposeWith(disposables);
     this.settingsService    = settingsService;
     this.notificationCenter = notificationCenter;
 }
Exemplo n.º 4
0
        public StrategyService()
        {
            _availableEntitiesCache = new SourceCache <IStrategy, String>(price => price.EntityCacheKey);
            _availableEntities      = _availableEntitiesCache.AsObservableCache();

            _availableEntitiesCache.Edit(innerCache =>
            {
                innerCache.AddOrUpdate(Enumerable.Range(0, 5).Select(_ => new Strategy()));
            });
        }
Exemplo n.º 5
0
        public LineScroller([NotNull] IObservable <ILineProvider> latest, [NotNull] IObservable <ScrollRequest> scrollRequest)
        {
            if (latest == null)
            {
                throw new ArgumentNullException(nameof(latest));
            }
            if (scrollRequest == null)
            {
                throw new ArgumentNullException(nameof(scrollRequest));
            }


            var lines = new SourceCache <Line, LineKey>(l => l.Key);

            Lines = lines.AsObservableCache();

            var locker = new object();

            scrollRequest = scrollRequest.Synchronize(locker);
            latest        = latest.Synchronize(locker);

            var aggregator = latest
                             .CombineLatest(scrollRequest, (currentLines, scroll) => new { currentLines, scroll })
                             .Sample(TimeSpan.FromMilliseconds(50))
                             .Select(x =>
            {
                if (x.scroll.PageSize == 0 || x.currentLines.Count == 0)
                {
                    return(new Line[0]);
                }

                return(x.currentLines.ReadLines(x.scroll).ToArray());
            })
                             .Subscribe(currentPage =>
            {
                var previous = lines.Items.ToArray();
                var added    = currentPage.Except(previous, Line.TextStartComparer).ToArray();
                var removed  = previous.Except(currentPage, Line.TextStartComparer).ToArray();


                lines.Edit(innerCache =>
                {
                    if (removed.Any())
                    {
                        innerCache.Remove(removed);
                    }
                    if (added.Any())
                    {
                        innerCache.AddOrUpdate(added);
                    }
                });
            });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
Exemplo n.º 6
0
        public LineScroller([NotNull] IObservable <ILineProvider> latest, [NotNull] IObservable <ScrollRequest> scrollRequest)
        {
            if (latest == null)
            {
                throw new ArgumentNullException(nameof(latest));
            }
            if (scrollRequest == null)
            {
                throw new ArgumentNullException(nameof(scrollRequest));
            }


            var lines = new SourceCache <Line, LineKey>(l => l.Key);

            Lines = lines.AsObservableCache();

            var locker = new object();

            scrollRequest = scrollRequest.Synchronize(locker);
            latest        = latest.Synchronize(locker);

            var aggregator = latest
                             .CombineLatest(scrollRequest, (currentLines, scroll) =>
            {
                try
                {
                    return(currentLines.ReadLines(scroll).ToArray());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            })
                             .Subscribe(currentPage =>
            {
                var previous = lines.Items.ToArray();
                var added    = currentPage.Except(previous, Line.TextStartComparer).ToArray();
                var removed  = previous.Except(currentPage, Line.TextStartComparer).ToArray();


                lines.Edit(innerCache =>
                {
                    if (removed.Any())
                    {
                        innerCache.Remove(removed);
                    }
                    if (added.Any())
                    {
                        innerCache.AddOrUpdate(added);
                    }
                });
            });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
Exemplo n.º 7
0
        public LineScroller(FileInfo file,
                            IObservable <ILineProvider> latest,
                            IObservable <ScrollRequest> scrollRequest,
                            ILogger logger,
                            IScheduler scheduler = null)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }
            if (latest == null)
            {
                throw new ArgumentNullException(nameof(latest));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            logger.Info($"Constructing file tailer for {file.FullName}");

            var lines = new SourceCache <Line, LineKey>(l => l.Key);

            Lines = lines.AsObservableCache();

            var locker = new object();

            scrollRequest = scrollRequest.Synchronize(locker);


            var aggregator = latest.CombineLatest(scrollRequest, (currentLines, scroll) => currentLines.ReadLines(scroll).ToArray())
                             .RetryWithBackOff <Line[], Exception>((ex, i) => TimeSpan.FromSeconds(1))
                             .Subscribe(currentPage =>
            {
                var previous = lines.Items.ToArray();
                var added    = currentPage.Except(previous, Line.TextStartComparer).ToArray();
                var removed  = previous.Except(currentPage, Line.TextStartComparer).ToArray();

                lines.Edit(innerCache =>
                {
                    if (removed.Any())
                    {
                        innerCache.Remove(removed);
                    }
                    if (added.Any())
                    {
                        innerCache.AddOrUpdate(added);
                    }
                });
            });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
        public void ImageExplorerViewModel_SyncsIntialItemsFromCache_WhenItemsAvailable() =>
        new TestScheduler().With(scheduler =>
        {
            var source = new SourceCache <ImageHandle, string>(x => x.LoadingSettings.FilePath);
            source.AddOrUpdate(GetDummyHandle("foo"));

            var sut = new ImageExplorerViewModel(source.AsObservableCache());
            sut.Activator.Activate();

            scheduler.AdvanceBy(2);

            Assert.Equal(1, sut.Children.Count);
        });
Exemplo n.º 9
0
 public VendingMachine(IVendingMachineManager manager, Currency currency, uint maxCapacityPerProduct)
 {
     ProfitHelper = this.WhenAnyValue(x => x.Income, x => x.Expenses, (income, expenses) => income - expenses).ToProperty(source: this, property: x => x.Profit);
     StockStatus.SubscribeMany((_) => UpdateProfitExcludingCurrentStockOutlaySubscriptionFactory());
     this.ObservableForProperty(x => x.Profit).Subscribe(x => UpdateProfitExcludingCurrentStockOutlay());
     Currency = currency;
     MaxCapacityPerProduct = maxCapacityPerProduct;
     this.manager          = manager;
     //No need to worry about null because of C# 8.0.
     //   (It would be caught at compile-time)
     //To have IVendingMachineOperator be nullable,
     //I'd have to declare it as IVendingMachineOperator?
     this.manager.SetupVendingMachine(_stock.AsObservableCache()).Subscribe(StockProduct);
 }
Exemplo n.º 10
0
        public PriceService()
        {
            _availableEntitiesCache = new SourceCache <IPrice, String>(price => price.EntityCacheKey);
            _availableEntities      = _availableEntitiesCache.AsObservableCache();

            TestHelper.Assets.ForEach(asset => _availableEntitiesCache.AddOrUpdate(new Price(DateTime.Now.Ticks, asset, asset.StartingPrice)));

            Observable
            .Interval(TimeSpan.FromMilliseconds(500))
            .Subscribe((_) =>
            {
                var price = CreatePrice();
                _availableEntitiesCache.AddOrUpdate(price);
            });
        }
Exemplo n.º 11
0
        public LineScroller([NotNull] IObservable<ILineProvider> latest, [NotNull] IObservable<ScrollRequest> scrollRequest)
        {
            if (latest == null) throw new ArgumentNullException(nameof(latest));
            if (scrollRequest == null) throw new ArgumentNullException(nameof(scrollRequest));


            var lines = new SourceCache<Line, LineKey>(l => l.Key);
            Lines = lines.AsObservableCache();

            var locker = new object();

            scrollRequest = scrollRequest.Synchronize(locker);
            latest = latest.Synchronize(locker);

            var aggregator = latest
                .CombineLatest(scrollRequest, (currentLines, scroll) =>
                {
                    try
                    {
                        var x = currentLines.ReadLines(scroll).ToArray();
                        return x;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                })
                .Subscribe(currentPage =>
                {

                    var previous = lines.Items.ToArray();
                    var added = currentPage.Except(previous, Line.TextStartComparer).ToArray();
                    var removed = previous.Except(currentPage, Line.TextStartComparer).ToArray();


                    lines.Edit(innerCache =>
                    {
                        if (removed.Any()) innerCache.Remove(removed);
                        if (added.Any()) innerCache.AddOrUpdate(added);
                    });
                });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
        public void ImageExplorerViewModel_SelectionsObservableFires_WhenNewItemSelected() =>
        new TestScheduler().With(scheduler =>
        {
            bool success = false;

            var source = new SourceCache <ImageHandle, string>(x => x.LoadingSettings.FilePath);
            source.AddOrUpdate(GetDummyHandle("foo"));
            source.AddOrUpdate(GetDummyHandle("bar"));

            var sut = new ImageExplorerViewModel(source.AsObservableCache());
            sut.Activator.Activate();
            scheduler.AdvanceBy(2);
            sut.Selections.Where(x => x.LoadingSettings.FilePath == "bar").Subscribe(_ => success = true);
            sut.SelectNext.Execute().Subscribe();
            scheduler.AdvanceBy(2);

            Assert.True(success);
        });
        public void ImageExplorerViewModel_SelectNextSelectsNextItem_WhenAtLeastTwoItemsAvailable() =>
        new TestScheduler().With(scheduler =>
        {
            var source = new SourceCache <ImageHandle, string>(x => x.LoadingSettings.FilePath);
            source.AddOrUpdate(GetDummyHandle("foo"));
            source.AddOrUpdate(GetDummyHandle("bar"));

            var sut = new ImageExplorerViewModel(source.AsObservableCache());
            sut.Activator.Activate();
            scheduler.AdvanceBy(2);

            Assert.Equal("foo", sut.SelectedItem.ExplorerItem.FilePath);

            sut.SelectNext.Execute().Subscribe();
            scheduler.AdvanceBy(1);

            Assert.Equal("bar", sut.SelectedItem.ExplorerItem.FilePath);
        });
Exemplo n.º 14
0
        public UwpAccesibleFolders()
        {
            source  = new SourceCache <Folder, string>(x => x.Token);
            Folders = source.AsObservableCache();

            var folders = StorageApplicationPermissions.FutureAccessList.Entries.Select(x => new { x.Token, x.Metadata });

            var enumerable = folders.Select(x => new Folder(x.Token, x.Metadata));

            source.AddOrUpdate(enumerable);

            picker = new FolderPicker
            {
                CommitButtonText       = "Select",
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            picker.FileTypeFilter.Add("*");
        }
Exemplo n.º 15
0
        public LineScroller([NotNull] IObservable<ILineProvider> latest, [NotNull] IObservable<ScrollRequest> scrollRequest)
        {
            if (latest == null) throw new ArgumentNullException(nameof(latest));
            if (scrollRequest == null) throw new ArgumentNullException(nameof(scrollRequest));

            var lines = new SourceCache<Line, LineKey>(l => l.Key);
            Lines = lines.AsObservableCache();

            var locker = new object();

            scrollRequest = scrollRequest.Synchronize(locker);
            latest = latest.Synchronize(locker);

            var aggregator = latest
                .CombineLatest(scrollRequest, (currentLines, scroll) => new { currentLines, scroll})
                .Sample(TimeSpan.FromMilliseconds(50))
                .Select(x =>
                {
                    if (x.scroll.PageSize == 0 || x.currentLines.Count == 0)
                        return new Line[0];

                    return x.currentLines.ReadLines(x.scroll).ToArray();
                })
                .Subscribe(currentPage =>
                {
                    var previous = lines.Items.ToArray();
                    var added = currentPage.Except(previous, Line.TextStartComparer).ToArray();
                    var removed = previous.Except(currentPage, Line.TextStartComparer).ToArray();

                    lines.Edit(innerCache =>
                    {
                        if (removed.Any()) innerCache.Remove(removed);
                        if (added.Any()) innerCache.AddOrUpdate(added);
                    });
                });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
Exemplo n.º 16
0
        public NeuronGraphPaneViewModel(INeuronService neuronService = null)
        {
            this.neuronService = neuronService ?? Locator.Current.GetService <INeuronService>();

            bool DefaultPredicate(Node <NeuronDto, int> node) => node.IsRoot;

            var cache = new SourceCache <NeuronDto, int>(x => x.Id);

            this.AddCommand = ReactiveCommand.Create(() =>
                                                     this.neuronService.Add(cache, NeuronService.CreateNeuron("Root Neuron", ChildType.NotSet)));
            this.ReloadCommand = ReactiveCommand.Create(() => {
                cache.Clear();
                this.neuronService.Reload(cache);
            });
            this.cleanUp = cache.AsObservableCache().Connect()
                           .TransformToTree(child => child.ParentId, Observable.Return((Func <Node <NeuronDto, int>, bool>)DefaultPredicate))
                           .Transform(e =>
                                      e.Item.Type == ChildType.Postsynaptic ?
                                      (NeuronViewModelBase)(new PostsynapticViewModel(e.Item.Data, e, cache)) :
                                      (NeuronViewModelBase)(new PresynapticViewModel(e.Item.Data, e, cache)))
                           .Bind(out this.children)
                           .DisposeMany()
                           .Subscribe();
        }
Exemplo n.º 17
0
        public MailBoxViewModel(IProfileDataQueryFactory queryFactory, IMailService mailService)
        {
            _queryFactory = queryFactory;
            _mailService  = mailService;
            _mailFolderSelectionViewModel = new MailFolderSelectionViewModel(_sourceFolders.AsObservableCache());

            var folderChanges = _sourceFolders.Connect(f => f.Type != FolderType.Root)
                                .ObserveOn(RxApp.TaskpoolScheduler)
                                .Sort(SortExpressionComparer <MailFolder> .Ascending(f => f.Type).ThenByAscending(f => f.Name))
                                .TransformToTree(f => f.ParentId)
                                .Transform(n => new MailFolderViewModel(n, this, queryFactory, mailService))
                                .DisposeMany()
                                .Publish();

            folderChanges
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out _allFolders)
            .Subscribe()
            .DisposeWith(_disposables);
            folderChanges
            .Filter(f => f.IsFavorite)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out _favoriteFolders)
            .Subscribe()
            .DisposeWith(_disposables);
            folderChanges.Connect()
            .DisposeWith(_disposables);

            var folderCollection = folderChanges
                                   .ToCollection()
                                   .Publish();

            folderCollection
            .Select(folders => folders.FirstOrDefault(f => f.Type == FolderType.Inbox))
            .ObserveOn(RxApp.MainThreadScheduler)
            .ToPropertyEx(this, x => x.Inbox)
            .DisposeWith(_disposables);
            folderCollection.Connect()
            .DisposeWith(_disposables);

            _mailService.FolderChanges
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(changes =>
            {
                _sourceFolders.Edit(updater =>
                {
                    foreach (var c in changes)
                    {
                        switch (c.State)
                        {
                        case DeltaState.Add:
                        case DeltaState.Update:
                            updater.AddOrUpdate(c.Entity);
                            break;

                        case DeltaState.Remove:
                            updater.RemoveKey(c.Entity.Id);
                            break;
                        }
                    }
                });
            })
            .DisposeWith(_disposables);

            Synchronize = ReactiveCommand.CreateFromTask(_mailService.SynchronizeFoldersAsync);
            //Synchronize.WithLatestFrom(folderCollection, (_, folders) => folders.Where(f => f.IsFavorite))
            //    .Subscribe(favoriteFolders =>
            //    {
            //        foreach (var f in favoriteFolders)
            //        {
            //            f.Synchronize.Execute().Subscribe();
            //        }
            //    })
            //    .DisposeWith(_disposables);
            Synchronize.ThrownExceptions
            .Subscribe(ex => this.Log().Error(ex))
            .DisposeWith(_disposables);
            Synchronize.IsExecuting
            .ToPropertyEx(this, x => x.IsSynchronizing)
            .DisposeWith(_disposables);
        }
Exemplo n.º 18
0
 public IObservableCache <TAggregate, TKey> OnItemChanged()
 {
     return(_sourceCache.AsObservableCache());
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageEditorViewModel" /> class.
        /// </summary>
        /// <param name="imageService">Service for image loading and manipulation.</param>
        public ImageEditorViewModel(IImageService imageService = null)
        {
            _imageService = imageService ?? Locator.Current.GetService <IImageService>();

            IObservable <ImageHandle> selectionChanges = this.WhenAnyValue(x => x.SelectedImage).Publish().RefCount();

            ImageExplorer = new ImageExplorerViewModel(_source.AsObservableCache());
            ImagePreview  = new ImagePreviewViewModel(selectionChanges);
            Settings      = new ImageSettingsViewModel(selectionChanges);

            SelectFolder = new Interaction <string, string>();

            LoadImage         = ReactiveCommand.CreateFromObservable <string, ImageHandle>(x => _imageService.LoadImage(x));
            ExportSelected    = ReactiveCommand.CreateFromObservable(ExportSelectedImpl);
            ExportAll         = ReactiveCommand.CreateFromObservable(ExportAllImpl);
            _calculatePreview = ReactiveCommand.CreateFromObservable <ImageHandle, ImageHandle>(x => _imageService.CalculatePreview(x));

            var connection = _source.Connect();

            this.WhenActivated(d =>
            {
                // Dispose handles removed from the source collection
                connection
                .DisposeMany()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Bind(out _images)
                .Subscribe()
                .DisposeWith(d);

                // Recaluclate image when quality changes
                connection.WhenPropertyChanged(x => x.ManipulationState.Quality, false)
                .Throttle(TimeSpan.FromMilliseconds(50))
                .Select(x => x.Sender)
                .InvokeCommand(_calculatePreview)
                .DisposeWith(d);

                // Notify about successful export.
                ExportSelected
                .Do(name => this.Notify().PublishInfo($"Image export to {name}", "Export completed!", TimeSpan.FromSeconds(3)))
                .Subscribe()
                .DisposeWith(d);

                // Notify about successful export.
                ExportAll
                .Do(path => this.Notify().PublishInfo($"All images exported to {path}", "Export completed!", TimeSpan.FromSeconds(3)))
                .Subscribe()
                .DisposeWith(d);

                // Add loaded images to source
                LoadImage
                .ObserveOn(RxApp.TaskpoolScheduler)
                .Where(x => x != null)
                .SelectMany(x => _calculatePreview.Execute(x))
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(handle => _source.AddOrUpdate(handle))
                .DisposeWith(d);

                // Show image loading error
                LoadImage.ThrownExceptions
                .OfType <ImageLoadingException>()
                .Subscribe(ex => this.Notify()
                           .PublishError($"Sorry. \"{ex.FilePath}\" does not have a supported file format.", "Error", TimeSpan.FromSeconds(5)))
                .DisposeWith(d);

                // Pipe loadings to property
                Observable.CombineLatest(
                    LoadImage.IsExecuting,
                    ExportSelected.IsExecuting,
                    ExportAll.IsExecuting,
                    _calculatePreview.IsExecuting,
                    (a, b, c, d) => a || b || c || d)
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.IsLoading)
                .DisposeWith(d);

                // React on close requests from explorer view
                this.WhenAnyObservable(x => x.ImageExplorer.DeletionRequests)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(x => _source.Remove(x))
                .DisposeWith(d);

                // Select explorer item
                this.WhenAnyObservable(x => x.ImageExplorer.Selections)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(x => SelectedImage = x)
                .DisposeWith(d);
            });
        }