Example #1
0
		public SourcesHandler (string gconf_key, Type container_type, EvolutionDataServerQueryable queryable, string fingerprint, params object[] ctor_args)
		{
			this.container_type = container_type;
			this.queryable = queryable;
			this.fingerprint = fingerprint;
			this.ctor_args = ctor_args;

			// This is the first code to hit e-d-s, so we might
			// get a DllNotFoundException exception if things
			// aren't configured correctly.  However, since
			// we're instantiating an object, it might be
			// wrapped in a TypeInitializationException, so
			// catch that and rethrow the inner exception.
			try {
				this.source_list = new SourceList (gconf_key);
			} catch (TypeInitializationException ex) {
				throw ex.InnerException;
			}

			if (this.source_list == null) {
				// FIXME: We may want to watch for the creation
				// of the sources GConf key
				Logger.Log.Info ("No sources found at {0}", gconf_key);
				return;
			}

			this.source_list.GroupAdded += OnGroupAdded;
			this.source_list.GroupRemoved += OnGroupRemoved;

			foreach (SourceGroup group in this.source_list.Groups)
				IndexSourceGroup (group, false);
		}
Example #2
0
        public void ListPerformance(int n)
        {
            var list = new SourceList<int>();
            int calculated = 0;

            var sw = Stopwatch.StartNew();

            var summation = list.Connect()
                .Sum(i => i)
                .Subscribe(result => calculated = result);
            
            //1. this is very slow if there are loads of updates (each updates causes a new summation)
            for (int i = 1; i < n; i++)
                list.Add(i);

            //2. very fast doing this (whole range is 1 update and 1 calculation):
            //list.AddRange(Enumerable.Range(0, n));
            sw.Stop();

            summation.Dispose();
            list.Dispose();

            Console.WriteLine("Total items: {0}. Value = {1}", n, calculated);
            Console.WriteLine("List: {0} updates took {1} ms {2:F3} ms each. {3}", n, sw.ElapsedMilliseconds, sw.Elapsed.TotalMilliseconds / n, DateTime.Now.ToShortDateString());

        }
        public AggregationViewModel()
        {
            var sourceList = new SourceList<AggregationItem>();

            sourceList.AddRange(Enumerable.Range(1, 15).Select(i => new AggregationItem(i)));

            //Load items to display to user and allow them to include items or not
         
            var listLoader = sourceList.Connect()
                .Sort(SortExpressionComparer<AggregationItem>.Ascending(vm => vm.Number))
                .ObserveOnDispatcher()
                .Bind(out _items)
                .Subscribe();

            // share the connection because we are doing multiple aggregations
            var aggregatable = sourceList.Connect()
                .FilterOnProperty(vm => vm.IncludeInTotal, vm => vm.IncludeInTotal)
                .Publish();

            //Do a custom aggregation (ToCollection() produces a readonly collection of underlying data)
            var sumOfOddNumbers = aggregatable.ToCollection()
                .Select(collection => collection.Where(i => i.Number%2 == 1).Select(ai => ai.Number).Sum())
                .Subscribe(sum => SumOfOddNumbers = sum);
            
            _cleanUp = new CompositeDisposable(sourceList, 
                listLoader,
                aggregatable.Count().Subscribe(count => Count = count),
                aggregatable.Sum(ai => ai.Number).Subscribe(sum => Sum = sum),
                aggregatable.Avg(ai => ai.Number).Subscribe(average => Avg = Math.Round(average,2)),
                aggregatable.Minimum(ai => ai.Number).Subscribe(max => Max = max),
                aggregatable.Maximum(ai => ai.Number).Subscribe(min => Min = min),
                aggregatable.StdDev(ai => ai.Number).Subscribe(std => StdDev = Math.Round(std, 2)),
                sumOfOddNumbers,
                aggregatable.Connect());
        }
        public EndpointsViewModel()
        {
            sourceEndpoints = new SourceList<Endpoint>();

            var filter = Observable.Return("")
                .Concat(this.ChangedProperty<string>(nameof(Search)).Select(pc => pc.After))
                //.Throttle(TimeSpan.FromMilliseconds(500))
                .Select(BuildFilter);

            sourceEndpoints.Connect()
                .Filter(filter)
                .Sort(SortExpressionComparer<Endpoint>.Ascending(e => e.Name))
                .ObserveOnUI()
                .Bind(out endpoints)
                .Subscribe();

            ServiceControl.Instance.Endpoints()
                .SubscribeOnBackground()
                .Subscribe(es =>
                {
                    sourceEndpoints.Edit(inner =>
                    {
                        inner.Clear();
                        inner.AddRange(es.DeserializeCollection<Endpoint>());
                    });
                });
        }
Example #5
0
        public ArrayList GetContacts(string bookName)
        {
            string contact_fax = null;
            ArrayList ebooks = new ArrayList();
            ArrayList records = new ArrayList();

            SourceList slist = new SourceList ("/apps/evolution/addressbook/sources");
            if (slist != null) {
                SList group_list = slist.Groups;
                foreach (SourceGroup group in group_list) {
                    //Only get phone books on this machine.
                    if (group.Name == "On This Computer") {
                        SList src_list = group.Sources;

                        foreach (Evolution.Source src in src_list) {
                            if (src.Name == bookName) {
                                //Book bk = Book.NewSystemAddressbook ();
                                Book bk = new Book(src);
                                bk.Open (true);

                                BookQuery q = BookQuery.AnyFieldContains ("");
                                Contact[] contactlist = bk.GetContacts (q);
                                //Console.WriteLine ("Contact count (range) : {0}", contactlist.Length);

                                if (contactlist != null) {

                                    foreach (Contact comp in contactlist) {
                                        contact_fax = null;

                                        if (comp.BusinessFax != null && comp.BusinessFax != String.Empty) {
                                            contact_fax = comp.BusinessFax;
                                        }
                                        else if (comp.OtherFax != null && comp.OtherFax != String.Empty) {
                                            contact_fax = comp.OtherFax;
                                        }
                                        else if (comp.HomeFax != null && comp.HomeFax != String.Empty) {
                                            contact_fax = comp.HomeFax;
                                        }

                                        if (contact_fax != null) {
                                            GfaxContact gc = new GfaxContact();
                                            //Console.WriteLine ("Id: {0}", comp.Id);
                                            gc.PhoneNumber = contact_fax;
                                            gc.ContactPerson = comp.FullName;
                                            gc.Organization = comp.Org;
                                            records.Add(gc);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return records;
        }
        public override void Load()
        {
            try {
                UpstreamSourceList = new MoblinSourceRpmList ();
                UpstreamSourceList.Load ();
            } catch {
                Console.WriteLine ("Could not fetch upstream source data");
            }

            LoadPackages ();
            // LoadSubmitRequests ();
        }
Example #7
0
        public Project()
        {
            //NOP
            sources = new SourceList();

            layers = new BuildLayerList();
            targets = new BuildTargetList();
            terrains = new TerrainList();

            graphs = new FilterGraphList();
            resources = new ResourceList();
            scripts = new ScriptList();
            mogreLocations = new List<MogreLocation>();
        }
        public void SkipInitialDoesNotReturnTheFirstBatchOfData()
        {
            bool updateReceived = false;

            var cache = new SourceList<Person>();


            var deferStream = cache.Connect().SkipInitial()
                                .Subscribe(changes => updateReceived = true);

            Assert.IsFalse(updateReceived, "No update should be received");

            cache.Add(new Person("P1", 1));

            Assert.IsFalse(updateReceived, "No update should be received for initial batch of changes");

            cache.Add(new Person("P2", 2));
            Assert.IsTrue(updateReceived, "Replace should be received");
            deferStream.Dispose();
        }
        public void MergeManyShouldWork()
        {
            var a = new SourceList<int>();
            var b = new SourceList<int>();
            var c = new SourceList<int>();

            var parent = new SourceList<SourceList<int>>();
            parent.Add(a);
            parent.Add(b);
            parent.Add(c);

            var d = parent.Connect()
                .MergeMany(e => e.Connect().RemoveIndex())
                .AsObservableList();

            Assert.AreEqual(d.Count,0); 

            a.Add(1);

            Assert.AreEqual(d.Count, 1);
            a.Add(2);
            Assert.AreEqual(d.Count, 2);

            b.Add(3);
            Assert.AreEqual(d.Count, 3);
            b.Add(5);
            Assert.AreEqual(d.Count, 4);
            CollectionAssert.AreEquivalent(d.Items, new[] { 1, 2, 3, 5 });


            b.Clear();

            // Fails below
            Assert.AreEqual(d.Count,2);
            CollectionAssert.AreEquivalent(d.Items, new[] { 1, 2});


        }
        public void DeferUntilLoadedDoesNothingUntilDataHasBeenReceived()
        {
            bool updateReceived = false;
            IChangeSet<Person> result = null;

            var cache = new SourceList<Person>();


            var deferStream = cache.Connect().DeferUntilLoaded()
                                .Subscribe(changes =>
                                           {
                                               updateReceived = true;
                                               result = changes;
                                           });

            Assert.IsFalse(updateReceived,"No update should be received");
            cache.Add(new Person("Test",1));

            Assert.IsTrue(updateReceived,"Replace should be received");
            Assert.AreEqual(1,result.Adds);
            Assert.AreEqual(new Person("Test",1), result.First().Item.Current);
            deferStream.Dispose();
        }
Example #11
0
        private void ListenForGroups()
        {
            Logger.Debug ("Listening for Changes in EDS Task Groups ");
               SourceList slist = new SourceList ("/apps/evolution/tasks/sources");

               if (slist == null)
                   Logger.Debug ("Unable to find sources");

               slist.GroupAdded += OnGroupAdded;
               slist.GroupRemoved += OnGroupRemoved;

               foreach (SourceGroup group in slist.Groups) {
                   ListenForSources (group);
               }
        }
Example #12
0
        /// <summary>
        /// Convert an observable collection into an observable change set
        /// </summary>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <typeparam name="TCollection"></typeparam>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">source</exception>
        public static IObservable <IChangeSet <T> > ToObservableChangeSet <TCollection, T>(this TCollection source)
            where TCollection : INotifyCollectionChanged, IEnumerable <T>
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            return(Observable.Create <IChangeSet <T> >
                   (
                       observer =>
            {
                var locker = new object();

                ChangeSet <T> InitialChangeSet()
                {
                    var initial = new Change <T>(ListChangeReason.AddRange, source.ToList());
                    return new ChangeSet <T>()
                    {
                        initial
                    };
                }

                //populate local cache, otherwise there is no way to deal with a reset
                var cloneOfList = new SourceList <T>();

                var sourceUpdates = Observable
                                    .FromEventPattern <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
                    h => source.CollectionChanged += h,
                    h => source.CollectionChanged -= h)
                                    .Select
                                    (
                    args =>
                {
                    var changes = args.EventArgs;

                    switch (changes.Action)
                    {
                    case NotifyCollectionChangedAction.Add:
                        return changes.NewItems.OfType <T>()
                        .Select((t, index) => new Change <T>(ListChangeReason.Add, t, index + changes.NewStartingIndex));

                    case NotifyCollectionChangedAction.Remove:
                        return changes.OldItems.OfType <T>()
                        .Select((t, index) => new Change <T>(ListChangeReason.Remove, t, index + changes.OldStartingIndex));

                    case NotifyCollectionChangedAction.Replace:
                        return changes.NewItems.OfType <T>()
                        .Select((t, idx) =>
                        {
                            var old = changes.OldItems[idx];
                            return new Change <T>(ListChangeReason.Replace, t, (T)old, idx + changes.NewStartingIndex, +changes.NewStartingIndex);
                        });

                    case NotifyCollectionChangedAction.Reset:
                        var cleared = new Change <T>(ListChangeReason.Clear, cloneOfList.Items.ToList(), 0);
                        var clearedChangeSet = new ChangeSet <T>()
                        {
                            cleared
                        };
                        return clearedChangeSet.Concat(InitialChangeSet());

                    case NotifyCollectionChangedAction.Move:
                        var item = changes.NewItems.OfType <T>().First();
                        var change = new Change <T>(item, changes.NewStartingIndex, changes.OldStartingIndex);
                        return new[] { change };

                    default:
                        return null;
                    }
                })
                                    .Where(updates => updates != null)
                                    .Select(updates => (IChangeSet <T>) new ChangeSet <T>(updates));

                var cacheLoader = Observable.Defer(() => Observable.Return(InitialChangeSet()))
                                  .Concat(sourceUpdates)
                                  .PopulateInto(cloneOfList);

                var subscriber = cloneOfList.Connect().SubscribeSafe(observer);
                return new CompositeDisposable(cacheLoader, subscriber, cloneOfList);
            }));
        }
Example #13
0
        public AppConfig(IShell sh, ILogger l)
        {
            shell = sh;
            log   = l;

            appConfigPath = GetRomaingPath("kamban.config");
            FileInfo file = new FileInfo(appConfigPath);

            if (file.Exists)
            {
                string data = File.ReadAllText(appConfigPath);

                try
                {
                    appConfigJson = JsonConvert.DeserializeObject <AppConfigJson>(data);
                }
                catch { }
            }

            // file not exists or deserialize error
            if (appConfigJson == null)
            {
                appConfigJson = new AppConfigJson();
            }

            if (string.IsNullOrEmpty(appConfigJson.AppGuid))
            {
                appConfigJson.AppGuid = Guid.NewGuid().ToString();
            }

            if (string.IsNullOrEmpty(appConfigJson.ColorTheme))
            {
                appConfigJson.ColorTheme = Colors.White.ToString();
            }

            OpenLatestAtStartupValue = appConfigJson.OpenLatestAtStartup;
            ShowFileNameInTabValue   = appConfigJson.ShowFileNameInTab;
            ColorThemeValue          = ToColor(appConfigJson.ColorTheme);

            appConfigJson.StartNumber++;
            SaveConfig();

            recentList = new SourceList <RecentViewModel>();
            recentList.AddRange(appConfigJson.Feed.Select(x => new RecentViewModel
            {
                Uri = x.Uri, LastAccess = x.LastAccess, Pinned = x.Pinned
            }));

            RecentObservable = recentList.Connect().AutoRefresh();

            publicBoards = new SourceList <PublicBoardJson>();
            publicBoards
            .Connect()
            .Bind(out ReadOnlyObservableCollection <PublicBoardJson> temp)
            .Subscribe();

            PublicBoards = temp;

            GetStarted = this.WhenAnyValue(x => x.GetStartedValue);
            Basement   = this.WhenAnyValue(x => x.BasementValue);
            OpenLatestAtStartupObservable = this.WhenAnyValue(x => x.OpenLatestAtStartupValue);
            ShowFileNameInTabObservable   = this.WhenAnyValue(x => x.ShowFileNameInTabValue);
            ColorThemeObservable          = this.WhenAnyValue(x => x.ColorThemeValue);
            // Manage current opened boards for raise on next startup

            shell.DockingManager.ActiveContentChanged += (s, e) =>
            {
                var view = shell.DockingManager.ActiveContent as BoardView;
                if (view == null)
                {
                    return;
                }
                var vm = view.ViewModel as BoardEditViewModel;
                if (vm.Box == null)
                {
                    return;
                }
                if (!appConfigJson.LatestOpenedAtStartup.Contains(vm.Box.Uri))
                {
                    appConfigJson.LatestOpenedAtStartup.Add(vm.Box.Uri);
                }
                SaveConfig();
            };

            shell.DockingManager.DocumentClosed += (s, e) =>
            {
                var view = e.Document.Content as BoardView;
                if (view == null)
                {
                    return;
                }

                var vm = view.ViewModel as BoardEditViewModel;
                appConfigJson.LatestOpenedAtStartup.Remove(vm.Box.Uri);
                SaveConfig();
            };
        }
        public TaskEditorViewModel(ICachedService service, IMapper mapper, IShell shell)
        {
            cachedService = service;
            this.mapper   = mapper;
            validator     = new TaskEditorValidator();
            IsValid       = true;
            Shell         = shell as CachedServiceShell;

            taskParameters   = new SourceList <TaskParameter>();
            bindedOpers      = new SourceList <DesktopOperation>();
            incomingPackages = new SourceList <string>();

            DataImporters       = cachedService.DataImporters;
            DataExporters       = cachedService.DataExporters;
            implementationTypes = new SourceList <string>();

            var canSave = this.WhenAnyValue(tvm => tvm.IsDirty, tvm => tvm.IsValid,
                                            (isd, isv) => isd && isv).Concat(Shell.CanEdit);

            SaveChangesCommand = ReactiveCommand.CreateFromTask(async() => await Save(),
                                                                canSave);

            CancelCommand = ReactiveCommand.CreateFromTask(Cancel);

            ClipBoardFillCommand = ReactiveCommand.Create <string>(Clipboard.SetText);

            OpenCurrentTaskViewCommand = ReactiveCommand //todo: make without interface blocking
                                         .CreateFromTask(async() =>
                                                         cachedService.OpenPageInBrowser(
                                                             await cachedService.GetCurrentTaskViewById(Id)));

            RemoveOperationCommand = ReactiveCommand.Create <DesktopOperation>(to =>
            {
                if (SelectedOperation?.Id == to.Id)
                {
                    ClearSelections();
                }
                bindedOpers.Remove(to);
            }, Shell.CanEdit);

            RemoveParameterCommand = ReactiveCommand
                                     .Create <TaskParameter>(par => taskParameters.Remove(par), Shell.CanEdit);

            AddParameterCommand = ReactiveCommand.Create(() => taskParameters.Add(new TaskParameter
            {
                Name = "@RepPar"
            }), Shell.CanEdit);

            AddOperationCommand = ReactiveCommand.CreateFromTask(AddOperation, Shell.CanEdit);


            CreateOperConfigCommand = ReactiveCommand.CreateFromTask(CreateOperConfig, Shell.CanEdit);

            OpenTemplatesListCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                if (SelectedOperationConfig != null && Shell.Role == ServiceUserRole.Editor)
                {
                    if (!await Shell.ShowWarningAffirmativeDialogAsync
                            ("All unsaved operation configuration changes will be lost. Close window?"))
                    {
                        return;
                    }
                }

                await SelectOperFromTemplates();
            }, Shell.CanEdit);

            SelectOperationCommand = ReactiveCommand.CreateFromTask <DesktopOperation>
                                         (SelectOperation);

            this.ObservableForProperty(s => s.Mode)
            .Subscribe(mode =>
            {
                var templates = mode?.Value == OperMode.Exporter
                        ? DataExporters.Select(pair => pair.Key)
                        : DataImporters.Select(pair => pair.Key);

                implementationTypes.ClearAndAddRange(templates);
                Type = implementationTypes.Items.FirstOrDefault();
            });

            this.ObservableForProperty(s => s.Type)
            .Where(type => type.Value != null)
            .Subscribe(type =>
            {
                var operType = Mode == OperMode.Exporter
                        ? DataExporters[type.Value]
                        : DataImporters[type.Value];
                if (operType == null)
                {
                    return;
                }

                SelectedOperationConfig = Activator.CreateInstance(operType);
                mapper.Map(cachedService, SelectedOperationConfig);
            });

            this.WhenAnyValue(tvm => tvm.SelectedOperationConfig)
            .Where(selop => selop != null)
            .Subscribe(conf =>
                       IncomingPackages = incomingPackages.SpawnCollection());
        }
Example #15
0
 // Assumes ownership of the 'children' and 'opTokens' array.
 public VariadicOpNode(ref int idNext, VariadicOp op, TexlNode[] children, Token[] opTokens, SourceList sourceList)
     : base(ref idNext, opTokens.VerifyValue().First(), sourceList, children)
 {
     Contracts.AssertNonEmpty(opTokens);
     Contracts.AssertAllValues(opTokens);
     Op       = op;
     OpTokens = opTokens;
 }
Example #16
0
 public void RemoveAt(int index)
 {
     SourceList.RemoveAt(index);
 }
Example #17
0
        public CoinListViewModel(Wallet wallet, bool canDequeueCoins = false, bool displayCommonOwnershipWarning = false)
        {
            Global = Locator.Current.GetService <Global>();

            AmountSortDirection = SortOrder.Decreasing;

            CoinJoinStatusWidth = new GridLength(0);
            Wallet          = wallet;
            CanDequeueCoins = canDequeueCoins;
            DisplayCommonOwnershipWarning = displayCommonOwnershipWarning;

            RefreshOrdering();

            // Otherwise they're all selected as null on load.
            SelectAllCheckBoxState        = false;
            SelectPrivateCheckBoxState    = false;
            SelectNonPrivateCheckBoxState = false;

            var sortChanged = this
                              .WhenAnyValue(x => x.MyComparer)
                              .ObserveOn(RxApp.MainThreadScheduler)
                              .Select(_ => MyComparer);

            RootList = new SourceList <CoinViewModel>();
            RootList
            .Connect()
            .Sort(MyComparer, comparerChanged: sortChanged, resetThreshold: 5)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out _coinViewModels)
            .Subscribe();

            SortCommand = ReactiveCommand.Create(RefreshOrdering);

            this.WhenAnyValue(x => x.AmountSortDirection)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x =>
            {
                if (x != SortOrder.None)
                {
                    PrivacySortDirection  = SortOrder.None;
                    StatusSortDirection   = SortOrder.None;
                    ClustersSortDirection = SortOrder.None;
                }
            });

            this.WhenAnyValue(x => x.ClustersSortDirection)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x =>
            {
                if (x != SortOrder.None)
                {
                    AmountSortDirection  = SortOrder.None;
                    StatusSortDirection  = SortOrder.None;
                    PrivacySortDirection = SortOrder.None;
                }
            });

            this.WhenAnyValue(x => x.StatusSortDirection)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x =>
            {
                if (x != SortOrder.None)
                {
                    AmountSortDirection   = SortOrder.None;
                    PrivacySortDirection  = SortOrder.None;
                    ClustersSortDirection = SortOrder.None;
                }
            });

            this.WhenAnyValue(x => x.PrivacySortDirection)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x =>
            {
                if (x != SortOrder.None)
                {
                    AmountSortDirection   = SortOrder.None;
                    StatusSortDirection   = SortOrder.None;
                    ClustersSortDirection = SortOrder.None;
                }
            });

            SelectAllCheckBoxCommand = ReactiveCommand.Create(() =>
            {
                switch (SelectAllCheckBoxState)
                {
                case true:
                    SelectCoins(x => true);
                    break;

                case null:
                case false:
                    SelectCoins(x => false);
                    SelectAllCheckBoxState = false;
                    break;
                }
            });

            SelectPrivateCheckBoxCommand = ReactiveCommand.Create(() =>
            {
                switch (SelectPrivateCheckBoxState)
                {
                case true:
                    SelectCoins(x => x.AnonymitySet >= Global.Config.MixUntilAnonymitySet);
                    break;

                case null:
                case false:
                    SelectCoins(x => false);
                    SelectPrivateCheckBoxState = false;
                    break;
                }
            });

            SelectNonPrivateCheckBoxCommand = ReactiveCommand.Create(() =>
            {
                switch (SelectNonPrivateCheckBoxState)
                {
                case true:
                    SelectCoins(x => x.AnonymitySet < Global.Config.MixUntilAnonymitySet);
                    break;

                case false:
                case null:
                    SelectCoins(x => false);
                    SelectNonPrivateCheckBoxState = false;
                    break;
                }
            });

            // This will be triggered after the Tab becomes visible for the user.
            InitList = ReactiveCommand.CreateFromTask(async() =>
            {
                IsCoinListLoading = true;              // Set the Loading animation.
                await Task.Delay(800);                 // Let the UI to be rendered to the user.
                OnOpen();
                CoinListShown?.Invoke(this, null);     // Trigger this event to refresh the list.
            });

            Observable
            .Merge(InitList.ThrownExceptions)
            .Merge(SelectNonPrivateCheckBoxCommand.ThrownExceptions)
            .Merge(SelectPrivateCheckBoxCommand.ThrownExceptions)
            .Merge(SelectAllCheckBoxCommand.ThrownExceptions)
            .Merge(SortCommand.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
Example #18
0
 public Talent(string name, string Discription, AptitudeName firstAptitude, AptitudeName secondAptitude, int tier, SourceList sourceBook, int sourcePage)
     : this(name, Discription, firstAptitude, secondAptitude, tier)
 {
     SourceBook = sourceBook;
     SourcePage = sourcePage;
 }
 private void UpdateList()
 {
     SelectedItems = new ObservableCollection <string>(SourceList.Where(i => i.IsChecked).Select(i => i.Name));
 }
        public StartupViewModel(IShell shell, ISourcesCacheProvider cacheProvider, IDockWindow window)
        {
            _shell         = shell;
            _cacheProvider = cacheProvider;
            _window        = window;

            var appConfigStorage = new AppConfigStorage();
            var config           = appConfigStorage.Load();

            Title = "App settings";

            // Title

            AppTitle = shell.Title;
            this.WhenAnyValue(x => x.AppTitle)
            .Subscribe(x => shell.Title = x);

            // Theme

            Accent = config.Accent ?? "Blue";
            IsDark = config.IsDark;
            UpdateTheme();

            this.ObservableForProperty(x => x.Accent)
            .Subscribe(x =>
            {
                config.Accent = x.Value;
                appConfigStorage.Save(config);
                UpdateTheme();
            });
            this.ObservableForProperty(x => x.IsDark)
            .Subscribe(x =>
            {
                config.IsDark = x.Value;
                appConfigStorage.Save(config);
                UpdateTheme();
            });

            // Server Urls

            var urls = config.ServerUrl?
                       .Split(';')
                       .Select(x => Uri.TryCreate(x, UriKind.Absolute, out var result) ? result : null as Uri)
                       .Where(x => x != null)
                       .ToArray();

            ServerUrlsSource = new SourceList <Uri>();
            if (urls != null)
            {
                ServerUrlsSource.AddRange(urls);
                ServerUrl = urls.First();
            }

            ServerUrlsSource
            .Connect()
            .ObserveOnDispatcher()
            .Bind(out _serverUrls)
            .ToCollection()
            .Subscribe(items =>
            {
                config.ServerUrl = string.Join(";", items);
                appConfigStorage.Save(config);
            });

            this.WhenAnyValue(x => x.ServerUrl)
            .Skip(1)
            .Subscribe(_ => UpdateSourcesCache());

            // Authorization Tokens

            var tokens = config.AuthToken?
                         .Split(';')
                         .Where(x => !string.IsNullOrEmpty(x))
                         .ToArray();

            AuthTokensSource = new SourceList <string>();
            if (tokens != null)
            {
                AuthTokensSource.AddRange(tokens);
                AuthToken = tokens.First();
            }

            AuthTokensSource
            .Connect()
            .ObserveOnDispatcher()
            .Bind(out _authTokens)
            .ToCollection()
            .Subscribe(items =>
            {
                config.AuthToken = string.Join(";", items);
                appConfigStorage.Save(config);
            });

            this.WhenAnyValue(x => x.AuthToken)
            .Skip(1)
            .Subscribe(_ => UpdateSourcesCache());

            // Create Commands

            var hasUrl = this.WhenAny(x => x.ServerUrl, x => x.Value != null);

            NewLogCommand       = CreateCommandWithInit(NewLog, hasUrl);
            NewKeepAliveCommand = CreateCommandWithInit(NewKeepAlive, hasUrl);
            NewMetricsCommand   = CreateCommandWithInit(NewMetrics, hasUrl);

            RemoveEntitiesCommand = CreateCommandWithInit(RemoveEntities, hasUrl);
            ManageGroupsCommand   = CreateCommandWithInit(ManageGroups, hasUrl);

            RemoveUrlCommand       = ReactiveCommand.Create <Uri>(url => ServerUrlsSource.Remove(url));
            RemoveAuthTokenCommand = ReactiveCommand.Create <string>(token => AuthTokensSource.Remove(token));

            RefreshCommand = ReactiveCommand.CreateFromTask(Refresh, hasUrl);

            UpdateSourcesCache();
        }
Example #21
0
        IObservable <Unit> SetupFilteringAnimals()
        {
            ReadOnlyObservableCollection <Animal> filteredAnimals;
            SourceList <Animal> animalList = Animal.CreateMeSomeAnimalsPlease();

            IObservable <Func <Animal, bool> > dynamicFilter =
                // ReactiveUI connecting to the DepedencyProperty
                this.WhenAnyValue(x => x.tbFilterText.Text)
                // Debounce
                .Throttle(TimeSpan.FromMilliseconds(250))
                .Select(CreatePredicate);

            IObservable <IComparer <Animal> > dynamicSort =
                this.WhenAnyValue(x => x.cbSortByName.IsChecked)
                .Select(x => x ?? false)
                .Select(isChecked => isChecked ?
                        SortExpressionComparer <Animal> .Ascending(i => i.Name)
                        : SortExpressionComparer <Animal> .Ascending(i => animalList.Items.IndexOf(i))
                        );

            var returnValue =
                animalList
                .Connect()
                .Filter(dynamicFilter)    // accepts any observable
                .Sort(dynamicSort)
                .ObserveOnDispatcher()
                // side effect
                .Bind(out filteredAnimals)
                .Publish();

            returnValue.Connect();


            // Create filtered source to watch for changes on
            var filteredAnimalsChanged =
                filteredAnimals
                .ToObservableChangeSet()
                .Publish()
                .RefCount();


            var calculateAverage =
                // Watch for property Changed events
                filteredAnimalsChanged
                .WhenPropertyChanged(x => x.AnimalRating).ToUnit()

                // watch for list changed
                .Merge(filteredAnimalsChanged.ToUnit())
                .Do(_ => UpdateAverage())
                .ToUnit();


            lvFilteredAnimals.ItemsSource = filteredAnimals;
            return(returnValue.ToUnit().Merge(calculateAverage));



            Func <Animal, bool> CreatePredicate(string text)
            {
                if (text == null || text.Length < 3)
                {
                    return(animal => true);
                }

                text = text.ToLower();
                return(animal => animal.Name.ToLower().Contains(text) ||
                       animal.Type.ToLower().Contains(text) ||
                       animal.Family.ToString().ToLower().Contains(text));
            }

            void UpdateAverage()
            {
                // There is a better way
                var filterBy = filteredAnimals.Where(x => x.AnimalRating > 0).ToArray();

                if (!filterBy.Any())
                {
                    tbAverageRating.Text = "Unknown";
                    return;
                }

                tbAverageRating.Text =
                    filterBy.Average(x => x.AnimalRating)
                    .ToString();
            }
        }
        public async Task TestFilterOnProperty()
        {
            var listA = new SourceList <X>();
            var listB = new SourceList <X>();

            using (IObservableList <X> list = listA.Connect()
                                              .Or(listB.Connect())
                                              .AsObservableList())
            {
                var nameA1 = "A1";
                var a1     = new X(nameA1);
                var a2     = new X("A2");
                listA.Edit(l =>
                {
                    l.Clear();
                    l.Add(a1);
                    l.Add(a2);
                });

                var b1 = new X("B1");
                var b2 = new X("B2");
                listB.Edit(l =>
                {
                    l.Clear();
                    l.Add(b1);
                    l.Add(b2);
                });

                Assert.AreEqual(4, list.Count);

                int count = await list.CountChanged.FirstAsync();

                Assert.AreEqual(4, count);

                IObservable <IChangeSet <X> > obsFiltered = list.Connect()
                                                            .FilterOnProperty(v => v.IsConnected, v => v.IsConnected);

                using (IObservableList <X> obsFilteredAsList = obsFiltered.AsObservableList())
                {
                    IObservable <IChangeSet <XVm> > obsTransformed = obsFiltered
                                                                     .Transform(v => new XVm(v))
                                                                     .DisposeMany();

                    var ctorCount = 0;
                    var dtorCount = 0;
                    using (IObservableList <XVm> obsTransformedAsList = obsTransformed.AsObservableList())
                    {
                        ctorCount += 4;

                        Assert.That(obsFilteredAsList.Items.Contains(a1));
                        Assert.That(obsFilteredAsList.Items.Count(), Is.EqualTo(obsTransformedAsList.Items.Count()));

                        a1.IsConnected = false;
                        Assert.That(obsFilteredAsList.Items, Has.No.Member(a1));
                        dtorCount++;
                        Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                        Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));

                        a1.IsConnected = true;
                        Assert.That(obsFilteredAsList.Items, Has.Member(a1));
                        ctorCount++;
                        Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                        Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));

                        //Console.WriteLine("--remove");
                        listA.Remove(a1);
                        dtorCount++;
                        Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                        Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));

                        //  Console.WriteLine("--add");
                        listA.Add(a1);
                        ctorCount++;
                        Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                        Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));

                        // Console.WriteLine("--clear");
                        listA.Clear();
                        dtorCount += 2; //FIX:  List A contains 2 items (was adding 4)
                        Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                        Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));

                        //   Console.WriteLine("--add");

                        //FIX: Maybe a debate required!  List B already contains b1, so not regarded as a new item in the Or result
                        Debug.Assert(listB.Items.Contains(b1));
                        listA.Add(b1);
                        //  ctorCount++;
                        Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                        Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));

                        //    Console.WriteLine("--disp");
                    }
                    dtorCount += 2; //FIX: Should be +3 s this is what
                    Assert.That(XVm.Constructed, Is.EqualTo(ctorCount));
                    Assert.That(XVm.Destructed, Is.EqualTo(dtorCount));
                }
            }
        }
 /// <summary>
 /// Inserts an item to the <see cref="AbstractTransformingList{TFrom, TTo}"/>
 /// at the specified index.
 /// </summary>
 /// <remarks>
 /// Reverse converts the <paramref name="item"/> to type
 /// <typeparamref name="TFrom"/> and insert the result data into the
 /// underlaying source list.
 /// </remarks>
 /// <param name="item">
 /// The object to insert into the list.</param>
 /// <param name="index">
 /// The zero-based index at which item should be inserted.</param>
 /// <exception cref="NotSupportedException">
 /// When the underlaying source list is read-only or the
 /// <see cref="Reverse"/> method throws this exception.</exception>
 /// <exception cref="ArgumentOutOfRangeException">
 /// index is not a valid index in the underlaying source list"/>.
 /// </exception>
 public override void Insert(int index, TTo item)
 {
     SourceList.Insert(index, Reverse(item));
 }
Example #24
0
 public void Insert(int index, TTarget item)
 {
     SourceList.Insert(index, Deconvert(item));
 }
 /// <summary>
 /// Adds an item to this list.
 /// </summary>
 /// <remarks>
 /// Converts the <paramref name="item"/> to <typeparamref name="TFrom"/>
 /// using the <see cref="Reverse"/> method. Then add converted
 /// item into the source list.
 /// </remarks>
 /// <param name="item">
 /// The object to add to the list.
 /// </param>
 /// <exception cref="NotSupportedException">
 /// The underlaying source list is read-only or the <see cref="Reverse"/>
 /// method throws this exception.
 /// </exception>
 public override void Add(TTo item)
 {
     SourceList.Add(Reverse(item));
 }
		public void SetUp()
		{
			_collection = new ObservableCollectionExtended<Person>();
			_source = new SourceList<Person>();
			_binder = _source.Connect().Bind(_collection).Subscribe();
		}
Example #27
0
 public BindingLIstBindListFixture()
 {
     _collection = new BindingList <Person>();
     _source     = new SourceList <Person>();
     _binder     = _source.Connect().Bind(_collection).Subscribe();
 }
 public BindFromObservableListFixture()
 {
     _collection = new ReactiveList <Person>();
     _source     = new SourceList <Person>();
     _binder     = _source.Connect().Bind(_collection).Subscribe();
 }
Example #29
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();

            // Populate Source List
            SourceList.Initialize();

            var TableViews = new SourceListItem("Table Based Views");

            TableViews.AddItem("Table View", "calendar.png", () => {
                DisplaySubview(new SubviewTableController(), SubviewType.TableView);
            });
            TableViews.AddItem("Outline View", "calendar.png", () => {
                DisplaySubview(new SubviewOutlineController(), SubviewType.OutlineView);
            });
            SourceList.AddItem(TableViews);

            var ImageViews = new SourceListItem("Photos");

            ImageViews.AddItem("First Person", "film-roll.png", () => {
                if (ViewType == SubviewType.ImageView)
                {
                    var Photo   = Subview as SubviewImage;
                    Photo.Image = NSImage.ImageNamed("person01.jpg");
                }
                else
                {
                    var Photo        = new SubviewImageController();
                    Photo.View.Image = NSImage.ImageNamed("person01.jpg");
                    DisplaySubview(Photo, SubviewType.ImageView);
                }
            });
            ImageViews.AddItem("Second Person", "film-roll.png", () => {
                if (ViewType == SubviewType.ImageView)
                {
                    var Photo   = Subview as SubviewImage;
                    Photo.Image = NSImage.ImageNamed("person02.jpg");
                }
                else
                {
                    var Photo        = new SubviewImageController();
                    Photo.View.Image = NSImage.ImageNamed("person02.jpg");
                    DisplaySubview(Photo, SubviewType.ImageView);
                }
            });
            ImageViews.AddItem("Third Person", "film-roll.png", () => {
                if (ViewType == SubviewType.ImageView)
                {
                    var Photo   = Subview as SubviewImage;
                    Photo.Image = NSImage.ImageNamed("person03.jpg");
                }
                else
                {
                    var Photo        = new SubviewImageController();
                    Photo.View.Image = NSImage.ImageNamed("person03.jpg");
                    DisplaySubview(Photo, SubviewType.ImageView);
                }
            });
            SourceList.AddItem(ImageViews);

            // Display Source List
            SourceList.ReloadData();
            SourceList.ExpandItem(null, true);
        }
Example #30
0
        public static IObservable <IChangeSet <T> > ToObservableChangeSet <T>(this ReadOnlyObservableCollection <T> source)
        {
            return(Observable.Create <IChangeSet <T> >
                   (
                       observer =>
            {
                Func <ChangeSet <T> > initialChangeSet = () =>
                {
                    var initial = new Change <T>(ListChangeReason.AddRange, source.ToList());
                    return new ChangeSet <T>()
                    {
                        initial
                    };
                };

                //populate local cache, otherwise there is no way to deal with a reset
                var cloneOfList = new SourceList <T>();

                var sourceUpdates = Observable
                                    .FromEventPattern <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
                    h => ((INotifyCollectionChanged)source).CollectionChanged += h,
                    h => ((INotifyCollectionChanged)source).CollectionChanged -= h)
                                    .Select
                                    (
                    args =>
                {
                    var changes = args.EventArgs;

                    switch (changes.Action)
                    {
                    case NotifyCollectionChangedAction.Add:
                        return changes.NewItems.OfType <T>()
                        .Select((t, index) => new Change <T>(ListChangeReason.Add, t, index + changes.NewStartingIndex));

                    case NotifyCollectionChangedAction.Remove:
                        return changes.OldItems.OfType <T>()
                        .Select((t, index) => new Change <T>(ListChangeReason.Remove, t, index + changes.OldStartingIndex));

                    case NotifyCollectionChangedAction.Replace:
                        {
                            return changes.NewItems.OfType <T>()
                            .Select((t, idx) =>
                            {
                                var old = changes.OldItems[idx];
                                return new Change <T>(ListChangeReason.Replace, t, (T)old, idx, idx);
                            });
                        }

                    case NotifyCollectionChangedAction.Reset:
                        {
                            var cleared = new Change <T>(ListChangeReason.Clear, cloneOfList.Items.ToList(), 0);
                            var clearedChangeSet = new ChangeSet <T>()
                            {
                                cleared
                            };
                            return clearedChangeSet.Concat(initialChangeSet());
                        }

                    case NotifyCollectionChangedAction.Move:
                        {
                            var item = changes.NewItems.OfType <T>().First();
                            var change = new Change <T>(item, changes.NewStartingIndex, changes.OldStartingIndex);
                            return new[] { change };
                        }

                    default:
                        return null;
                    }
                })
                                    .Where(updates => updates != null)
                                    .Select(updates => (IChangeSet <T>) new ChangeSet <T>(updates));

                var initialChanges = initialChangeSet();
                var cacheLoader = Observable.Return(initialChanges).Concat(sourceUpdates).PopulateInto(cloneOfList);
                var subscriber = cloneOfList.Connect().SubscribeSafe(observer);
                return new CompositeDisposable(cacheLoader, subscriber, cloneOfList);
            }));
        }
        private ProxyService()
        {
            mCurrent = this;

            ProxyDomains = new SourceList <AccelerateProjectGroupDTO>();
            ProxyScripts = new SourceList <ScriptDTO>();

            ProxyDomains
            .Connect()
            .ObserveOn(RxApp.MainThreadScheduler)
            .Sort(SortExpressionComparer <AccelerateProjectGroupDTO> .Ascending(x => x.Order).ThenBy(x => x.Name))
            .Bind(out _ProxyDomainsList)
            .Subscribe(_ => SelectGroup = ProxyDomains.Items.FirstOrDefault());


            this.WhenValueChanged(x => x.ProxyStatus, false)
            .Subscribe(async x =>
            {
                if (x)
                {
                    httpProxyService.ProxyDomains   = EnableProxyDomains;
                    httpProxyService.IsEnableScript = ProxySettings.IsEnableScript.Value;
                    httpProxyService.Scripts        = EnableProxyScripts;
                    if (IApplication.IsDesktopPlatform)
                    {
                        httpProxyService.IsOnlyWorkSteamBrowser = ProxySettings.IsOnlyWorkSteamBrowser.Value;
                        httpProxyService.IsSystemProxy          = ProxySettings.EnableWindowsProxy.Value;
                        httpProxyService.IsProxyGOG             = ProxySettings.IsProxyGOG.Value;
                    }
                    else
                    {
                        httpProxyService.IsSystemProxy = true;
                    }

                    // macOS 上目前因权限问题仅支持 0.0.0.0(IPAddress.Any)
                    httpProxyService.ProxyIp = (!OperatingSystem2.IsMacOS && IPAddress2.TryParse(ProxySettings.SystemProxyIp.Value, out var ip)) ? ip : IPAddress.Any;

                    httpProxyService.Socks5ProxyEnable = ProxySettings.Socks5ProxyEnable.Value;
                    httpProxyService.Socks5ProxyPortId = ProxySettings.Socks5ProxyPortId.Value;
                    if (!ModelValidatorProvider.IsPortId(httpProxyService.Socks5ProxyPortId))
                    {
                        httpProxyService.Socks5ProxyPortId = ProxySettings.DefaultSocks5ProxyPortId;
                    }

                    //httpProxyService.HostProxyPortId = ProxySettings.HostProxyPortId;
                    httpProxyService.TwoLevelAgentEnable = ProxySettings.TwoLevelAgentEnable.Value;

                    httpProxyService.TwoLevelAgentProxyType = (ExternalProxyType)ProxySettings.TwoLevelAgentProxyType.Value;
                    if (!httpProxyService.TwoLevelAgentProxyType.IsDefined())
                    {
                        httpProxyService.TwoLevelAgentProxyType = IHttpProxyService.DefaultTwoLevelAgentProxyType;
                    }

                    httpProxyService.TwoLevelAgentIp     = IPAddress2.TryParse(ProxySettings.TwoLevelAgentIp.Value, out var ip_t) ? ip_t.ToString() : IPAddress.Loopback.ToString();
                    httpProxyService.TwoLevelAgentPortId = ProxySettings.TwoLevelAgentPortId.Value;
                    if (!ModelValidatorProvider.IsPortId(httpProxyService.TwoLevelAgentPortId))
                    {
                        httpProxyService.TwoLevelAgentPortId = ProxySettings.DefaultTwoLevelAgentPortId;
                    }
                    httpProxyService.TwoLevelAgentUserName = ProxySettings.TwoLevelAgentUserName.Value;
                    httpProxyService.TwoLevelAgentPassword = ProxySettings.TwoLevelAgentPassword.Value;

                    httpProxyService.ProxyDNS = IPAddress2.TryParse(ProxySettings.ProxyMasterDns.Value, out var dns) ? dns : null;

                    this.RaisePropertyChanged(nameof(EnableProxyDomains));
                    this.RaisePropertyChanged(nameof(EnableProxyScripts));

                    if (!httpProxyService.IsSystemProxy)
                    {
                        const ushort httpsPort = 443;
                        var inUse = httpProxyService.PortInUse(httpsPort);
                        if (inUse)
                        {
                            string?error_CommunityFix_StartProxyFaild443 = null;
                            if (OperatingSystem2.IsWindows)
                            {
                                var p = SocketHelper.GetProcessByTcpPort(httpsPort);
                                if (p != null)
                                {
                                    error_CommunityFix_StartProxyFaild443 = AppResources.CommunityFix_StartProxyFaild443___.Format(httpsPort, p.ProcessName, p.Id);
                                }
                            }
                            error_CommunityFix_StartProxyFaild443 ??= AppResources.CommunityFix_StartProxyFaild443_.Format(httpsPort);
                            Toast.Show(error_CommunityFix_StartProxyFaild443);
                            return;
                        }
                    }

                    var isRun = await httpProxyService.StartProxy();

                    if (isRun)
                    {
                        if (!httpProxyService.IsSystemProxy)
                        {
                            if (httpProxyService.ProxyDomains.Any_Nullable())
                            {
                                var localhost = IPAddress.Any.Equals(httpProxyService.ProxyIp) ? IPAddress.Loopback.ToString() : httpProxyService.ProxyIp.ToString();

                                var hosts = httpProxyService.ProxyDomains !.SelectMany(s =>
                                {
                                    if (s == null)
                                    {
                                        return(default !);
Example #32
0
 public void Dispose()
 {
     SourceList.Dispose();
     AudioList.Dispose();
 }
Example #33
0
 public MockGameController()
 {
     _rootCache = new SourceList <RedFileSystemModel>();
 }
 /// <summary>
 /// Removes the list item at the specified index.
 /// </summary>
 /// <remarks>
 /// Removes the underlaying source list item at the specified
 /// index.
 /// </remarks>
 /// <param name="index">
 /// The zero-based index of the item to remove.</param>
 /// <exception cref="NotSupportedException">
 /// When the underlaying source list is read-only.</exception>
 /// <exception cref="ArgumentOutOfRangeException">
 /// index is not a valid index in the underlaying source list"/>.
 /// </exception>
 public override void RemoveAt(int index)
 {
     SourceList.RemoveAt(index);
 }
Example #35
0
 public void SetUp()
 {
     _collection = new ObservableCollectionExtended <Person>();
     _source     = new SourceList <Person>();
     _binder     = _source.Connect().Bind(_collection).Subscribe();
 }
 /// <summary>
 /// Removes all items from this list.
 /// </summary>
 /// <remarks>
 /// Remove all item from the underlaying source list.
 /// </remarks>
 /// <exception cref="NotSupportedException">
 /// When the underlaying source list is read-only.
 /// </exception>
 public override void Clear()
 {
     SourceList.Clear();
 }
 /// <summary>
 /// Returns an enumerator that iterates through the list.
 /// </summary>
 /// <returns>
 /// A <see cref="IEnumerator{T}"/> that can be used to iterate
 /// through the list.
 /// </returns>
 /// <filterpriority>1</filterpriority>
 public override IEnumerator <TTo> GetEnumerator()
 {
     return(new TransformingEnumerator <TFrom, TTo>(SourceList.GetEnumerator(), Transform));
 }
Example #38
0
        public ArrayList GetPhoneBooks()
        {
            ArrayList ebooks = new ArrayList();

            SourceList slist = new SourceList ("/apps/evolution/addressbook/sources");
            if (slist != null) {
                SList group_list = slist.Groups;
                //Console.WriteLine ("Group count: {0}", group_list.Count);

                foreach (SourceGroup group in group_list) {
                    //Only get phone books on this machine.
                    if (group.Name == "On This Computer") {
                        SList src_list = group.Sources;

                        foreach (Evolution.Source src in src_list) {
                            ebooks.Add(src.Name);
                        }
                    }
                }
            }
            return ebooks;
        }
Example #39
0
        public PrivacyControlViewModel(Wallet wallet, TransactionInfo transactionInfo, TransactionBroadcaster broadcaster)
        {
            _wallet = wallet;

            _pocketSource = new SourceList <PocketViewModel>();

            _pocketSource.Connect()
            .Bind(out _pockets)
            .Subscribe();

            var selected = _pocketSource.Connect()
                           .AutoRefresh()
                           .Filter(x => x.IsSelected);

            var selectedList = selected.AsObservableList();

            selected.Sum(x => x.TotalBtc)
            .Subscribe(x =>
            {
                StillNeeded    = transactionInfo.Amount.ToDecimal(MoneyUnit.BTC) - x;
                EnoughSelected = StillNeeded <= 0;
            });

            StillNeeded = transactionInfo.Amount.ToDecimal(MoneyUnit.BTC);

            NextCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                var coins = selectedList.Items.SelectMany(x => x.Coins).ToArray();

                try
                {
                    try
                    {
                        var transactionResult = await Task.Run(() => TransactionHelpers.BuildTransaction(_wallet, transactionInfo.Address, transactionInfo.Amount, transactionInfo.Labels, transactionInfo.FeeRate, coins, subtractFee: false));
                        Navigate().To(new TransactionPreviewViewModel(wallet, transactionInfo, broadcaster, transactionResult));
                    }
                    catch (InsufficientBalanceException)
                    {
                        var dialog = new InsufficientBalanceDialogViewModel(BalanceType.Pocket);
                        var result = await NavigateDialog(dialog, NavigationTarget.DialogScreen);

                        if (result.Result)
                        {
                            var transactionResult = await Task.Run(() => TransactionHelpers.BuildTransaction(_wallet, transactionInfo.Address, transactionInfo.Amount, transactionInfo.Labels, transactionInfo.FeeRate, coins, subtractFee: true));
                            Navigate().To(new TransactionPreviewViewModel(wallet, transactionInfo, broadcaster, transactionResult));
                        }
                        else
                        {
                            Navigate().BackTo <SendViewModel>();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    await ShowErrorAsync("Transaction Building", ex.ToUserFriendlyString(), "Wasabi was unable to create your transaction.");
                    Navigate().BackTo <SendViewModel>();
                }
            },
                this.WhenAnyValue(x => x.EnoughSelected));

            EnableAutoBusyOn(NextCommand);
        }
Example #40
0
        public FileTailer(FileInfo file, 
            IObservable<string> textToMatch,
            IObservable<ScrollRequest> scrollRequest,
            IScheduler scheduler=null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (textToMatch == null) throw new ArgumentNullException(nameof(textToMatch));

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

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

            var metronome = Observable
                    .Interval(TimeSpan.FromMilliseconds(250), scheduler ?? Scheduler.Default)
                    .ToUnit()
                    .Replay().RefCount();

            //temp mess for a few days
            var indexer = file.WatchFile(metronome)
                            .TakeWhile(notification => notification.Exists)
                            .Repeat()
                            .Index()
                            .Synchronize(locker)
                            .Replay(1).RefCount();

            var matcher = textToMatch.Select(searchText =>
            {
                if (string.IsNullOrEmpty(searchText) || searchText.Length < 3)
                    return Observable.Return(LineMatches.None);

                return file.WatchFile(metronome)
                    .TakeWhile(notification => notification.Exists)
                    .Repeat()
                    .Match(s => s.Contains(searchText, StringComparison.OrdinalIgnoreCase));

            }).Switch()
            .Synchronize(locker)
            .Replay(1).RefCount();

            //count matching lines (all if no filter is specified)
            MatchedLines = indexer.CombineLatest(matcher, (indicies, matches) => matches == LineMatches.None ? indicies.Count : matches.Count);

            //count total line
            TotalLines = indexer.Select(x => x.Count);

            FileSize = file.WatchFile(metronome).Select(notification => notification.Size);

            var aggregator = indexer.CombineLatest(matcher, scrollRequest,(idx, mtch, scroll) => new CombinedResult(scroll, mtch, idx))
                .Select(result =>
                {
                    var scroll = result.Scroll;
                    var indicies = result.Incidies;
                    var matched = result.MatchedLines;

                    IEnumerable<LineIndex> indices;
                    if (result.MatchedLines.ChangedReason == LineMatchChangedReason.None)
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? indicies.GetTail(scroll)
                            : indicies.GetFromIndex(scroll);
                    }
                    else
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? indicies.GetTail(scroll, matched)
                            : indicies.GetFromIndex(scroll, matched);
                    }

                    var currentPage = indices.ToArray();
                    var previous = lines.Items.Select(l => l.LineIndex).ToArray();
                    var removed = previous.Except(currentPage).ToArray();
                    var removedLines = lines.Items.Where(l=> removed.Contains(l.LineIndex)).ToArray();

                    var added = currentPage.Except(previous).ToArray();
                    //finally we can load the line from the file
                    var newLines =  file.ReadLines(added, (lineIndex, text) =>
                    {
                        var isEndOfTail = indicies.ChangedReason != LinesChangedReason.Loaded && lineIndex.Line > indicies.TailStartsAt;

                        return new Line(lineIndex, text, isEndOfTail ? DateTime.Now : (DateTime?) null);
                    }, indicies.Encoding).ToArray();

                    return new { NewLines = newLines, OldLines = removedLines };
                })
                .RetryWithBackOff((Exception error, int attempts) =>
                {
                    //todo: plug in file missing or error into the screen
                    return TimeSpan.FromSeconds(1);
                 })
                 .Where(fn=> fn.NewLines.Length + fn.OldLines.Length > 0)
                .Subscribe(changes =>
                {
                    //update observable list
                    lines.Edit(innerList =>
                    {
                        if (changes.OldLines.Any()) innerList.RemoveMany(changes.OldLines);
                        if (changes.NewLines.Any())  innerList.AddRange(changes.NewLines);
                    });
                });
            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
Example #41
0
 public Document()
 {
     Lines = new SourceList <string>();
 }
Example #42
0
        private void Reset(bool LoadColumnsFromSettings)
        {
            FirstLoad    = true;
            ActualRender = true;

            LastHorizontalSkip = -1;

            LastHorizontalScrollPosition = 0;


            if (bvgGrid != null)
            {
                bvgGridTransferableState = new BvgGridTransferableState <TItem>(bvgGrid);
            }
            else
            {
                bvgGridTransferableState = new BvgGridTransferableState <TItem>();
            }

            bvgGrid = new BvgGrid <TItem>
            {
                IsReady         = true,
                Name            = TableName,
                RowsTotalCount  = SourceList.Count(),
                bvgSettings     = bvgSettings,
                AllProps        = typeof(TItem).GetProperties(BindingFlags.Public | BindingFlags.Instance),
                HasMeasuredRect = bvgGridTransferableState.HasMeasuredRect,
                bvgSize         = bvgGridTransferableState.bvgSize,
            };

            bvgGrid.bvgModal.bvgGrid = bvgGrid;

            if (bvgGridTransferableState.ContaintState)
            {
                bvgGrid.cssHelper = bvgGridTransferableState.cssHelper;
            }

            if (bvgGridTransferableState.ContaintState && !LoadColumnsFromSettings)
            {
                bvgGrid.ColumnsOrderedList          = bvgGridTransferableState.ColumnsOrderedList;
                bvgGrid.ColumnsOrderedListFrozen    = bvgGridTransferableState.ColumnsOrderedListFrozen;
                bvgGrid.ColumnsOrderedListNonFrozen = bvgGridTransferableState.ColumnsOrderedListNonFrozen;
            }
            else
            {
                bvgGrid.ColumnsOrderedList = ColumnsHelper <TItem> .GetColumnsOrderedList(bvgGrid);

                bvgGrid.ColumnsOrderedListFrozen    = bvgGrid.ColumnsOrderedList.Where(x => x.IsFrozen).ToArray();
                bvgGrid.ColumnsOrderedListNonFrozen = bvgGrid.ColumnsOrderedList.Where(x => x.IsFrozen == false).ToArray();
            }


            bvgGrid.UpdateNonFrozenColwidthSumsByElement();

            if (bvgSettings.SortedColumn.Item1)
            {
                bvgGrid.SortState = Tuple.Create(bvgSettings.SortedColumn.Item1, bvgSettings.SortedColumn.Item2, bvgSettings.SortedColumn.Item3);


                if (bvgSettings.SortedColumn.Item3)
                {
                    SortedRowsList = GenericAdapter <TItem> .GetSortedRowsList(SourceList.AsQueryable(), bvgSettings.SortedColumn.Item2).ToArray();
                }
                else
                {
                    SortedRowsList = GenericAdapter <TItem> .GetSortedRowsList(SourceList.AsQueryable(), bvgSettings.SortedColumn.Item2 + " desc").ToArray();
                }
            }
            else
            {
                bvgGrid.SortState = Tuple.Create(false, string.Empty, false);

                SortedRowsList = SourceList.ToArray();
            }
        }
        public MetricsViewModel(ISourcesCacheProvider cacheProvider)
        {
            _model = new MetricsModel
            {
                Caption = "Metrics",
                Cache   = cacheProvider.CurrentCache
            };
            Disposables.Add(_model);

            _model.WhenAnyValue(x => x.Caption, x => x.Online)
            .Subscribe(v => Title = v.Item1 + (v.Item2 ? " >" : " ||"));

            var dynamicFilter = _model.SelectedSourcesChanged
                                .Select(_ => Filters.CreateFilterMetricBySources(_model));

            var observable = _model.Cache.Metrics
                             .Connect()
                             .Filter(dynamicFilter)
                             .Publish();

            _metricsCache = observable
                            .AsObservableCache()
                            .DisposeWith(Disposables);

            observable
            .Transform(x => new MetricValueItem {
                Metric = x
            })
            .Sort(SortExpressionComparer <MetricValueItem>
                  .Ascending(x => x.Metric.Instance.Source.Name)
                  .ThenByAscending(x => x.Metric.Instance.Name)
                  .ThenByAscending(x => x.Metric.Name))
            .ObserveOnDispatcher()
            .Bind(out var metricValuesStatic)
            .Subscribe()
            .DisposeWith(Disposables);

            observable
            .Connect()
            .DisposeWith(Disposables);

            var metricValuesDynamicSource = new SourceList <MetricValueItem>()
                                            .DisposeWith(Disposables);

            metricValuesDynamicSource
            .Connect()
            .ObserveOnDispatcher()
            .Bind(out var metricValuesDynamic)
            .Subscribe()
            .DisposeWith(Disposables);

            _model.WhenAnyValue(x => x.MetricDiagramVisible)
            .Subscribe(x => MetricValuesList = x ? metricValuesStatic : metricValuesDynamic);

            _model.SelectedSourcesChanged.Subscribe(_ => UpdateSelectedMetrics());
            UpdateSelectedMetrics();

            var canStart = _model.WhenAny(x => x.Online, x => !x.Value);

            StartCommand = ReactiveCommand.Create(OnStart, canStart);

            var canStop = _model.WhenAny(x => x.Online, x => x.Value);

            StopCommand = ReactiveCommand.Create(OnStop, canStop);

            UpdateCommand = ReactiveCommand.Create(OnUpdate, canStop);

            var mapper = Mappers.Xy <MetricValueItem>()
                         .X(item => (double)item.Interval.Ticks / TimeSpan.FromMinutes(5).Ticks)
                         .Y(item => item.Value);

            //lets save the mapper globally.
            Charting.For <MetricValueItem>(mapper);

            SeriesCollection = new ChartValues <MetricValueItem>();

            //lets set how to display the X Labels
            DateTimeFormatter = value => new DateTime((long)value * TimeSpan.FromMinutes(5).Ticks).ToString("t");

            UpdateCommand.Subscribe(results =>
            {
                if (_model.MetricDiagramVisible)
                {
                    SeriesCollection.Clear();
                    if (results != null)
                    {
                        SeriesCollection.AddRange(results);
                    }
                }
                else
                {
                    metricValuesDynamicSource.Edit(innerList =>
                    {
                        innerList.Clear();
                        innerList.AddRange(results);
                    });
                }
            });
        }
Example #44
0
        public FileTailer(FileInfo file, 
            IObservable<string> textToMatch,
            IObservable<ScrollRequest> scrollRequest,
            IScheduler scheduler=null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (textToMatch == null) throw new ArgumentNullException(nameof(textToMatch));

            //create list of lines which contain the observable text
               var matchedLines = textToMatch
                    .Select(searchText =>
                    {
                        Func<string, bool> predicate = null;
                        if (!string.IsNullOrEmpty(searchText))
                            predicate = s => s.Contains(searchText, StringComparison.OrdinalIgnoreCase);

                        return file.WatchFile(scheduler:scheduler ?? Scheduler.Default)
                                    .TakeWhile(notification => notification.Exists)
                                    .Repeat()
                                    .ScanFile(predicate);

                    }).Switch()
                    .Replay(1).RefCount();

            MatchedLines = matchedLines.Select(x => x.MatchingLines.Length);

            TotalLines = matchedLines.Select(x => x.TotalLines);

            //todo: plug in file missing or error into the screen

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

            //this is the beast! Dynamically combine lines requested by the consumer
            //with the lines which exist in the file. This enables proper virtualisation of the file
            var scroller = matchedLines
                .CombineLatest(scrollRequest, (scanResult, request) => new {scanResult , request })
                .Subscribe(x =>
                {
                    var mode = x.request.Mode;
                    var pageSize = x.request.PageSize;
                    var endOfTail = x.scanResult.EndOfTail;
                    var isInitial = x.scanResult.Index==0;
                    var allLines = x.scanResult.MatchingLines;
                    var previousPage = lines.Items.Select(l => new LineIndex(l.Number, l.Index)).ToArray();

                    //Otherwise take the page size and start index from the request
                    var currentPage = (mode == ScrollingMode.Tail
                        ? allLines.Skip(allLines.Length-pageSize).Take(pageSize).ToArray()
                        : allLines.Skip(x.request.FirstIndex).Take(pageSize)).ToArray();

                    var added = currentPage.Except(previousPage).ToArray();
                    var removed = previousPage.Except(currentPage).Select(li=>li.Line).ToArray();

                    if (added.Length + removed.Length == 0) return;

                    try
                    {
                        var addedLines = file.ReadLines(added, (lineIndex, text) =>
                        {
                            var isEndOfTail = !isInitial && lineIndex.Line > endOfTail;
                            return new Line(lineIndex.Line, lineIndex.Index, text, isEndOfTail ? DateTime.Now : (DateTime?)null);
                        }).ToArray();

                        //get old lines from the current collection
                        var removedLines = lines.Items.Where(l => removed.Contains(l.Number)).ToArray();

                        //finally relect changes in the list
                        lines.Edit(innerList =>
                        {
                            innerList.RemoveMany(removedLines);
                            innerList.AddRange(addedLines);
                        });
                    }
                    catch (Exception)
                    {
                        //Very small chance of an error here but if one is causght the next successful read will recify this
                        //TODO: 1. Feedback to user that steaming has stopped
                        //TODO: 2. Place the ReadLines(..) method with the select of an observable
                    }

                });
            _cleanUp = new CompositeDisposable(Lines, scroller, lines);
        }
Example #45
0
 public int IndexOf(TTarget item)
 {
     return(SourceList.IndexOf(Deconvert(item)));
 }
Example #46
0
        public FileTailer(FileInfo file,
                IObservable<FileSearchResult> filter,
                IObservable<ScrollRequest> scrollRequest,
                ILogger logger,
                IScheduler scheduler = null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (filter == null) throw new ArgumentNullException(nameof(filter));
            if (logger == null) throw new ArgumentNullException(nameof(logger));

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

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

            var isBusy = new Subject<bool>();
            IsSearching = isBusy.AsObservable();

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

            var fileWatcher = file.WatchFile(scheduler: scheduler)
                            .DistinctUntilChanged()
                            .TakeWhile(notification => notification.Exists).Repeat()
                            .Replay(1).RefCount();

            var indexer = fileWatcher.Index().Replay(1).RefCount();

            //compare latest lines and latest filter and only take the filtered results it is not empty
            var latestLines = indexer.Cast<ILineProvider>().Synchronize(locker);
            var latestFilter = filter.Cast<ILineProvider>().Synchronize(locker);
            var latest = latestLines.CombineLatest(latestFilter, (l, f) => f.IsEmpty ? l : f);

            MatchedLines = latest.Select(provider => provider.Count);
            TotalLines = latestLines.Select(x => x.Count);
            FileSize = fileWatcher.Select(notification => notification.Size);
            IsLoading = indexer.Take(1).Select(_ => false).StartWith(true);

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

                lines.Edit(innerList =>
                {
                    if (removed.Any()) innerList.RemoveMany(removed);
                    if (added.Any()) innerList.AddRange(added);
                });

            });

            //var aggregator = latest.CombineLatest(scrollRequest, (currentLines, scroll) =>
            //{
            //    //TODO: Read entire page, the check which lines should be added and which shold be removed
            //    //as part of that work, get the maximum inded [this is the head!]

            //    //   Debug.WriteLine($"{scroll.Mode}, {scroll.FirstIndex}, {scroll.PageSize}");

            //    var currentPage = currentLines.GetIndicies(scroll).ToArray();

            //    var previous = lines.Items.Select(l => l.LineInfo).ToArray();
            //    var removed = previous.Except(currentPage, LineInfo.LineIndexComparer).ToArray();
            //    var added = currentPage.Except(previous, LineInfo.LineIndexComparer).ToArray();
            //    //calculated added and removed lines
            //    var removedLines = lines.Items.Where(l => removed.Contains(l.LineInfo)).ToArray();

            //    Func<long, DateTime?> isTail = l =>
            //    {
            //        //account for time with tail (i.e. add time to ILineProvider.TailStartsAt )
            //        var tail = currentLines.TailStartsAt;
            //        var onTail = tail != -1 && l >= tail;
            //        return onTail ? DateTime.Now : (DateTime?)null;
            //    };

            //    //Console.WriteLine();
            //    //finally we can load the line from the file todo: Add encdoing back in
            //    var newLines = file.ReadLine(added, (lineIndex, text, position) => new Line(lineIndex, text, isTail(position)), Encoding.UTF8).ToArray();

            //    return new { NewLines = newLines, OldLines = removedLines };
            //})
            //.Where(fn => fn.NewLines.Length + fn.OldLines.Length > 0)
            //.Subscribe(changes =>
            //{
            //    //update observable list
            //    lines.Edit(innerList =>
            //{
            //    if (changes.OldLines.Any()) innerList.RemoveMany(changes.OldLines);
            //    if (changes.NewLines.Any()) innerList.AddRange(changes.NewLines);
            //});
            //});

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator, Disposable.Create(() => isBusy.OnCompleted()));
        }
Example #47
0
        public FileTailer(FileInfo file, 
            IObservable<string> textToMatch,
            IObservable<ScrollRequest> scrollRequest,
            IScheduler scheduler=null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (textToMatch == null) throw new ArgumentNullException(nameof(textToMatch));

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

            var matcher = textToMatch.Select(searchText =>
            {
                if (string.IsNullOrEmpty(searchText) || searchText.Length < 3)
                    return Observable.Return(LineMatches.None);

                return file.WatchFile(scheduler: scheduler)
                    .TakeWhile(notification => notification.Exists)
                    .Repeat()
                    .Match(s => s.Contains(searchText, StringComparison.OrdinalIgnoreCase));

            }).Switch()
            .Replay(1).RefCount();

            //temp mess for a few days
            var indexer = file.WatchFile(scheduler: scheduler)
                                .TakeWhile(notification => notification.Exists)
                                .Repeat()
                                .Index()
                                .Replay(1).RefCount();

            //count matching lines (all if no filter is specified)
            MatchedLines = indexer.CombineLatest(matcher, (indicies, matches) => matches == LineMatches.None ? indicies.Count : matches.Count);

            //count total line
            TotalLines = indexer.Select(x => x.Count);

            //todo: plug in file missing or error into the screen

            var locker = new object();
            var theBeast = indexer.Synchronize(locker)
                .CombineLatest(matcher.Synchronize(locker), scrollRequest.Synchronize(locker),(idx, mtch, scroll) => new CombinedResult(scroll, mtch, idx))
                .Select(result =>
                {
                    var scroll = result.Scroll;
                    var allLines = result.Incidies;
                    var matched = result.MatchedLines;

                    IEnumerable<LineIndex> indices;
                    if (result.MatchedLines.ChangedReason == LineMatchChangedReason.None)
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? allLines.GetTail(scroll)
                            : allLines.GetFromIndex(scroll);
                    }
                    else
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? allLines.GetTail(scroll, matched)
                            : allLines.GetFromIndex(scroll, matched);
                    }

                    return  file.ReadLines(indices, (lineIndex, text) =>
                    {
                        var isEndOfTail = allLines.ChangedReason != LinesChangedReason.Loaded && lineIndex.Line > allLines.TailStartsAt;
                        return new Line(lineIndex.Line, lineIndex.Index, text,isEndOfTail ? DateTime.Now : (DateTime?) null);
                    }).ToArray();
                })
                //.RetryWithBackOff((error, attempts) =>
                //{
                //    //TODO: Log
                //    return TimeSpan.FromSeconds(1);
                //})
                .Subscribe(newPage =>
                {
                    //update observable list
                    lines.Edit(innerList =>
                    {

                        var removed = innerList.Except(newPage).ToArray();
                        var added = newPage.Except(innerList).ToArray();

                        if (removed.Any()) innerList.RemoveMany(removed);
                        if (added.Any())  innerList.AddRange(added);
                    });

                });

            ////this is the beast! Dynamically combine lines requested by the consumer
            ////with the lines which exist in the file. This enables proper virtualisation of the file
            //var scroller = matchedLines
            //    .CombineLatest(scrollRequest, (scanResult, request) => new {scanResult , request })
            //    .Subscribe(x =>
            //    {
            //        var mode = x.request.Mode;
            //        var pageSize = x.request.PageSize;
            //        var endOfTail = x.scanResult.EndOfTail;
            //        var isInitial = x.scanResult.Index==0;
            //        var allLines = x.scanResult.MatchingLines;
            //        var previousPage = lines.Items.Select(l => new LineIndex(l.Number, l.Index, 0, 0)).ToArray();

            //        //Otherwise take the page size and start index from the request
            //        var currentPage = (mode == ScrollingMode.Tail
            //            ? allLines.Skip(allLines.Length-pageSize).Take(pageSize).ToArray()
            //            : allLines.Skip(x.request.FirstIndex).Take(pageSize)).ToArray();

            //        var added = currentPage.Except(previousPage).ToArray();
            //        var removed = previousPage.Except(currentPage).Select(li=>li.Line).ToArray();

            //        if (added.Length + removed.Length == 0) return;

            //        try
            //        {
            //            var addedLines = file.ReadLines(added, (lineIndex, text) =>
            //            {
            //                var isEndOfTail = !isInitial && lineIndex.Line > endOfTail;
            //                return new Line(lineIndex.Line, lineIndex.Index, text, isEndOfTail ? DateTime.Now : (DateTime?)null);
            //            }).ToArray();

            //            //get old lines from the current collection
            //            var removedLines = lines.Items.Where(l => removed.Contains(l.Number)).ToArray();

            //            //finally relect changes in the list
            //            lines.Edit(innerList =>
            //            {
            //                innerList.RemoveMany(removedLines);
            //                innerList.AddRange(addedLines);
            //            });
            //        }
            //        catch (Exception)
            //        {
            //            //Very small chance of an error here but if one is causght the next successful read will recify this
            //            //TODO: 1. Feedback to user that steaming has stopped
            //            //TODO: 2. Place the ReadLines(..) method with the select of an observable
            //        }

            //    });
            _cleanUp = new CompositeDisposable(Lines, lines);
        }