static CountdownModelBase()
        {
            r_Interval = Observable.Interval(TimeSpan.FromSeconds(1.0)).Publish();
            r_Interval.Connect();

            LastOneMinute = TimeSpan.FromMinutes(1.0);
        }
Ejemplo n.º 2
0
        public Aggregator(string counterCategoryFilter, string counterNameFilter, string aggregationType, string aggregationParameters, Type valuesDataType)
        {
            _aggregationOperation = AggregationOperationFactory.Create(valuesDataType, aggregationType, aggregationParameters);
            _counterCategoryFilter = counterCategoryFilter;
            _counterNameFilter = counterNameFilter;
            _valuesDataType = valuesDataType;
            _seq = new MovingWindowSequence(1000, 1000*5);
            _logEventBuffer = _eventSubject.Window(_seq.BufferOpenings, _seq.ClosingWindowSequenceSelector).Publish();
            _logEventBuffer.Connect();

        }
        public MemoryLogReader(string logName, IScheduler scheduler = null)
        {
            _logName = logName;
            scheduler = scheduler ?? TaskPoolScheduler.Default;

            _target = FindTarget();

            _connectObservable = Observable.Interval(TimeSpan.FromSeconds(1), scheduler)
                .Select(x => ReadTargetEntries())
                .Publish();

              _disposable = _connectObservable.Connect();
        }
        public MemoryService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null)
        {
            _taskPoolScheduler = taskPoolScheduler ?? TaskPoolScheduler.Default;
            _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current;

            _logger = LogManager.GetCurrentClassLogger();

            _countersObservable = Observable.Create<Counters>(x => CreateCounters(x))
                .SubscribeOn(_taskPoolScheduler)
                .CombineLatest(BufferedDispatcherIdle(TimeSpan.FromSeconds(1)), (x, y) => x)
                .Replay(1);

            _disposable = _countersObservable.Connect();
        }
        /// <summary>
        /// Constructs an ObservableAsPropertyHelper object.
        /// </summary>
        /// <param name="observable">The Observable to base the property on.</param>
        /// <param name="onChanged">The action to take when the property
        /// changes, typically this will call the ViewModel's
        /// RaisePropertyChanged method.</param>
        /// <param name="onChanging">The action to take when the property
        /// changes, typically this will call the ViewModel's
        /// RaisePropertyChanging method.</param>
        /// <param name="initialValue">The initial value of the property.</param>
        /// <param name="scheduler">The scheduler that the notifications will be
        /// provided on - this should normally be a Dispatcher-based scheduler
        /// (and is by default)</param>
        public ObservableAsPropertyHelper(
            IObservable <T> observable,
            Action <T> onChanged,
            Action <T> onChanging = null,
            T initialValue        = default(T),
            IScheduler scheduler  = null)
        {
            Contract.Requires(observable != null);
            Contract.Requires(onChanged != null);

            scheduler  = scheduler ?? CurrentThreadScheduler.Instance;
            onChanging = onChanging ?? (_ => {});
            _lastValue = initialValue;

            var subj      = new ScheduledSubject <T>(scheduler);
            var exSubject = new ScheduledSubject <Exception>(CurrentThreadScheduler.Instance, RxApp.DefaultExceptionHandler);

            bool firedInitial = false;

            subj.Subscribe(x => {
                // Suppress a non-change between initialValue and the first value
                // from a Subscribe
                if (firedInitial && EqualityComparer <T> .Default.Equals(x, _lastValue))
                {
                    return;
                }

                onChanging(x);
                _lastValue = x;
                onChanged(x);
                firedInitial = true;
            }, exSubject.OnNext);

            ThrownExceptions = exSubject;

            // Fire off an initial RaisePropertyChanged to make sure bindings
            // have a value
            subj.OnNext(initialValue);
            _source = observable.DistinctUntilChanged().Multicast(subj);

            if (ModeDetector.InUnitTestRunner())
            {
                _inner = _source.Connect();
            }
        }
Ejemplo n.º 6
0
    /// <summary>
    /// Observableを枝分かれ、コルーチン版
    /// サブスクリプション前にConnect
    /// </summary>
    private IEnumerator ExcutePublishCoroutineBad()
    {
        TimeSpan time = TimeSpan.FromSeconds(1);
        IConnectableObservable <long> stream = Observable
                                               .Interval(time)
                                               .Publish();

        // ここでConnectを呼ぶと、1回目のSubscribeと2回目のSubscribeがズレる可能性がある
        stream.Connect();
        stream.Subscribe(x => {
            Debug.Log("First Value :  " + x);
        });
        yield return(new WaitForSeconds(2));

        stream.Subscribe(x => {
            Debug.Log(string.Format("<color=blue>Second Value : {0}</color>", x));
        });
    }
Ejemplo n.º 7
0
        /// <summary>
        /// the subscription of the real data consumer won't affect the underlying cold observable
        /// it will keep generating data as long as proxy is connected to it
        /// </summary>
        private static void TestUnderlyingStreamAlwaysOpen()
        {
            IConnectableObservable <long> proxy = Observable.Interval(TimeSpan.FromSeconds(0.5))
                                                  .Do(num => Console.WriteLine("<{0}> produced.", num))
                                                  .Publish();

            Helper.Pause("connect");
            IDisposable connection = proxy.Connect();

            Helper.Pause("subscribe observer");
            IDisposable subscription = proxy.Subscribe(num => Console.WriteLine("\t<{0}> consumed.", num));

            Helper.Pause("unsubscribe observer");
            subscription.Dispose();

            Helper.Pause("disconnect");
            connection.Dispose();
        }
Ejemplo n.º 8
0
 public IDisposable Connect()
 {
     lock (gate)
     {
         EnsureConnectableSource();
         var connection = connectableSource.Connect();
         return(Disposable.Create(() =>
         {
             lock (gate)
             {
                 using (connection)
                 {
                     connectableSource = null;
                 }
             }
         }));
     }
 }
Ejemplo n.º 9
0
        public static IObservable <T> LazilyConnect <T>(this IConnectableObservable <T> connectable,
                                                        SingleAssignmentDisposable futureDisposable)
        {
            var connected = 0;

            return(Observable.Create <T>(observer =>
            {
                var subscription = connectable.Subscribe(observer);
                if (Interlocked.CompareExchange(ref connected, 1, 0) == 0)
                {
                    if (!futureDisposable.IsDisposed)
                    {
                        futureDisposable.Disposable = connectable.Connect();
                    }
                }
                return subscription;
            }).AsObservable());
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OperationQueue"/> class.
        /// </summary>
        /// <param name="maximumConcurrent">The maximum number of concurrent operations.</param>
        public OperationQueue(int maximumConcurrent = 4)
        {
            _maximumConcurrent = maximumConcurrent;
            _scheduledGate     = new PrioritySemaphoreSubject <KeyedOperation>(maximumConcurrent);

            _resultObs = _queuedOps
                         .Multicast(_scheduledGate).RefCount()
                         .GroupBy(x => x.Key)
                         .Select(x =>
            {
                var ret = x.Select(y => ProcessOperation(y).TakeUntil(y.CancelSignal).Finally(() => _scheduledGate.Release()));
                return(x.Key == DefaultKey ? ret.Merge() : ret.Concat());
            })
                         .Merge()
                         .Multicast(new Subject <KeyedOperation>());

            _resultObs.Connect();
        }
Ejemplo n.º 11
0
        public IdleService(ISchedulerService schedulerService)
        {
            using (Duration.Measure(Logger, "Constructor - " + GetType().Name))
            {
                var mainWindow = Application.Current.MainWindow;
                if (mainWindow == null)
                {
                    throw new Exception("Main window has not been created yet!");
                }

                _idleObservable = Observable.FromEventPattern(h => mainWindow.Dispatcher.Hooks.DispatcherInactive += h,
                                                              h => mainWindow.Dispatcher.Hooks.DispatcherInactive -= h, schedulerService.TaskPool)
                                  .Publish();

                _idleObservable.Connect()
                .DisposeWith(this);
            }
        }
Ejemplo n.º 12
0
        private void Activate()
        {
            if (_isConnected)
            {
                return;
            }

            _connectedChange = GetValidationChangeObservable()
                               .Do(state =>
            {
                _isValid = state.IsValid;
                _text    = state.Text;
            })
                               .Replay(1);

            _connectedChange.Connect().DisposeWith(_disposables);
            _isConnected = true;
        }
Ejemplo n.º 13
0
        private async Task HandleConnection(WebSocket webSocket, CancellationToken cancellation)
        {
            try
            {
                WebCastData streamInfo = await GetStreamInfo(webSocket, cancellation);

                IConnectableObservable <byte[]> observable = CreateObserver(webSocket);

                SubscribeFile(cancellation, streamInfo, observable);
                SubscribeIcecast(cancellation, streamInfo, observable);

                observable.Connect();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Error handling web socket connection");
            }
        }
Ejemplo n.º 14
0
        static AsyncSubject<TSource> RunAsync<TSource>(IConnectableObservable<TSource> source, CancellationToken cancellationToken)
        {
            var s = new AsyncSubject<TSource>();

            if (cancellationToken.IsCancellationRequested)
            {
                return Cancel(s, cancellationToken);
            }

            var d = source.Subscribe(s);
            var c = source.Connect();

            if (cancellationToken.CanBeCanceled)
            {
                RegisterCancelation(s, StableCompositeDisposable.Create(d, c), cancellationToken);
            }

            return s;
        }
Ejemplo n.º 15
0
        private void Start()
        {
            IConnectableObservable <Unit> iconnectableObservable = (IConnectableObservable <Unit>)Observable.Publish <Unit>((IObservable <M0>)Observable.FromCoroutine((Func <IEnumerator>)(() => this.InputWait()), false));

            iconnectableObservable.Connect();
            ObservableExtensions.Subscribe <Unit>((IObservable <M0>)Observable.WhenAll(new IObservable <Unit>[1]
            {
                (IObservable <Unit>)iconnectableObservable
            }), (Action <M0>)(_ => Singleton <Manager.Scene> .Instance.LoadReserve(new Manager.Scene.Data()
            {
                levelName = Singleton <Resources> .Instance.DefinePack.SceneNames.MapScene,
                isAdd     = false,
                isFade    = true,
                isAsync   = true
            }, false)));
            Singleton <Input> .Instance.ReserveState(Input.ValidType.UI);

            Singleton <Input> .Instance.SetupState();
        }
Ejemplo n.º 16
0
        public virtual AsyncSubject <TSource> RunAsync <TSource>(IConnectableObservable <TSource> source, CancellationToken cancellationToken)
        {
            var s = new AsyncSubject <TSource>();

            if (cancellationToken.IsCancellationRequested)
            {
                return(Cancel(s));
            }

            var d = source.SubscribeSafe(s);
            var c = source.Connect();

            if (cancellationToken.CanBeCanceled)
            {
                RegisterCancelation(s, new CompositeDisposable(d, c), cancellationToken);
            }

            return(s);
        }
Ejemplo n.º 17
0
        public static AwaitableAsyncSubject <TSource> RunAsync <TSource>(this IConnectableObservable <TSource> source, CancellationToken cancellationToken)
        {
            var s = new AwaitableAsyncSubject <TSource>();

            var cancel = new Action(() => s.OnError(new OperationCanceledException()));

            if (cancellationToken.IsCancellationRequested)
            {
                cancel();
                return(s);
            }

            var d = new CompositeDisposable(source.SubscribeSafe(s), source.Connect());

            cancellationToken.Register(d.Dispose);
            cancellationToken.Register(cancel);

            return(s);
        }
Ejemplo n.º 18
0
    /// <summary>
    /// Observableを枝分かれ、コルーチン版
    /// サブスクリプション後にConnect
    /// </summary>
    private IEnumerator ExcutePublishCoroutineGood()
    {
        TimeSpan time = TimeSpan.FromSeconds(1);
        IConnectableObservable <long> stream = Observable
                                               .Interval(time)
                                               .Publish();

        stream.Subscribe(x => {
            Debug.Log("First Value :  " + x);
        });
        yield return(new WaitForSeconds(2));

        stream.Subscribe(x => {
            Debug.Log(string.Format("<color=blue>Second Value : {0}</color>", x));
        });
        // Connectは全てのサブスクリプションが終わってから呼び出すと
        // コルーチンやスレッドでズレることは無くなる
        stream.Connect();
    }
Ejemplo n.º 19
0
        public FSViewModel(IObservable <EventPattern <RoutedEventArgs> > uiAddQuery)
        {
            _storeSubject = GetFileSystemStream().Replay();

            //Compute aggregates  - 1st attempt
            IObservable <double> fileLenthgs = _storeSubject.Select(fcf => (double)fcf.Length);

            IObservable <int> fileCounts = fileLenthgs.Scan(0, (count, _) => count + 1);

            IObservable <double> fileLenRunningSums = fileLenthgs.Scan((sum, next) => sum + next);

            IObservable <FileChangeAggregate> aggCountSum =
                fileCounts.Zip(fileLenRunningSums, (cnt, sum) => new FileChangeAggregate()
            {
                Sum = sum, Count = cnt
            });

            IObservable <FileChangeAggregate> aggCountSumMean =
                aggCountSum.Zip(fileLenthgs.Mean(), (fca, mean) => { fca.Mean = mean; return(fca); });

            IObservable <FileChangeAggregate> aggCountSumMeanStdDev =
                aggCountSumMean.Zip(fileLenthgs.StdDev(), (fca, stddev) => { fca.StdDev = stddev; return(fca); });

            uiAddQuery.Subscribe(_ignore =>
            {
                Func <FileChangeFact, bool> fltr = _ => true;
                if (!String.IsNullOrEmpty(FilterPath))
                {
                    string fp = FilterPath; // need to copy the value from the UI based DP so that the RX based Where() clause can safely access it
                    fltr      = fci => fci.Path.StartsWith(fp, StringComparison.CurrentCultureIgnoreCase);
                }

                QuerySubscriptions.Add(new QuerySubscriptionDO(FilterPath, _storeSubject.Where(fltr)));
            });

            //Wire up UI
            FSItems            = new ObservableCollection <FileChangeFact>();
            QuerySubscriptions = new ObservableCollection <QuerySubscriptionDO>();
            aggCountSumMeanStdDev.ObserveOnDispatcher().Subscribe(fca => TotalAggregate = fca);
            FSItems.Insert(_storeSubject);

            _storeSubject.Connect();
        }
Ejemplo n.º 20
0
        public TimeService(IScheduler scheduler)
        {
            this.scheduler = scheduler;

            previousSecondLocalDateTime = CurrentDateTime.ToLocalTime();
            midnightSubject             = new Subject <DateTimeOffset>();

            CurrentDateTimeObservable =
                Observable
                .Interval(TimeSpan.FromSeconds(1), scheduler)
                .Select(_ => CurrentDateTime)
                .Do(tickOnMidnight)
                .Publish();

            MidnightObservable = midnightSubject.AsObservable().Publish();

            disposable.Add(CurrentDateTimeObservable.Connect());
            disposable.Add(MidnightObservable.Connect());
        }
Ejemplo n.º 21
0
        public MinioRulesDriver(IRulesClient rulesClient, MinioRulesDriverSettings settings, ILogger logger = null, IScheduler scheduler = null)
        {
            logger    = logger ?? NullLogger.Instance;
            scheduler = scheduler ?? DefaultScheduler.Instance;

            _pipeline = Observable.Create <Dictionary <string, RuleDefinition> >(async(sub, ct) =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        var latestVersion = await rulesClient.GetVersion(ct);
                        LastCheckTime     = scheduler.Now.UtcDateTime;
                        if (latestVersion != CurrentLabel)
                        {
                            var ruleset = await rulesClient.GetRuleset(latestVersion, ct);
                            sub.OnNext(ruleset);
                            CurrentLabel = latestVersion;
                        }
                        await Observable.Return(Unit.Default).Delay(settings.SampleInterval, scheduler);
                    }
                }
                catch (Exception ex)
                {
                    sub.OnError(ex);
                }
            })
                        .SubscribeOn(scheduler)
                        .Catch((Exception exception) =>
            {
                logger.LogWarning(exception, "Failed to update rules");
                return(Observable.Empty <Dictionary <string, RuleDefinition> >()
                       .Delay(settings.FailureDelay));
            })
                        .Repeat()
                        .Replay(1);

            _subscription = new CompositeDisposable(
                _pipeline.Subscribe(rules => OnRulesChange?.Invoke(rules)),
                _pipeline.Connect()
                );
        }
Ejemplo n.º 22
0
    void Start()
    {
        //var originalSubject = new Subject<string>();

        //IConnectableObservable<string> appendStringObservable = originalSubject
        //    .Scan((previous, current) => previous + " " + current)
        //    .Last()
        //    //Hot変換する
        //    .Publish();

        //// IConnectableObservable.Connect()を呼ぶと、Subscribe()実行される (Hot変換実行)
        //var disposable = appendStringObservable.Connect();

        //originalSubject.OnNext("I");
        //originalSubject.OnNext("have");

        //appendStringObservable.Subscribe(x => Debug.Log(x));

        //originalSubject.OnNext("a");
        //originalSubject.OnNext("pen");
        //originalSubject.OnCompleted();

        //originalSubject.Dispose();

        var subject    = new Subject <int>();
        var subSubject = new Subject <int>();

        IConnectableObservable <int> doObservable = subject
                                                    .Do(x => Debug.Log(x))
                                                    //Hot変換
                                                    .Publish();

        //Hot変換実行
        doObservable.Connect();

        subject.OnNext(0);
        doObservable.Subscribe(subSubject);
        subject.OnNext(1);
        subSubject.Subscribe(x => Debug.Log("Sub; " + x));
        subject.OnNext(2);
        subSubject.OnNext(3);
    }
Ejemplo n.º 23
0
        public static IObservable <TSource> Prime <TSource>(
            this IConnectableObservable <TSource> source,
            Action <IDisposable> whenConnected)
        {
            Contract.Requires(source != null);
            Contract.Requires(whenConnected != null);
            Contract.Ensures(Contract.Result <IObservable <TSource> >() != null);

            object gate    = new object();
            bool   isFirst = true;

            return(Observable.Create <TSource>(
                       observer =>
            {
                var subscription = source.Subscribe(observer);

                lock (gate)
                {
                    if (isFirst)
                    {
                        isFirst = false;

                        var connection = source.Connect();

                        whenConnected(Disposable.Create(() =>
                        {
                            lock (gate)
                            {
                                if (!isFirst)
                                {
                                    connection.Dispose();

                                    isFirst = true;
                                }
                            }
                        }));
                    }
                }

                return subscription;
            }));
        }
        public ConnectionStatusMonitor(IEventStoreConnection eventStoreConnection)
        {
            _eventStoreConnection = eventStoreConnection;
            _isConnected          = new BehaviorSubject <bool>(false);


            var connected = Observable.FromEventPattern <ClientConnectionEventArgs>(h => _eventStoreConnection.Connected += h, h => _eventStoreConnection.Connected -= h).Select(_ =>
            {
                return(ConnectionStatus.Connected);
            });

            var disconnected = Observable.FromEventPattern <ClientConnectionEventArgs>(h => _eventStoreConnection.Disconnected += h, h => _eventStoreConnection.Disconnected -= h).Select(_ =>
            {
                return(ConnectionStatus.Disconnected);
            });

            var reconnecting = Observable.FromEventPattern <ClientReconnectingEventArgs>(h => _eventStoreConnection.Reconnecting += h, h => _eventStoreConnection.Reconnecting -= h).Select(_ =>
            {
                return(ConnectionStatus.Connecting);
            });

            var closed = Observable.FromEventPattern <ClientClosedEventArgs>(h => _eventStoreConnection.Closed += h, h => _eventStoreConnection.Closed -= h).Select(arg =>
            {
                return(ConnectionStatus.Closed);
            });

            var errorOccurred = Observable.FromEventPattern <ClientErrorEventArgs>(h => _eventStoreConnection.ErrorOccurred += h, h => _eventStoreConnection.ErrorOccurred -= h).Select(arg =>
            {
                return(ConnectionStatus.ErrorOccurred);
            });

            var authenticationFailed = Observable.FromEventPattern <ClientAuthenticationFailedEventArgs>(h => _eventStoreConnection.AuthenticationFailed += h, h => _eventStoreConnection.AuthenticationFailed -= h).Select(arg =>
            {
                return(ConnectionStatus.AuthenticationFailed);
            });

            _connectionInfoChanged = Observable.Merge(connected, disconnected, reconnecting, closed, errorOccurred, authenticationFailed)
                                     .Scan(ConnectionInfo.Initial, UpdateConnectionInfo)
                                     .Replay(1);

            _cleanup = _connectionInfoChanged.Connect();
        }
Ejemplo n.º 25
0
        public DiagnosticsService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null)
        {
            _taskPoolScheduler   = taskPoolScheduler ?? TaskPoolScheduler.Default;
            _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current;

            _countersObservable = Observable.Create <Counters>(x => CreateCounters(x))
                                  .SubscribeOn(_taskPoolScheduler)
                                  .Replay(1);

            _assemblyObservable = AssemblyLoaded()
                                  .SubscribeOn(_taskPoolScheduler)
                                  .Merge(Observable.Return(AppDomain.CurrentDomain.GetAssemblies()).SelectMany(x => x))
                                  .Replay();

            _disposable = new CompositeDisposable
            {
                _countersObservable.Connect(),
                    _assemblyObservable.Connect()
            };
        }
Ejemplo n.º 26
0
        private void ConnectCountersObservable()
        {
            if (_countersConnected)
            {
                return;
            }

            lock (_sync)
            {
                if (_countersConnected)
                {
                    return;
                }

                var disposable = _countersObservable.Connect();
                _disposable.Add(disposable);

                _countersConnected = true;
            }
        }
Ejemplo n.º 27
0
        public TradeService(ILogger logger, TradeGenerator tradeGenerator, ISchedulerProvider schedulerProvider)
        {
            _logger            = logger;
            _tradeGenerator    = tradeGenerator;
            _schedulerProvider = schedulerProvider;

            //emulate a trade service which asynchronously
            IConnectableObservable <IChangeSet <Trade, long> > tradesData = GenerateTradesAndMaintainCache().Publish();

            //call AsObservableCache() so the cache can be directly exposed
            All = tradesData.AsObservableCache();

            //create a derived cache
            Live = tradesData.Filter(trade => trade.Status == TradeStatus.Live).AsObservableCache();

            //log changes
            IDisposable loggerWriter = LogChanges();

            _cleanup = new CompositeDisposable(All, tradesData.Connect(), loggerWriter);
        }
Ejemplo n.º 28
0
        //ストリーミング
        private async void streamingtest()
        {
            try {
                tweet2    = ViewModel2.TweetTimeline;
                sm_stream = tokens.Streaming.UserAsObservable().Publish();
                sm_stream.OfType <StatusMessage>().Subscribe(x => streamLoad(x));

                disposable = sm_stream.Connect();
                //testBlock.Text = "接続中です";
                var xx       = ViewModel.streamCount();
                int tw_count = int.Parse(xx);
                await Task.Delay(tw_count * 60000);

                disposable.Dispose();
                streamButton.IsChecked = false;
                //testBlock.Text = "接続終了";
            }
            catch (Exception ex)
            { }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates a collection of target operations for items to be published
        /// </summary>
        protected override IObservable <ICandidateOperation> CreateTargetOperationsStream(DateTime started, IPublishCandidateSource publishCandidateSource, IPublishValidator validator, PublishOptions jobOptions, IObservable <CandidateValidationContext> publishStream, IItemIndexService targetIndex, ITestableContentRepository testableContentRepository, IMediaRepository targetMediaRepository, IRequiredPublishFieldsResolver requiredPublishFieldsResolver, CancellationTokenSource errorSource, Guid targetId)
        {
            IObservable <CandidateValidationTargetContext> processingStream1 = this.CreateTargetProcessingStream(started, publishCandidateSource, validator, jobOptions, publishStream, targetIndex, testableContentRepository, targetMediaRepository, this._requiredPublishFieldsResolver, errorSource, targetId);
            RelatedNodesSourceProducer nodesSourceProducer = new RelatedNodesSourceProducer(processingStream1.Where <CandidateValidationTargetContext>((Func <CandidateValidationTargetContext, bool>)(ctx => ctx.IsValid)).Select <CandidateValidationTargetContext, ValidCandidateTargetContext>((Func <CandidateValidationTargetContext, ValidCandidateTargetContext>)(ctx => ctx.AsValid())), publishCandidateSource, validator, this._options.RelatedItemBatchSize, jobOptions.RelatedItems, jobOptions.GetDetectCloneSources(), errorSource, this._logger);
            IObservable <CandidateValidationTargetContext>            processingStream2 = this.CreateTargetProcessingStream(started, publishCandidateSource, validator, jobOptions, (IObservable <CandidateValidationContext>)nodesSourceProducer, targetIndex, testableContentRepository, targetMediaRepository, this._requiredPublishFieldsResolver, errorSource, targetId);
            IConnectableObservable <CandidateValidationTargetContext> source            = processingStream1.Merge <CandidateValidationTargetContext>(processingStream2).Publish <CandidateValidationTargetContext>();

            source.Connect();
            UpdatedCandidatesOperationsProducer          operationsProducer1   = new UpdatedCandidatesOperationsProducer(source.Where <CandidateValidationTargetContext>((Func <CandidateValidationTargetContext, bool>)(ctx => ctx.IsValid)).Select <CandidateValidationTargetContext, ValidCandidateTargetContext>((Func <CandidateValidationTargetContext, ValidCandidateTargetContext>)(ctx => ctx.AsValid())), started, errorSource, this._loggerFactory.CreateLogger <UpdatedCandidatesOperationsProducer>());
            MediaOperationsProducer                      operationsProducer2   = new MediaOperationsProducer(source.Where <CandidateValidationTargetContext>((Func <CandidateValidationTargetContext, bool>)(ctx => ctx.IsValid)).Select <CandidateValidationTargetContext, ValidCandidateTargetContext>((Func <CandidateValidationTargetContext, ValidCandidateTargetContext>)(ctx => ctx.AsValid())), targetMediaRepository, requiredPublishFieldsResolver.MediaFieldsIds, started, this._options.MediaBatchSize, errorSource, this._loggerFactory.CreateLogger <MediaOperationsProducer>());
            IConnectableObservable <ICandidateOperation> connectableObservable = Observable.Merge <ICandidateOperation>(new IObservable <ICandidateOperation>[3]
            {
                (IObservable <ICandidateOperation>) new DeletedCandidateOperationsProducer(source.Where <CandidateValidationTargetContext>((Func <CandidateValidationTargetContext, bool>)(ctx => !ctx.IsValid)).Select <CandidateValidationTargetContext, Guid>((Func <CandidateValidationTargetContext, Guid>)(ctx => ctx.AsInvalid().Id)), targetIndex, started, this._options.DeletedItemsBatchSize, errorSource, this._sourceName, this._loggerFactory.CreateLogger <DeletedCandidateOperationsProducer>()),
                (IObservable <ICandidateOperation>)operationsProducer1,
                (IObservable <ICandidateOperation>)operationsProducer2
            }).Publish <ICandidateOperation>();

            connectableObservable.Connect();
            return((IObservable <ICandidateOperation>)connectableObservable);
        }
Ejemplo n.º 30
0
        private static IObservable <uint> Frames(Auto.ISource autoSource, Mqtt.ISource mqttSource)
        {
            IObservable <uint>            autoFrames           = autoSource.Create().Publish().RefCount();
            IObservable <uint>            mqttFrames           = mqttSource.Create().Publish().RefCount();
            IConnectableObservable <uint> mqttFramesWithReplay = mqttFrames.Replay(1);

            var mqttFrameTimeout = mqttFrames
                                   .Timeout(TimeSpan.FromSeconds(10))
                                   .IgnoreElements()
                                   .Materialize()
                                   .Where(notification => notification.Kind == NotificationKind.OnError);

            var autoFramesUntilMqttFrames = autoFrames.TakeUntil(mqttFrames);
            var mqttFramesUntilTimeout    = mqttFramesWithReplay.TakeUntil(mqttFrameTimeout);

            return(Observable.Using(
                       () => mqttFramesWithReplay.Connect(),
                       _ => Observable.Defer(() => Observable.Concat(autoFramesUntilMqttFrames, mqttFramesUntilTimeout)).Repeat()
                       ));
        }
Ejemplo n.º 31
0
        /// <summary>
        /// publish is used to convert Cold =====> Hot
        /// </summary>
        private static void TestPublish()
        {
            // what "Publish" returns is just a proxy, or say, a subject, which serves
            // both as Observer (to original cold observable) and Observable (to observer connects to it)
            IConnectableObservable <long> proxy = Observable.Interval(TimeSpan.FromSeconds(1)).Publish();

            // the proxy subscribe on the original source cold observable, data production starts
            IDisposable connection = proxy.Connect();

            // when the first real observer connects, it already cannot receive 0 anymore
            Helper.Pause("subscribe 1st");
            IDisposable subscription1 = proxy.Subscribe(new ConsolePrintObserver <long>("one"));

            Helper.Pause("subscribe 2nd");
            IDisposable subscription2 = proxy.Subscribe(new ConsolePrintObserver <long>("two", ConsoleColor.Magenta));

            // since proxy is unsubscribed, all its follower will not receive any data any more
            Helper.Pause("disconnect");
            connection.Dispose();
        }
        public ConnectionStatusMonitor(IEventStoreConnection connection)
        {
            var connectedChanged = Observable.FromEventPattern <ClientConnectionEventArgs>(h => connection.Connected += h,
                                                                                           h => connection.Connected -= h)
                                   .Select(_ => ConnectionStatus.Connected);

            var disconnectedChanged = Observable.FromEventPattern <ClientConnectionEventArgs>(h => connection.Disconnected += h,
                                                                                              h => connection.Disconnected -= h)
                                      .Select(_ => ConnectionStatus.Disconnected);

            var reconnectingChanged = Observable.FromEventPattern <ClientReconnectingEventArgs>(h => connection.Reconnecting += h,
                                                                                                h => connection.Reconnecting -= h)
                                      .Select(_ => ConnectionStatus.Connecting);

            _connectionInfoChanged = Observable.Merge(connectedChanged, disconnectedChanged, reconnectingChanged)
                                     .Scan(ConnectionInfo.Initial, UpdateConnectionInfo)
                                     .StartWith(ConnectionInfo.Initial)
                                     .Replay(1);

            _connection = _connectionInfoChanged.Connect();
        }
Ejemplo n.º 33
0
        private static void CheckReplayable(Func <IObservable <long>, IConnectableObservable <long> > proxyFactory)
        {
            IObservable <long>            source = Observable.Interval(TimeSpan.FromSeconds(1));
            IConnectableObservable <long> proxy  = proxyFactory(source);

            using (proxy.Connect())
            {
                Helper.Pause("subscribe 1st");
                proxy.Subscribe(new ConsolePrintObserver <long>("1st"));

                Helper.Pause("subscribe 2nd");
                proxy.Subscribe(new ConsolePrintObserver <long>("2nd", ConsoleColor.Green));

                Helper.Pause("disconnect");
            }

            Helper.Pause("subscribe after disconnect");
            proxy.Subscribe(new ConsolePrintObserver <long>("late", ConsoleColor.Red));

            Console.WriteLine("**************** END ****************");
        }
        public ConnectionStatusMonitor(IEventStoreConnection connection)
        {
            var connectedChanged = Observable.FromEventPattern<ClientConnectionEventArgs>(h => connection.Connected += h,
                                                                                          h => connection.Connected -= h)
                                             .Select(_ => ConnectionStatus.Connected);

            var disconnectedChanged = Observable.FromEventPattern<ClientConnectionEventArgs>(h => connection.Disconnected += h,
                                                                                             h => connection.Disconnected -= h)
                                                .Select(_ => ConnectionStatus.Disconnected);

            var reconnectingChanged = Observable.FromEventPattern<ClientReconnectingEventArgs>(h => connection.Reconnecting += h,
                                                                                               h => connection.Reconnecting -= h)
                                                .Select(_ => ConnectionStatus.Connecting);

            _connectionInfoChanged = Observable.Merge(connectedChanged, disconnectedChanged, reconnectingChanged)
                                               .Scan(ConnectionInfo.Initial, UpdateConnectionInfo)
                                               .StartWith(ConnectionInfo.Initial)
                                               .Replay(1);

            _connection = _connectionInfoChanged.Connect();
        }
Ejemplo n.º 35
0
        public void ValueDependentExperiment()
        {
            IObservable <double> source = Observable.Interval(TimeSpan.FromSeconds(.5))
                                          .Select(v => (double)++v)
                                          .Take(10);

            IConnectableObservable <Either <double, double> > sourceWithProgress =
                source
                .Pair(value => value * 10 / 100)
                .Publish();

            IObservable <double> progressOnly = sourceWithProgress.TakeRight();
            IObservable <double> resultOnly   = sourceWithProgress.TakeLeft().TakeLast(1);

            using (progressOnly.Subscribe(ConsoleOutputFormat(Text.Progress, "{0,5:P0}")))
                using (resultOnly.Subscribe(ConsoleOutput(Text.Result)))
                    using (sourceWithProgress.Connect())
                    {
                        WaitForKey();
                    }
        }
Ejemplo n.º 36
0
        public BluetoothProfileActivator(IBluetoothService bluetoothService,
            IPersonalizationSettings personalizationSettings,
            ISchedulerProvider schedulerProvider,
            ILoggerFactory loggerFactory)
        {
            _bluetoothService = bluetoothService;
            _personalizationSettings = personalizationSettings;
            _schedulerProvider = schedulerProvider;
            _logger = loggerFactory.CreateLogger(GetType());
            _bluetoothEventLoop = _schedulerProvider.CreateEventLoopScheduler("BluetoothActivator");
            _logger.Verbose("BluetoothProfileActivator.ctor();");

            _profileActivated = _bluetoothService.IdentitiesActivated(_bluetoothEventLoop)
                .Retry()
                .Repeat()
                .Log(_logger, "IdentitiesActivated")
                .Select(Translate)
                .Publish();

            //HACK: Avoid work in the ctor. Can be smart here using SelectMany on the IsEnabled + Connecting when ProfileActivated is subscribed to. -LC
            if (_bluetoothService.IsSupported && IsEnabled)
                _connection.Disposable = _profileActivated.Connect();
        }
        public EmbeddedEventStoreConnectionFactory()
        {
            var noIp = new IPEndPoint(IPAddress.None, 0);

            _vnode = EmbeddedVNodeBuilder.AsSingleNode()
                .RunInMemory()
                .WithExternalTcpOn(noIp)
                .WithInternalTcpOn(noIp)
                .WithExternalHttpOn(noIp)
                .WithInternalHttpOn(noIp)
                .Build();

            _status = Observable.FromEventPattern<VNodeStatusChangeArgs>(
                h => _vnode.NodeStatusChanged += h,
                h => _vnode.NodeStatusChanged -= h)
                .Select(e => e.EventArgs.NewVNodeState)
                .Log(new ConsoleLogger(), "VNode.State")
                .Publish(VNodeState.Unknown);

            _statusSubscription.Disposable = _status.Connect();

            _vnode.Start();
            _conn = EmbeddedEventStoreConnection.Create(_vnode);
        }
Ejemplo n.º 38
0
        public async Task LoginAsync(UserStatus initialStatus = UserStatus.Online)
        {

            await @lock.WriterLockAsync();

            try
            {

                if (IsLoggedIn)
                    return;

                IConnection connection = null;
                ConnectionStream stream = null;
                CommandReader reader = null;
                CommandWriter writer = null;
                ResponseTracker responseTracker = null;
                IConnectableObservable<Command> commands = null;
                IDisposable commandsDisposable = null;

                int transferCount = 0;

                SocketEndPoint endPoint = SocketEndPoint.Parse("messenger.hotmail.com:1863");

                string authTicket = null;

                while (authTicket == null)
                {

                    connection = new SocketConnection();

                    await connection.ConnectAsync(endPoint);

                    stream = new ConnectionStream(connection);

                    writer = new CommandWriter(stream);
                    reader = new CommandReader(stream, new Dictionary<string, Type> {
                        { "VER", typeof(VersionCommand) },
                        { "CVR", typeof(ClientVersionCommand) },
                        { "USR", typeof(AuthenticateCommand) },
                        { "XFR", typeof(TransferCommand) },
                        { "SYN", typeof(SynchronizeCommand) },
                        { "SBS", typeof(SbsCommand) },
                        { "MSG", typeof(MessageCommand) },
                        { "LST", typeof(UserCommand) },
                        { "LSG", typeof(GroupCommand) },
                        { "BPR", typeof(UserPropertyCommand) },
                        { "BLP", typeof(PrivacySettingCommand) },
                        { "GTC", typeof(PrivacySettingCommand) },
                        { "CHG", typeof(ChangeStatusCommand) },
                        { "UBX", typeof(BroadcastCommand) },
                        { "PRP", typeof(LocalPropertyCommand) },
                        { "NLN", typeof(UserOnlineCommand) },
                        { "ILN", typeof(InitialUserOnlineCommand) },
                        { "FLN", typeof(UserOfflineCommand) },
                        { "UUX", typeof(SendBroadcastCommand) },
                        { "NOT", typeof(NotificationCommand) },
                        { "QNG", typeof(PingCommand) },
                        { "CHL", typeof(ChallengeCommand) },
                        { "ADC", typeof(AddContactCommand) },
                        { "REM", typeof(RemoveContactCommand) },
                        { "ADG", typeof(AddGroupCommand) },
                        { "RMG", typeof(RemoveGroupCommand) },
                        { "REG", typeof(RenameGroupCommand) },  
                        { "QRY", typeof(AcceptChallengeCommand) },  
                        { "RNG", typeof(RingCommand) },
                        { "SBP", typeof(ChangeUserPropertyCommand) },
                        { "IMS", typeof(EnableIMCommand) },
                    });
                    
                    commands = reader.GetReadObservable().Publish();
                    responseTracker = new ResponseTracker(writer, commands);

                    commandsDisposable = commands.Connect();

                    var versionCommand = new VersionCommand("MSNP12");
                    var versionResponse = await responseTracker.GetResponseAsync<VersionCommand>(versionCommand, defaultTimeout);

                    if (versionResponse.Versions.Length == 0)
                        throw new ProtocolNotAcceptedException();

                    var clientVersionCommand = new ClientVersionCommand
                    {
                        LocaleId = "0x0409",
                        OsType = "winnt",
                        OsVersion = "5.0",
                        Architecture = "1386",
                        LibraryName = "MSMSGS",
                        ClientVersion = "5.0.0482",
                        ClientName = "WindowsMessenger",
                        LoginName = credentials.LoginName,
                    };

                    await responseTracker.GetResponseAsync<ClientVersionCommand>(clientVersionCommand, defaultTimeout);

                    var userCommand = new AuthenticateCommand("TWN", "I", credentials.LoginName);
                    var userResponse = await responseTracker.GetResponseAsync(userCommand, new Type[] { typeof(AuthenticateCommand), typeof(TransferCommand) }, defaultTimeout);

                    if (userResponse is AuthenticateCommand)
                    {
                        authTicket = (userResponse as AuthenticateCommand).Argument;
                    }

                    else if (userResponse is TransferCommand)
                    {
                        
                        TransferCommand transferResponse = userResponse as TransferCommand;

                        if (transferCount > 3)
                            throw new InvalidOperationException("The maximum number of redirects has been reached.");

                        transferCount++;

                        endPoint = SocketEndPoint.Parse(transferResponse.Host);

                        commandsDisposable.Dispose();

                        reader.Close();
                        writer.Close();
                        connection.Dispose();

                    }

                }

                PassportAuthentication auth = new PassportAuthentication();

                string authToken = await auth.GetToken(credentials.LoginName, credentials.Password, authTicket);

                var authCommand = new AuthenticateCommand("TWN", "S", authToken);
                var authResponse = await responseTracker.GetResponseAsync<AuthenticateCommand>(authCommand, defaultTimeout);

                var synCommand = new SynchronizeCommand(syncTimeStamp1 ?? "0", syncTimeStamp2 ?? "0");
                var synResponse = await responseTracker.GetResponseAsync<SynchronizeCommand>(synCommand, defaultTimeout);

                IDisposable syncCommandsSubscription = null;
                List<Command> syncCommands = null;

                if (synResponse.TimeStamp1 != syncTimeStamp1 || synResponse.TimeStamp2 != syncTimeStamp2)
                {

                    syncCommands = new List<Command>();

                    Type[] syncTypes = new Type[] { 
                        typeof(MessageCommand), 
                        typeof(UserCommand), 
                        typeof(GroupCommand), 
                        typeof(LocalPropertyCommand), 
                        typeof(PrivacySettingCommand),
                    };

                    syncCommandsSubscription = commands
                        .Where(c => syncTypes.Contains(c.GetType()))
                        .Catch(Observable.Empty<Command>())
                        .Subscribe(c => syncCommands.Add(c));

                    //if we're expecting users/groups, wait for them before we proceed
                    if (synResponse.UserCount + synResponse.GroupCount > 0)
                    {

                        await commands
                            .Where(c => c is UserCommand || c is GroupCommand)
                            .Take(synResponse.UserCount + synResponse.GroupCount)
                            .Timeout(defaultTimeout);

                    }

                }

                UserCapabilities capabilities = 0;
                MSNObject displayPicture = MSNObject.Empty;

                if (LocalUser != null)
                {
                    capabilities = LocalUser.Capabilities;
                    displayPicture = LocalUser.DisplayPicture;
                }

                Command changeStatusCommand = new ChangeStatusCommand(User.StatusToString(UserStatus.Online), (uint)capabilities, displayPicture != MSNObject.Empty ? displayPicture.ToString() : "0");
                await responseTracker.GetResponseAsync(changeStatusCommand, defaultTimeout);

                if (syncCommandsSubscription != null)
                    syncCommandsSubscription.Dispose();

                this.writer = writer;
                this.reader = reader;
                this.stream = stream;
                this.connection = connection;
                this.responseTracker = responseTracker;
                this.commands = commands;
                this.commandsDisposable = commandsDisposable;

                if (LocalUser == null)
                {
                    LocalUser = new LocalUser(this, credentials.LoginName);
                    userCache.Add(credentials.LoginName, new WeakReference(LocalUser));
                }

                LocalUser.Status = initialStatus;

                SyncEvents syncEvents = null;

                if (syncCommands != null)
                {
                    syncTimeStamp1 = synResponse.TimeStamp1;
                    syncTimeStamp2 = synResponse.TimeStamp2;

                    syncEvents = ProcessSyncCommands(syncCommands);
                }

                var commandsSafe = commands
                    .Catch<Command, ConnectionErrorException>(tx => Observable.Empty<Command>());

                commandsSafe.OfType<MessageCommand>().Subscribe(cmd => HandleMessages(cmd, connection));
                commandsSafe.OfType<RingCommand>().Subscribe(cmd => HandleRings(cmd, connection));
                commandsSafe.OfType<BroadcastCommand>().Subscribe(cmd => HandleBroadcasts(cmd, connection));
                commandsSafe.OfType<NotificationCommand>().Subscribe(cmd => HandleNotifications(cmd, connection));
                commandsSafe.OfType<AddContactCommand>().Subscribe(cmd => HandleNewUsers(cmd, connection));
                commandsSafe.OfType<OutCommand>().Subscribe(cmd => HandleOut(cmd, connection));
                commandsSafe.OfType<ChallengeCommand>().Subscribe(cmd => HandleChallenges(cmd, connection));
                commandsSafe.OfType<UserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<InitialUserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<UserOfflineCommand>().Subscribe(cmd => HandleOfflineUsers(cmd, connection));

                connection.Error += connection_Error;

                IsLoggedIn = true;

                OnLoggedIn();

                OnUserStatusChanged(new UserStatusEventArgs(LocalUser, initialStatus, UserStatus.Offline, true));

                if (syncEvents != null)
                    RaiseSyncEvents(syncEvents);


            }
            finally
            {
                @lock.WriterRelease();
            }

        }
Ejemplo n.º 39
0
        KanColleGame()
        {
            Proxy = new GameProxy();
            Headquarter = new Headquarter();
            QuestTable = new Table<Quest>();

            Fleets = new Table<Fleet>();
            Ships = new Table<Ship>();
            Equipments = new Table<Equipment>();

            ObservablePropertyChanged = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                rpHandler => PropertyChanged += rpHandler,
                rpHandler => PropertyChanged -= rpHandler)
                .Select(r => r.EventArgs.PropertyName)
                .Publish();
            r_PropertyChangedSubscriptions = ObservablePropertyChanged.Connect();
        }
        public DiagnosticsService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null)
        {
            _taskPoolScheduler = taskPoolScheduler ?? TaskPoolScheduler.Default;
            _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current;

            _countersObservable = Observable.Create<Counters>(x => CreateCounters(x))
                .SubscribeOn(_taskPoolScheduler)
                .Replay(1);

            _assemblyObservable = AssemblyLoaded()
                .SubscribeOn(_taskPoolScheduler)
                .Merge(Observable.Return(AppDomain.CurrentDomain.GetAssemblies()).SelectMany(x => x))
                .Replay();

            _disposable = new CompositeDisposable
                          {
                              _countersObservable.Connect(),
                              _assemblyObservable.Connect()
                          };
        }
Ejemplo n.º 41
0
        void InitializeCommunicator(int rpHostProcessID)
        {
            r_Communicator = new MemoryMappedFileCommunicator($"Sakuno/HeavenlyWind({rpHostProcessID})", 4096);
            r_Communicator.ReadPosition = 0;
            r_Communicator.WritePosition = 2048;

            r_Messages = r_Communicator.GetMessageObservable().ObserveOnDispatcher().Publish();
            r_Messages.Connect();

            r_Communicator.StartReader();

            r_Messages.Subscribe(CommunicatorMessages.ClearCache, _ => r_BrowserProvider?.ClearCache(false));
            r_Messages.Subscribe(CommunicatorMessages.ClearCacheAndCookie, _ => r_BrowserProvider?.ClearCache(true));

            r_Messages.Subscribe(CommunicatorMessages.GoBack, _ => r_Browser?.GoBack());
            r_Messages.Subscribe(CommunicatorMessages.GoForward, _ => r_Browser?.GoForward());
            r_Messages.Subscribe(CommunicatorMessages.Navigate, rpUrl => r_Browser?.Navigate(rpUrl));
            r_Messages.Subscribe(CommunicatorMessages.Refresh, _ => r_Browser?.Refresh());

            r_Messages.Subscribe(CommunicatorMessages.SetZoom, r =>
            {
                r_Zoom = double.Parse(r);
                r_Browser?.SetZoom(r_Zoom);
                r_Communicator.Write(CommunicatorMessages.InvalidateArrange);
            });

            r_Messages.Subscribe(CommunicatorMessages.ResizeBrowserToFitGame, _ =>
            {
                r_Container.Width = GameConstants.GameWidth * r_Zoom / DpiUtil.ScaleX / DpiUtil.ScaleX;
                r_Container.Height = GameConstants.GameHeight * r_Zoom / DpiUtil.ScaleY / DpiUtil.ScaleY;
                r_Communicator.Write(CommunicatorMessages.InvalidateArrange);
            });

            InitializeScreenshotMessagesSubscription();

        }
Ejemplo n.º 42
0
 static TimerNotifier()
 {
     timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1)).Publish();
     timer.Connect();
 }