コード例 #1
1
        public static IDisposable HandleClients(TcpListener listener, Func<TcpClient, string, Task> handleClientAccessPolicy, string policyResponse)
        {
            listener.Start();

            var disposableHandler = ThreadPoolScheduler.Instance.ScheduleAsync(async (scheduler, ct) =>
            {
                var disposable = new BooleanDisposable();

                while (!disposable.IsDisposed)
                {
                    var client = await listener.AcceptTcpClientAsync();
                    await handleClientAccessPolicy(client, policyResponse);
                    await scheduler.Yield();
                }

                return disposable;
            });

            var compositeDisposable = new CompositeDisposable();

            compositeDisposable.Add(Disposable.Create(() => listener.Stop()));
            compositeDisposable.Add(disposableHandler);

            return compositeDisposable;
        }
コード例 #2
0
        public IObservable<string> Receive(byte[] buffer, IScheduler scheduler)
        {
            return Observable.Create<string>(observer =>
                {
                    var disposable = new CompositeDisposable();
                    this.connectionToken.SocketEvent.SetBuffer(buffer, 0, buffer.Length);
                    var subject = new Subject<Unit>();

                    var disposableEventSubscription = connectionToken.SocketEvent.Completed.Subscribe(_ =>
                    {
                        if (SendNotificationToObserver(observer, connectionToken.SocketEvent))
                        {
                            subject.OnNext(Unit.Default);
                        }
                    });

                    var disposableActions = subject.ObserveOn(scheduler).Subscribe(_ =>
                    {
                        if (!connectionToken.Socket.ReceiveAsync(connectionToken.SocketEvent))
                        {
                            if (SendNotificationToObserver(observer, connectionToken.SocketEvent))
                            {
                                subject.OnNext(Unit.Default);
                            }
                        }
                    });

                    subject.OnNext(Unit.Default);

                    disposable.Add(disposableEventSubscription);
                    disposable.Add(disposableActions);

                    return disposable;
                });
        }
コード例 #3
0
ファイル: BehaviorLogger.cs プロジェクト: upsilon/StarryEyes
        internal static void Initialize()
        {
            if (!Setting.IsLoaded || !Setting.IsBehaviorLogEnabled.Value)
            {
                return;
            }

            var disposables = new CompositeDisposable();
            try
            {
                var file = new FileStream(
                    Path.Combine(App.ConfigurationDirectoryPath, App.BehaviorLogFileName),
                    FileMode.Append,
                    FileAccess.Write,
                    FileShare.ReadWrite);
                var writer = new StreamWriter(file) { AutoFlush = true };
                _writer = writer.WriteLine;
                disposables.Add(Disposable.Create(() => _writer = null));
                disposables.Add(writer);
                disposables.Add(file);
            }
            finally
            {
                _disposable = disposables;
            }
        }
コード例 #4
0
        public IObservable<string> Receive(Socket connectedSocket, SocketAsyncEventArgs socketEventArgs, IScheduler scheduler, byte[] buffer)
        {
            if (connectedSocket == null)
                throw new ArgumentNullException("connectedSocket");

            if (socketEventArgs == null)
                throw new ArgumentNullException("socketEventArgs");

            return Observable.Create<string>(observer =>
            {
                var disposable = new CompositeDisposable();

                var disposableEventSubscription = socketEventArgs.CompletedObservable().ObserveOn(scheduler).Subscribe(_ =>
                {
                    SendNotificationToObserver(observer, socketEventArgs);
                });

                var disposableActions = scheduler.Schedule(() =>
                {
                    socketEventArgs.SetBuffer(buffer, 0, buffer.Length);
                    if (!connectedSocket.ReceiveAsync(socketEventArgs))
                    {
                        SendNotificationToObserver(observer, socketEventArgs);
                    }
                });

                disposable.Add(disposableEventSubscription);
                disposable.Add(disposableActions);

                return disposable;
            });
        }
コード例 #5
0
        public IObservable<Socket> Connect(string host, int port, IScheduler scheduler)
        {
            return Observable.Create<Socket>(observer =>
            {
                var disposable = new CompositeDisposable();

                var socket = socketFactory();
                var socketEvent = socketEventsFactory();

                socketEvent.RemoteEndPoint = new DnsEndPoint(host, port);
                socketEvent.UserToken = socket;

                var disposableEventSubscription = socketEvent.CompletedObservable().ObserveOn(scheduler).Subscribe(_ =>
                {
                    SendNotificationToObserver(observer, socketEvent);
                });

                var disposableActions = scheduler.Schedule(() =>
                {    
                    if (!socket.ConnectAsync(socketEvent))
                    {
                        SendNotificationToObserver(observer, socketEvent);
                    }
                });

                disposable.Add(disposableEventSubscription);
                disposable.Add(disposableActions);

                return disposable;
            });
        }
コード例 #6
0
        public IObservable<Unit> SendMessage(Socket connectedSocket, SocketAsyncEventArgs socketEventArgs, IScheduler scheduler, string message)
        {
            if (connectedSocket == null)
                throw new ArgumentNullException("connectedSocket");

            if (socketEventArgs == null)
                throw new ArgumentNullException("socketEventArgs");

            return Observable.Create<Unit>(observer =>
            {
                var disposable = new CompositeDisposable();
                var buffer = Encoding.UTF8.GetBytes(message);

                var disposableCompletedSubscription = socketEventArgs.CompletedObservable().ObserveOn(scheduler).Subscribe(_ =>
                {
                    SendNotificationToObserver(observer, socketEventArgs);
                });

                var disposableActions = scheduler.Schedule(() =>
                {
                    socketEventArgs.SetBuffer(buffer, 0, buffer.Length);
                    if (!connectedSocket.SendAsync(socketEventArgs))
                    {
                        SendNotificationToObserver(observer, socketEventArgs);
                    }
                });

                disposable.Add(disposableCompletedSubscription);
                disposable.Add(disposableActions);

                return disposable;
            });
        }
コード例 #7
0
        public IObservable<ConnectionToken> BuildConnectionToken(string host, int port, IScheduler scheduler)
        {
            return Observable.Create<ConnectionToken>(observer =>
            {
                var disposable = new CompositeDisposable();

                var socket = socketFactory();
                var socketEvent = socketEventsFactory();

                socketEvent.RemoteEndPoint = new DnsEndPoint(host, port);
                socketEvent.SocketClientAccessPolicyProtocol = System.Net.Sockets.SocketClientAccessPolicyProtocol.Tcp;

                var connectionToken = new ConnectionToken(socket, socketEvent);

                var disposableEventSubscription = socketEvent.Completed.Subscribe(_ =>
                {
                    SendNotificationToObserver(observer, socketEvent, connectionToken);
                });

                var disposableActions = scheduler.Schedule(() =>
                {    
                    if (!socket.ConnectAsync(socketEvent))
                    {
                        SendNotificationToObserver(observer, socketEvent, connectionToken);
                    }
                });

                disposable.Add(disposableEventSubscription);
                disposable.Add(disposableActions);

                return disposable;
            });
        }
コード例 #8
0
        public void SetUp()
        {
            Clock.Reset();

            disposables = new CompositeDisposable
            {
                Disposable.Create(Clock.Reset)
            };

            schedule = GetScheduleDelegate();

            commandsScheduled = new ConcurrentBag<IScheduledCommand>();
            commandsDelivered = new ConcurrentBag<IScheduledCommand>();

            var configuration = new Configuration()
                .TraceScheduledCommands() // trace to console
                .TraceScheduledCommands(
                    onScheduling: _ => { },
                    onScheduled: c => commandsScheduled.Add(c),
                    onDelivering: _ => { },
                    onDelivered: c => commandsDelivered.Add(c));

            Configure(configuration, d => disposables.Add(d));

            disposables.Add(ConfigurationContext.Establish(configuration));
        }
        public void SetUp()
        {
            disposables = new CompositeDisposable();

            Command<Order>.AuthorizeDefault = (order, command) => true;
            configuration = GetConfiguration();
            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
コード例 #10
0
			public IDisposable ShowView(FrameworkElement view) {
				var disp = new CompositeDisposable();
				disp.Add(scheduler.Schedule(() => {
					disp.Add(showView(view));
				}));
				return Disposable.Create(() => {
					scheduler.Schedule(() => {
						disp.Dispose();
					});
				});
			}
コード例 #11
0
        //public IObservable<string> TailV2(IFile file)
        //{
        //    return ObservableFile.WatchLines(file.GetNativePath(), Encoding.Default);
        //}

        public IObservable<string> Tail(IFile file, IScheduler scheduler = null)
        {
            return Observable.Create<string>(subj =>
            {
                var disposable = new CompositeDisposable();
                scheduler = scheduler ?? RxApp.TaskpoolScheduler;
                var abortSignal = new ManualResetEvent(false);

                disposable.Add(Disposable.Create(() => abortSignal.Set()));

                disposable.Add(scheduler.Schedule(abortSignal, (sched, state) =>
                {
                    using (var reader = new StreamReader(
                        file.GetContent().OpenStream(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                    {
                        long lastOffset = reader.BaseStream.Length;
                        if (reader.BaseStream.Length > 0)
                        {
                            // Send the last 10 kb of text to the reader.
                            lastOffset = Math.Max(0, reader.BaseStream.Length - (1024 * 10));
                        }

                        while (!state.WaitOne(100))
                        {
                            // Idle if file hasn't changed.
                            if (reader.BaseStream.Length <= lastOffset)
                            {
                                if (reader.BaseStream.Length < lastOffset)
                                {
                                    lastOffset = reader.BaseStream.Length;
                                }
                                continue;
                            }

                            // Read the data.
                            reader.BaseStream.Seek(lastOffset, SeekOrigin.Begin);
                            var delta = reader.BaseStream.Length - lastOffset;
                            var buffer = new char[delta];
                            reader.ReadBlock(buffer, 0, buffer.Length);

                            // Publish the data.
                            subj.OnNext(new string(buffer));

                            // Update the offset.
                            lastOffset = reader.BaseStream.Position;
                        }
                    }
                    return Disposable.Empty;
                }));

                return disposable;
            });
        }
コード例 #12
0
 public void AddTwice()
 {
     int i = 0;
     var d = new CompositeDisposable ();
     var item = Disposable.Create (() => i++);
     d.Add (item);
     d.Add (item);
     // this results in two items registered.
     Assert.AreEqual (2, d.Count, "#1");
     d.Dispose ();
     // though, since the first disposal takes effect, it never invokes Dispose() on item twice.
     Assert.AreEqual (1, i, "#2");
 }
コード例 #13
0
        /// <summary>
        /// Schedules action to be executed after dueTime.
        /// </summary>
        public IDisposable Schedule(Action action, TimeSpan dueTime)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            var dt = Scheduler.Normalize(dueTime);

            var g = new CompositeDisposable();

            g.Add(ThreadPoolScheduler.Instance.Schedule(() => g.Add(Schedule(action)), dt));

            return g;
        }
コード例 #14
0
ファイル: PrimingLab.cs プロジェクト: ibebbs/Rxx
    public void PrimeExperiment()
    {
      IObservable<long> xs = Observable.Interval(TimeSpan.FromSeconds(1))
        .Do(ConsoleOutput(Text.Generated))
        .Take(3);

      IObservable<long> pruned = xs.PublishLast().Prime();

      for (int r = 0; r < 2; r++)
      {
        using (var subscriptions = new CompositeDisposable())
        {
          for (int s = 0; s < 5; s++)
          {
            Thread.Sleep(TimeSpan.FromSeconds(.4));

            TraceLine(Text.SubscribingFormat, s);

            subscriptions.Add(
              pruned.Subscribe(ConsoleOutput(Text.NamedObserverFormat, s)));
          }

          Thread.Sleep(TimeSpan.FromSeconds(2));
        }
      }
    }
コード例 #15
0
        public void AddAfterDisposal()
        {
            int i1 = 0, i2 = 0;
            var d = new CompositeDisposable ();
            d.Add (Disposable.Create (() => i1++));
            d.Dispose ();
            Assert.AreEqual (1, i1, "#1");
            d.Dispose ();
            Assert.AreEqual (1, i1, "#2"); // no further addition

            d.Add (Disposable.Create (() => i2++));
            Assert.AreEqual (1, i2, "#3");
            d.Dispose ();
            Assert.AreEqual (1, i2, "#4"); // no further addition

            d.Add (Disposable.Create (() => i2++)); // should be immediately disposed
            Assert.AreEqual (2, i2, "#5");
        }
        public void SetUp()
        {
            disposables = new CompositeDisposable();

            Command<Order>.AuthorizeDefault = (order, command) => true;
            EventStoreDbTest.SetConnectionStrings();
            configuration = GetConfiguration();
            disposables.Add(ConfigurationContext.Establish(configuration));
        }
コード例 #17
0
        public static IDisposable DisposeWith(this IDisposable disposable, CompositeDisposable compositeDisposable)
        {
            if (disposable == null)
            {
                return(disposable);
            }

            compositeDisposable?.Add(disposable);
            return(disposable);
        }
        public void SetUp()
        {
            disposables = new CompositeDisposable();

            Command<Order>.AuthorizeDefault = (order, command) => true;
            CommandSchedulerDbContext.NameOrConnectionString =
                @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=ItsCqrsTestsCommandScheduler";
            configuration = GetConfiguration();
            disposables.Add(ConfigurationContext.Establish(configuration));
        }
コード例 #19
0
        public void SetUp()
        {
            Command<Order>.AuthorizeDefault = (order, command) => true;

            disposables = new CompositeDisposable();

            var configuration = new Configuration()
                .UseInMemoryEventStore()
                .UseInMemoryCommandScheduling();
            disposables.Add(ConfigurationContext.Establish(configuration));
        }
コード例 #20
0
		public ModalDialogContext(string title = null) {
			var activeView = new SerialDisposable();
			ModalDialogView dialog = null;// new ModalDialogView();
			var dispatcher = Application.Current.Dispatcher;
			//var dispatcher = dialog.Dispatcher;
			dispatcher.BeginInvoke(() => {
				dialog = new ModalDialogView();
				if (!disposables.IsDisposed) {
					disposables.Add(
						Disposable.Create(
							() => dispatcher.BeginInvoke(
								()=>dialog.Close()
							)
						)
					);
					dialog.Header = title;
					dialog.Owner = Application.Current.MainWindow;
					dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
					dialog.SizeToContent = SizeToContent.WidthAndHeight;
					dialog.ShowInTaskbar = false;
					dialog.ShowDialog();
					activeView.Dispose();
				}
			});
			var presenter = ViewPresenter.Create(view => {
				var disp = new CompositeDisposable();
				activeView.Disposable = disp;
				dispatcher.BeginInvoke(()=>{
					dbg.Assert(dialog != null);
					if (!disp.IsDisposed) {
						dbg.Assert(dialog.Content == null);
						dialog.Content = view;
						var header = NavigationContext.GetTitle(view);
						dialog.Header = header ?? title;
						disp.Add( Disposable.Create(() => {
							dispatcher.BeginInvoke(() => {
								dbg.Assert(dialog.Content == view);
								dialog.Header = title;
								dialog.Content = null;
								var d = view as IDisposable;
								if (d != null) {
									d.Dispose();
								}
							});
						}));
					}
				});
				return disp;
			});
			container.RegisterInstance<IViewPresenter>(presenter);
		}
コード例 #21
0
        public static IDisposable Schedule(this IScheduler scheduler, Action<Action> action)
        {
            // InvokeRec1
            var group = new CompositeDisposable(1);
            var gate = new object();

            Action recursiveAction = null;
            recursiveAction = () => action(() =>
            {
                var isAdded = false;
                var isDone = false;
                var d = default(IDisposable);
                d = scheduler.Schedule(() =>
                {
                    lock (gate)
                    {
                        if (isAdded)
                            group.Remove(d);
                        else
                            isDone = true;
                    }
                    recursiveAction();
                });

                lock (gate)
                {
                    if (!isDone)
                    {
                        group.Add(d);
                        isAdded = true;
                    }
                }
            });

            group.Add(scheduler.Schedule(recursiveAction));

            return group;
        }
コード例 #22
0
        public void SetUp()
        {
            // this is a shim to make sure that the Test.Domain.Ordering.Api assembly is loaded into the AppDomain, otherwise Web API won't discover the controller type
            var controller = new OrderApiController();

            disposables = new CompositeDisposable();

            Command<Order>.AuthorizeDefault = (order, command) => true;

            var configuration = new Configuration()
                .UseInMemoryEventStore()
                .UseInMemoryCommandScheduling();
            disposables.Add(ConfigurationContext.Establish(configuration));
        }
コード例 #23
0
        public void when_Dispose_is_called_then_added_IDisposable_is_disposed()
        {
            var disposables = new CompositeDisposable();

            var eventWasFired = false;

            var disposable = AnonymousDisposable.Create(() => eventWasFired = true);
            disposables.Add(disposable);

            Assert.That(eventWasFired, Is.False);

            disposables.Dispose();

            Assert.That(eventWasFired, Is.True);
        }
コード例 #24
0
        public override void DidReceiveLocalNotification(UILocalNotification localNotification, Action<WKUserNotificationInterfaceType> completionHandler)
        {
            _compositeDisposable.Dispose();
            _compositeDisposable = new CompositeDisposable();

            var trade = GetTrade(localNotification);
            var currencyPair = GetCurrencyPair(localNotification, _priceSubject.AsObservable());

            SetupWormholePriceStream(trade);

            _trader = GetTrader(currencyPair, _priceSubject.AsObservable());
            _compositeDisposable.Add(_trader);

            SetupInterface(trade);
            SetupStreams(_trader);

            completionHandler(WKUserNotificationInterfaceType.Custom);
        }
コード例 #25
0
        public IObservable<IList<string>> IdentitiesActivated(IScheduler scheduler)
        {
            return Observable.Create<IList<string>>(
                o =>
                {
                    if (!IsSupported)
                    {
                        return Observable.Empty<IList<string>>().Subscribe(o);
                        o.OnError(new InvalidOperationException("Bluetooth not currently supported on this device."));
                        return Disposable.Empty;
                    }

                    var resources = new CompositeDisposable();
                    try
                    {
                        var listener = StartBluetoothListener();
                        resources.Add(Disposable.Create(listener.Stop));

                        var subscription = Task.Factory.FromAsync<BluetoothClient>(listener.BeginAcceptBluetoothClient,
                                                                                   listener.EndAcceptBluetoothClient,
                                                                                   null, TaskCreationOptions.None)
                                               .ToObservable()
                                               .Log(_logger, "AcceptBluetoothClient")
                                               .SelectMany(btClient => this.GetIdentities(btClient, scheduler))
                                               .Subscribe(o);

                        resources = new CompositeDisposable(subscription, resources);
                    }
                    catch (Exception ex)
                    {
                        o.OnError(ex);
                    }
                    return resources;
                })
                .Log(_logger, "IdentitiesActivated")
                .SubscribeOn(scheduler);
        }
コード例 #26
0
 public static void DisposeWith(this IDisposable disposable, CompositeDisposable compositeDisposable)
 {
     compositeDisposable.Add(disposable);
 }
コード例 #27
0
 public void Dispose()
 {
     _disposables.Add(Formatting.Formatter.ResetToDefault);
     _disposables.Dispose();
 }
コード例 #28
0
ファイル: MainController.cs プロジェクト: vardars/NBXplorer
        public async Task <IActionResult> ConnectWebSocket(
            string cryptoCode,
            bool includeTransaction        = true,
            CancellationToken cancellation = default(CancellationToken))
        {
            if (!HttpContext.WebSockets.IsWebSocketRequest)
            {
                return(NotFound());
            }

            GetNetwork(cryptoCode);             // Internally check if cryptoCode is correct
            var listenedBlocks      = new ConcurrentDictionary <string, string>();
            var listenedDerivations = new ConcurrentDictionary <(Network, DerivationStrategyBase), DerivationStrategyBase>();

            WebsocketMessageListener server        = new WebsocketMessageListener(await HttpContext.WebSockets.AcceptWebSocketAsync(), _SerializerSettings);
            CompositeDisposable      subscriptions = new CompositeDisposable();

            subscriptions.Add(_EventAggregator.Subscribe <Events.NewBlockEvent>(async o =>
            {
                if (listenedBlocks.ContainsKey(o.CryptoCode))
                {
                    var chain = ChainProvider.GetChain(o.CryptoCode);
                    if (chain == null)
                    {
                        return;
                    }
                    var block = chain.GetBlock(o.BlockId);
                    if (block != null)
                    {
                        await server.Send(new Models.NewBlockEvent()
                        {
                            CryptoCode        = o.CryptoCode,
                            Hash              = block.HashBlock,
                            Height            = block.Height,
                            PreviousBlockHash = block?.Previous.HashBlock
                        });
                    }
                }
            }));
            subscriptions.Add(_EventAggregator.Subscribe <Events.NewTransactionMatchEvent>(async o =>
            {
                var network = Waiters.GetWaiter(o.CryptoCode);
                if (network == null)
                {
                    return;
                }
                if (listenedDerivations.ContainsKey((network.Network.NBitcoinNetwork, o.Match.DerivationStrategy)))
                {
                    var chain = ChainProvider.GetChain(o.CryptoCode);
                    if (chain == null)
                    {
                        return;
                    }
                    var blockHeader = o.BlockId == null ? null : chain.GetBlock(o.BlockId);
                    await server.Send(new Models.NewTransactionEvent()
                    {
                        CryptoCode         = o.CryptoCode,
                        DerivationStrategy = o.Match.DerivationStrategy,
                        BlockId            = blockHeader?.HashBlock,
                        TransactionData    = ToTransactionResult(includeTransaction, chain, new[] { o.SavedTransaction }),
                        Inputs             = o.Match.Inputs,
                        Outputs            = o.Match.Outputs
                    });
                }
            }));
            try
            {
                while (server.Socket.State == WebSocketState.Open)
                {
                    object message = await server.NextMessageAsync(cancellation);

                    switch (message)
                    {
                    case Models.NewBlockEventRequest r:
                        r.CryptoCode = r.CryptoCode ?? cryptoCode;
                        listenedBlocks.TryAdd(r.CryptoCode, r.CryptoCode);
                        break;

                    case Models.NewTransactionEventRequest r:
                        r.CryptoCode = r.CryptoCode ?? cryptoCode;
                        var network = Waiters.GetWaiter(r.CryptoCode)?.Network;
                        if (network == null)
                        {
                            break;
                        }
                        foreach (var derivation in r.DerivationSchemes)
                        {
                            var parsed = new DerivationStrategyFactory(network.NBitcoinNetwork).Parse(derivation);
                            listenedDerivations.TryAdd((network.NBitcoinNetwork, parsed), parsed);
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch when(server.Socket.State != WebSocketState.Open)
            {
            }
            finally { subscriptions.Dispose(); await server.DisposeAsync(cancellation); }
            return(new EmptyResult());
        }
コード例 #29
0
ファイル: DisposableExtensions.cs プロジェクト: drailan/LIFX
 public static void DisposeWith(this IDisposable disposable, CompositeDisposable composite)
 {
     if (composite == null || disposable == null)
         return;
     composite.Add(disposable);
 }
コード例 #30
0
        public void Initialize()
        {
            #region bind events
            CompositeDisposable.Add(
                Observable.FromEvent <bool>(
                    h => MainWindowModel.WindowCommandsDisplayChanged += h,
                    h => MainWindowModel.WindowCommandsDisplayChanged -= h)
                .Subscribe(visible =>
            {
                var offset = visible
                                               ? Interlocked.Increment(ref _visibleCount)
                                               : Interlocked.Decrement(ref _visibleCount);
                ShowWindowCommands = offset >= 0;
            }));
            CompositeDisposable.Add(
                Observable.FromEvent <TaskDialogOptions>(
                    h => MainWindowModel.TaskDialogRequested += h,
                    h => MainWindowModel.TaskDialogRequested -= h)
                .Subscribe(options => this.Messenger.RaiseSafe(() =>
                                                               new TaskDialogMessage(options))));
            CompositeDisposable.Add(
                Observable.FromEvent(
                    h => MainWindowModel.StateStringChanged += h,
                    h => MainWindowModel.StateStringChanged -= h)
                .Subscribe(_ => RaisePropertyChanged(() => StateString)));
            CompositeDisposable.Add(
                Observable.Interval(TimeSpan.FromSeconds(0.5))
                .Subscribe(_ => UpdateStatistics()));
            CompositeDisposable.Add(
                Observable.FromEvent <AccountSelectDescription>(
                    h => MainWindowModel.AccountSelectActionRequested += h,
                    h => MainWindowModel.AccountSelectActionRequested -= h)
                .Subscribe(
                    desc =>
            {
                // ensure close before opening.
                _globalAccountSelectionFlipViewModel.Close();

                _globalAccountSelectionFlipViewModel.SelectedAccounts =
                    desc.SelectionAccounts;
                _globalAccountSelectionFlipViewModel.SelectionReason = "";
                switch (desc.AccountSelectionAction)
                {
                case AccountSelectionAction.Favorite:
                    _globalAccountSelectionFlipViewModel.SelectionReason =
                        "favorite";
                    break;

                case AccountSelectionAction.Retweet:
                    _globalAccountSelectionFlipViewModel.SelectionReason =
                        "retweet";
                    break;
                }
                IDisposable disposable = null;
                disposable             = Observable.FromEvent(
                    h => _globalAccountSelectionFlipViewModel.Closed += h,
                    h => _globalAccountSelectionFlipViewModel.Closed -= h)
                                         .Subscribe(_ =>
                {
                    if (disposable == null)
                    {
                        return;
                    }
                    disposable.Dispose();
                    disposable = null;
                    desc.Callback(
                        this._globalAccountSelectionFlipViewModel
                        .SelectedAccounts);
                });
                _globalAccountSelectionFlipViewModel.Open();
            }));
            CompositeDisposable.Add(
                Observable.FromEvent(
                    h => ThemeManager.ThemeChanged += h,
                    h => ThemeManager.ThemeChanged -= h
                    ).Subscribe(_ => this.Messenger.RaiseAsync(new InteractionMessage("InvalidateTheme"))));

            #endregion

            #region special navigations
            // check first boot
            if (Setting.IsFirstGenerated)
            {
                var kovm = new KeyOverrideViewModel();
                Messenger.RaiseSafeSync(() => new TransitionMessage(
                                            typeof(KeyOverrideWindow),
                                            kovm, TransitionMode.Modal, null));
            }

            // register new account if accounts haven't been authorized yet
            if (!Setting.Accounts.Collection.Any())
            {
                var auth = new AuthorizationViewModel();
                auth.AuthorizeObservable
                .Subscribe(Setting.Accounts.Collection.Add);
                Messenger.RaiseSafeSync(() => new TransitionMessage(
                                            typeof(AuthorizationWindow),
                                            auth, TransitionMode.Modal, null));
            }
            #endregion

            TabManager.Load();
            TabManager.Save();

            if (TabManager.Columns.Count == 1 && TabManager.Columns[0].Tabs.Count == 0)
            {
                // lost tab info
                this.ReInitTabs();
            }

            // check cleanup parameter
            if (Setting.AutoCleanupTweets.Value &&
                Setting.AutoCleanupThreshold.Value < 0)
            {
                var msg = this.Messenger.GetResponseSafe(() =>
                                                         new TaskDialogMessage(new TaskDialogOptions
                {
                    Title           = AppInitResources.MsgCleanupConfigTitle,
                    MainIcon        = VistaTaskDialogIcon.Information,
                    MainInstruction = AppInitResources.MsgCleanupConfigInst,
                    Content         = AppInitResources.MsgCleanupConfigContent,
                    ExpandedInfo    = AppInitResources.MsgCleanupConfigExInfo,
                    CommonButtons   = TaskDialogCommonButtons.YesNo
                }));
                Setting.AutoCleanupTweets.Value    = msg.Response.Result == TaskDialogSimpleResult.Yes;
                Setting.AutoCleanupThreshold.Value = 100000;
            }

            // check execution properties
            if (Setting.ShowStartupConfigurationWarning.Value)
            {
                if (App.ExecutionMode == ExecutionMode.Standalone)
                {
                    var msg = this.Messenger.GetResponseSafe(() =>
                                                             new TaskDialogMessage(new TaskDialogOptions
                    {
                        Title            = AppInitResources.MsgExecModeWarningTitle,
                        MainIcon         = VistaTaskDialogIcon.Warning,
                        MainInstruction  = AppInitResources.MsgExecModeWarningInst,
                        Content          = AppInitResources.MsgExecModeWarningContent,
                        FooterIcon       = VistaTaskDialogIcon.Error,
                        FooterText       = AppInitResources.MsgExecModeWarningFooter,
                        CommonButtons    = TaskDialogCommonButtons.Close,
                        VerificationText = Resources.MsgDoNotShowAgain
                    }));
                    Setting.ShowStartupConfigurationWarning.Value = !msg.Response.VerificationChecked.GetValueOrDefault();
                }
                else if (App.DatabaseDirectoryUserSpecified)
                {
                    var msg = this.Messenger.GetResponseSafe(() =>
                                                             new TaskDialogMessage(new TaskDialogOptions
                    {
                        Title            = AppInitResources.MsgDatabasePathWarningTitle,
                        MainIcon         = VistaTaskDialogIcon.Warning,
                        MainInstruction  = AppInitResources.MsgDatabasePathWarningInst,
                        Content          = AppInitResources.MsgDatabasePathWarningContent,
                        FooterIcon       = VistaTaskDialogIcon.Error,
                        FooterText       = AppInitResources.MsgDatabasePathWarningFooter,
                        CommonButtons    = TaskDialogCommonButtons.Close,
                        VerificationText = Resources.MsgDoNotShowAgain
                    }));
                    Setting.ShowStartupConfigurationWarning.Value = !msg.Response.VerificationChecked.GetValueOrDefault();
                }
            }

            Task.Run(() => App.RaiseUserInterfaceReady());

            // initially focus to timeline
            MainWindowModel.SetFocusTo(FocusRequest.Timeline);

            PostInitialize();
        }
コード例 #31
0
        public ToolViewViewModel(
            IKCVDBClient client,
            string sessionId,
            IDispatcher dispatcher)
            : base(dispatcher)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            if (sessionId == null)
            {
                throw new ArgumentNullException(nameof(sessionId));
            }
            Client    = client;
            SessionId = sessionId;

            // Register metrics
            CustomMetrics.Add(new StartedTimeMetrics(DateTimeOffset.Now));
            CustomMetrics.Add(new TransferredApiCountMetrics(Client));
            CustomMetrics.Add(new SuccessCountMetrics(Client));
            CustomMetrics.Add(new FailureCountMetrics(Client));
            CustomMetrics.Add(new TransferredDataAmountMetrics(Client));
            CustomMetrics.Add(new TransferredDataAmountPerHourMetrics(Client));


            // Register a listener to update history
            Observable.FromEventPattern <ApiDataSentEventArgs>(Client, nameof(Client.ApiDataSent))
            .Select(x => x.EventArgs)
            .Select(x => {
                var now = DateTimeOffset.Now;
                return(x.ApiData.Select(apiData => new HistoryItem {
                    Time = now,
                    Body = apiData.RequestUri.PathAndQuery,
                    Success = true,
                }));
            })
            .SubscribeOnDispatcher(System.Windows.Threading.DispatcherPriority.Normal)
            .Subscribe(historyItems => {
                try {
                    HistoryItems = new ObservableCollection <HistoryItem>(
                        historyItems.Reverse().Concat(HistoryItems).Take(MaxHistoryCount));
                }
                catch (Exception ex) {
                    TelemetryClient.TrackException("Failed to update history.", ex);
                    if (ex.IsCritical())
                    {
                        throw;
                    }
                }
            });

            // Register a listener to notify chinese option chaning
            Subscriptions.Add(Observable.FromEventPattern <PropertyChangedEventArgs>(Settings.Default, nameof(Settings.PropertyChanged))
                              .Where(x => x.EventArgs.PropertyName == nameof(Settings.ShowTraditionalChinese))
                              .SubscribeOnDispatcher()
                              .Subscribe(_ => {
                try {
                    RaisePropertyChanged(nameof(EnableSendingTelemetry));
                    RaisePropertyChanged(nameof(ShowTraditionalChinese));
                }
                catch (Exception ex) {
                    TelemetryClient.TrackException("Failed to raise property chaning of show traditional chinese option", ex);
                    if (ex.IsCritical())
                    {
                        throw;
                    }
                }
            }));

            // Register a listener to receive language switching event
            Subscriptions.Add(Observable.FromEventPattern <PropertyChangedEventArgs>(ResourceHolder.Instance, nameof(ResourceHolder.PropertyChanged))
                              .Where(x => x.EventArgs.PropertyName == nameof(ResourceHolder.Culture))
                              .SubscribeOnDispatcher()
                              .Subscribe(_ => {
                try {
                    CurrentLanguageTwoLetterName = ResourceHolder.Instance.Culture?.TwoLetterISOLanguageName;
                }
                catch (Exception ex) {
                    TelemetryClient.TrackException("Failed to update current language two letter name.", ex);
                    if (ex.IsCritical())
                    {
                        throw;
                    }
                }
            }));

            CurrentLanguageTwoLetterName = ResourceHolder.Instance.Culture?.TwoLetterISOLanguageName;
        }
コード例 #32
0
 public VirtualClockTests(ITestOutputHelper output)
 {
     disposables.Add(LogEvents.Subscribe(e => output.WriteLine(e.ToLogString())));
 }
コード例 #33
0
 public void AddDisposable(IDisposable disposable)
 {
     disposables.Add(disposable);
 }
コード例 #34
0
        private IDisposable StartStreaming(IInternalResultCursor cursor,
                                           IObserver <IRecord> recordObserver = null, IObserver <IResultSummary> summaryObserver = null)
        {
            var cancellation = new CompositeDisposable(2);

            if (summaryObserver != null)
            {
                cancellation.Add(_summary.Subscribe(summaryObserver));
            }

            if (StartStreaming())
            {
                if (recordObserver != null)
                {
                    cancellation.Add(_records.Subscribe(recordObserver));
                }

                var streamingCancellation = new CancellationDisposable();
                cancellation.Add(streamingCancellation);

                Task.Run(async() =>
                {
                    try
                    {
                        // Ensure that we propagate any errors from the KeysAsync call
                        await cursor.KeysAsync().ConfigureAwait(false);

                        if (!_records.HasObservers)
                        {
                            cursor.Cancel();
                        }
                        else
                        {
                            streamingCancellation.Token.Register(cursor.Cancel);
                        }

                        while (await cursor.FetchAsync().ConfigureAwait(false))
                        {
                            _records.OnNext(cursor.Current);
                        }

                        _records.OnCompleted();
                    }
                    catch (Exception exc)
                    {
                        _records.OnError(exc);

                        if (summaryObserver != null)
                        {
                            _summary.OnError(exc);
                        }
                    }

                    try
                    {
                        _summary.OnNext(await cursor.ConsumeAsync().ConfigureAwait(false));
                        _summary.OnCompleted();
                    }
                    catch (Exception exc)
                    {
                        _summary.OnError(exc);
                    }

                    CompleteStreaming();
                }, streamingCancellation.Token);
            }
            else
            {
                recordObserver?.OnError(new ResultConsumedException(
                                            "Streaming has already started and/or finished with a previous Records or Summary subscription."));
            }

            return(cancellation);
        }
コード例 #35
0
        public void Events_committed_to_the_event_store_are_caught_up_by_multiple_independent_read_model_stores()
        {
            var productName = Any.Paragraph(4);

            var projector1 = new Projector <Order.ItemAdded>(() => new ReadModels1DbContext())
            {
                OnUpdate = (work, e) => new ReadModels1DbContext().DisposeAfter(db => UpdateReservedInventory(db, e))
            };
            var projector2 = new Projector <Order.ItemAdded>(() => new ReadModels2DbContext())
            {
                OnUpdate = (work, e) => new ReadModels2DbContext().DisposeAfter(db => UpdateReservedInventory(db, e))
            };
            var numberOfEvents = Any.Int(10, 50);

            using (var disposables = new CompositeDisposable())
                using (var catchup1 = CreateReadModelCatchup <ReadModels1DbContext>(projector1))
                    using (var catchup2 = CreateReadModelCatchup <ReadModels2DbContext>(projector2))
                    {
                        catchup1.Progress.ForEachAsync(p => Console.WriteLine("catchup1: " + p));
                        catchup2.Progress.ForEachAsync(p => Console.WriteLine("catchup2: " + p));

                        Action <string, ThreadStart> startThread =
                            (name, start) =>
                        {
                            var thread = new Thread(() =>
                            {
                                Console.WriteLine("starting thread (" + Thread.CurrentThread.ManagedThreadId + ")");
                                start();
                                Console.WriteLine("ended thread (" + Thread.CurrentThread.ManagedThreadId + ")");
                            });
                            thread.Name = name;
                            thread.Start();
                            disposables.Add(Disposable.Create(thread.Abort));
                        };

                        Events.Write(numberOfEvents, i => new Order.ItemAdded
                        {
                            ProductName = productName,
                            Quantity    = 1,
                            AggregateId = Any.Guid()
                        });

                        // TODO: (Events_committed_to_the_event_store_are_caught_up_by_multiple_independent_read_model_stores) is this leading to intermittent test failures by leaving a dangling app lock?
                        startThread("catchup1", () =>
                        {
                            catchup1.Run().Wait();
                            catchup1.Dispose();
                        });
                        startThread("catchup2", () =>
                        {
                            catchup2.Run().Wait();
                            catchup2.Dispose();
                        });

                        Console.WriteLine("Waiting on catchups to complete");

                        // wait on both catchups to complete
                        catchup1
                        .Progress
                        .Merge(catchup2.Progress)
                        .Where(p => p.IsEndOfBatch)
                        .Take(2)
                        .Timeout(DefaultTimeout)
                        .Wait();
                    }

            Action <DbContext> verify = db =>
            {
                var readModelInfoName = ReadModelInfo.NameForProjector(projector1);

                var readModelInfos = db.Set <ReadModelInfo>();
                Console.WriteLine(new { readModelInfos }.ToLogString());
                readModelInfos
                .Single(i => i.Name == readModelInfoName)
                .CurrentAsOfEventId
                .Should()
                .Be(HighestEventId + numberOfEvents);

                var productInventories = db.Set <ProductInventory>();
                Console.WriteLine(new { productInventories }.ToLogString());
                productInventories
                .Single(pi => pi.ProductName == productName)
                .QuantityReserved
                .Should()
                .Be(numberOfEvents);
            };

            Console.WriteLine("verifying ReadModels1DbContext...");
            new ReadModels1DbContext().DisposeAfter(r => verify(r));

            Console.WriteLine("verifying ReadModels2DbContext...");
            new ReadModels2DbContext().DisposeAfter(r => verify(r));
        }
コード例 #36
0
 protected void AddToDisposable(IDisposable disposable)
 {
     disposables.Add(disposable);
 }
コード例 #37
0
ファイル: TestDependencyTests.cs プロジェクト: colombod/Peaky
 public TestDependencyTests(ITestOutputHelper output)
 {
     disposables.Add(LogEvents.Subscribe(e => output.WriteLine(e.ToLogString())));
 }
コード例 #38
0
 private ValidationBinding(IObservable <Unit> validationObservable)
 {
     _disposables.Add(validationObservable.Subscribe());
 }
コード例 #39
0
        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            onUnloaded = new CompositeDisposable();

            var keyboardHost = VisualAndLogicalTreeHelper.FindVisualParent <KeyboardHost>(this);

            // If key isn't visible, it won't have a visual parent and this is okay.
            if (keyboardHost == null && !this.IsVisible)
            {
                return;
            }

            var mainViewModel         = keyboardHost.DataContext as MainViewModel;
            var keyStateService       = mainViewModel.KeyStateService;
            var capturingStateManager = mainViewModel.CapturingStateManager;

            //Calculate KeyDownState
            if (Value != null)
            {
                var keyStateSubscription = keyStateService.KeyDownStates[Value]
                                           .OnPropertyChanges(kds => kds.Value)
                                           .Subscribe(value => KeyDownState = value);
                onUnloaded.Add(keyStateSubscription);
            }
            KeyDownState = (Value == null) ? KeyDownStates.Up : keyStateService.KeyDownStates[Value].Value;

            //Calculate SelectionProgress and SelectionInProgress
            if (Value != null)
            {
                var keySelectionProgressSubscription = keyStateService.KeySelectionProgress[Value]
                                                       .OnPropertyChanges(ksp => ksp.Value)
                                                       .Subscribe(value =>
                {
                    SelectionProgress   = value;
                    SelectionInProgress = value > 0d;
                });
                onUnloaded.Add(keySelectionProgressSubscription);
            }
            var progress = (Value == null) ? 0 : keyStateService.KeySelectionProgress[Value].Value;

            SelectionProgress   = progress;
            SelectionInProgress = progress > 0d;

            //Calculate IsEnabled
            Action calculateIsEnabled     = () => IsEnabled = keyStateService.KeyEnabledStates[Value];
            var    keyEnabledSubscription = keyStateService.KeyEnabledStates
                                            .OnAnyPropertyChanges()
                                            .Subscribe(_ => calculateIsEnabled());

            onUnloaded.Add(keyEnabledSubscription);
            calculateIsEnabled();

            //Calculate IsCurrent
            Action <KeyValue> calculateIsCurrent = value => IsCurrent = value != null && Value != null && value.Equals(Value);
            var currentPositionSubscription      = mainViewModel.OnPropertyChanges(vm => vm.CurrentPositionKey)
                                                   .Subscribe(calculateIsCurrent);

            onUnloaded.Add(currentPositionSubscription);
            calculateIsCurrent(mainViewModel.CurrentPositionKey);

            //Calculate DisplayShiftDownText
            //Display shift down text (upper case text) if shift is locked down, or down (but NOT when we are capturing a multi key selection)
            Action <KeyDownStates, bool> calculateDisplayShiftDownText = (shiftDownState, capturingMultiKeySelection) =>
                                                                         DisplayShiftDownText = shiftDownState == KeyDownStates.LockedDown ||
                                                                                                (shiftDownState == KeyDownStates.Down && !capturingMultiKeySelection);

            var capturingMultiKeySelectionSubscription = capturingStateManager
                                                         .OnPropertyChanges(csm => csm.CapturingMultiKeySelection)
                                                         .Subscribe(value => calculateDisplayShiftDownText(keyStateService.KeyDownStates[KeyValues.LeftShiftKey].Value, value));

            onUnloaded.Add(capturingMultiKeySelectionSubscription);

            var leftShiftKeyStateSubscription = keyStateService.KeyDownStates[KeyValues.LeftShiftKey]
                                                .OnPropertyChanges(sds => sds.Value)
                                                .Subscribe(value => calculateDisplayShiftDownText(value, capturingStateManager.CapturingMultiKeySelection));

            onUnloaded.Add(leftShiftKeyStateSubscription);
            calculateDisplayShiftDownText(keyStateService.KeyDownStates[KeyValues.LeftShiftKey].Value, capturingStateManager.CapturingMultiKeySelection);

            //Publish own version of KeySelection event
            var keySelectionSubscription = Observable.FromEventPattern <KeyValue>(
                handler => mainViewModel.KeySelection += handler,
                handler => mainViewModel.KeySelection -= handler)
                                           .Subscribe(pattern =>
            {
                if (Value != null &&
                    pattern.EventArgs.Equals(Value) &&
                    Selection != null)
                {
                    Selection(this, null);
                }
            });

            onUnloaded.Add(keySelectionSubscription);
        }
コード例 #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BasePropertyValidation{TViewModel}"/> class.
 /// </summary>
 protected BasePropertyValidation()
 {
     // subscribe to the valid subject so we can assign the validity
     _disposables.Add(_isValidSubject.Subscribe(v => _isValid = v));
 }
コード例 #41
0
        public RepositoryHosts(
            IRepositoryHostFactory repositoryHostFactory,
            ISharedCache sharedCache,
            IConnectionManager connectionManager)
        {
            Guard.ArgumentNotNull(repositoryHostFactory, nameof(repositoryHostFactory));
            Guard.ArgumentNotNull(sharedCache, nameof(sharedCache));
            Guard.ArgumentNotNull(connectionManager, nameof(connectionManager));

            this.connectionManager = connectionManager;

            RepositoryHostFactory = repositoryHostFactory;
            GitHubHost            = DisconnectedRepositoryHost;
            EnterpriseHost        = DisconnectedRepositoryHost;

            var persistEntepriseHostObs = this.WhenAny(x => x.EnterpriseHost, x => x.Value)
                                          .Skip(1) // The first value will be null or something already in the db
                                          .SelectMany(enterpriseHost =>
            {
                if (!enterpriseHost.IsLoggedIn)
                {
                    return(sharedCache.UserAccount
                           .InvalidateObject <Uri>(EnterpriseHostApiBaseUriCacheKey)
                           .Catch <Unit, Exception>(ex =>
                    {
                        log.Warn("Failed to invalidate enterprise host uri", ex);
                        return Observable.Return(Unit.Default);
                    }));
                }

                return(sharedCache.UserAccount
                       .InsertObject(EnterpriseHostApiBaseUriCacheKey, enterpriseHost.Address.ApiUri)
                       .Catch <Unit, Exception>(ex =>
                {
                    log.Warn("Failed to persist enterprise host uri", ex);
                    return Observable.Return(Unit.Default);
                }));
            });

            isLoggedInToAnyHost = this.WhenAny(
                x => x.GitHubHost.IsLoggedIn,
                x => x.EnterpriseHost.IsLoggedIn,
                (githubLoggedIn, enterpriseLoggedIn) => githubLoggedIn.Value || enterpriseLoggedIn.Value)
                                  .ToProperty(this, x => x.IsLoggedInToAnyHost);

            // This part is strictly to support having the IConnectionManager request that a connection
            // be logged in. It doesn't know about hosts or load anything reactive, so it gets
            // informed of logins by an observable returned by the event
            connectionManager.DoLogin += RunLoginHandler;

            // monitor the list of connections so we can log out hosts when connections are removed
            disposables.Add(
                connectionManager.Connections.CreateDerivedCollection(x => x)
                .ItemsRemoved
                .SelectMany(async x =>
            {
                var host = LookupHost(x.HostAddress);
                if (host.Address != x.HostAddress)
                {
                    host = await RepositoryHostFactory.Create(x.HostAddress);
                }
                return(host);
            })
                .Select(h => LogOut(h))
                .Merge().ToList().Select(_ => Unit.Default).Subscribe());


            // Wait until we've loaded (or failed to load) an enterprise uri from the db and then
            // start tracking changes to the EnterpriseHost property and persist every change to the db
            disposables.Add(persistEntepriseHostObs.Subscribe());
        }
コード例 #42
0
        public BindingDiagDialog(IServiceProvider provider, Site site)
            : base(provider)
        {
            InitializeComponent();

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnGenerate, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
                try
                {
                    Debug($"System Time: {DateTime.Now}");
                    Debug($"Processor Architecture: {Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")}");
                    Debug($"OS: {Environment.OSVersion}");
                    Debug($"Server Type: {site.Server.Mode.AsString(EnumFormat.Description)}");
                    Debug("-----");

                    var adapters = Dns.GetHostEntry(string.Empty).AddressList.Where(address => !address.IsIPv6LinkLocal).ToList();
                    if (adapters.Count == 0)
                    {
                        Warn("This machine has no suitable IP address to accept external traffic.");
                    }
                    else
                    {
                        Info($"This machine has {adapters.Count} IP addresses to take external traffic.");
                        foreach (IPAddress address in adapters)
                        {
                            Info($"* {address}.");
                        }
                    }

                    Debug("-----");

                    Debug($"[W3SVC/{site.Id}]");
                    Debug($"ServerComment  : {site.Name}");
                    Debug($"ServerAutoStart: {site.ServerAutoStart}");
                    Debug($"ServerState    : {site.State}");
                    Debug(string.Empty);
                    var feature = new ReservedUrlsFeature((Module)provider);
                    feature.Load();
                    foreach (Binding binding in site.Bindings)
                    {
                        Debug($"BINDING: {binding.Protocol} {binding}");
                        if (binding.Protocol == "https" || binding.Protocol == "http")
                        {
                            if (binding.Host != "localhost")
                            {
                                if (site.Server.Mode == WorkingMode.IisExpress)
                                {
                                    var reservation = binding.ToUrlPrefix();
                                    if (!feature.Items.Any(item => item.UrlPrefix == reservation))
                                    {
                                        Warn($"URL reservation {reservation} is missing. So this binding only works if IIS Express runs as administrator.");
                                    }
                                }

                                Info($"This site can take external traffic if,");
                                Info($" * TCP port {binding.EndPoint.Port} must be opened on Windows Firewall (or any other equivalent products).");
                            }

                            if (binding.EndPoint.Address.Equals(IPAddress.Any))
                            {
                                if (binding.Host != "localhost")
                                {
                                    Info($" * Requests from web browsers must be routed to following end points on this machine,");
                                    foreach (IPAddress address in adapters)
                                    {
                                        Info($"   * {address}:{binding.EndPoint.Port}.");
                                    }
                                }

                                if (Socket.OSSupportsIPv4)
                                {
                                    Debug($"This site can take local traffic at {IPAddress.Loopback}:{binding.EndPoint.Port}.");
                                }

                                if (Socket.OSSupportsIPv6)
                                {
                                    Debug($"This site can take local traffic at [{IPAddress.IPv6Loopback}]:{binding.EndPoint.Port}.");
                                }
                            }
                            else
                            {
                                Info($" * The networking must be properly set up to forward requests from web browsers to {binding.EndPoint} on this machine.");
                            }

                            if (binding.Host == "*" || binding.Host == string.Empty)
                            {
                                if (binding.EndPoint.Address.Equals(IPAddress.Any))
                                {
                                    Info($" * Web browsers can use several URLs, such as");
                                    foreach (IPAddress address in adapters)
                                    {
                                        Debug($"   * {binding.Protocol}://{address}:{binding.EndPoint.Port}.");
                                    }

                                    Info($"   * {binding.Protocol}://localhost:{binding.EndPoint.Port}.");
                                    Info($"   * {binding.Protocol}://{IPAddress.Loopback}:{binding.EndPoint.Port}.");
                                    Info($"   * {binding.Protocol}://[{IPAddress.IPv6Loopback}]:{binding.EndPoint.Port}.");
                                }
                                else
                                {
                                    Info($" * Web browsers should use URL {binding.Protocol}://{binding.EndPoint.Address}:{binding.EndPoint.Port}.");
                                }
                            }
                            else
                            {
                                Info($" * Web browsers should use URL {binding.Protocol}://{binding.Host}:{binding.EndPoint.Port}. Requests must have Host header {binding.Host}.");
                                var entry = Dns.GetHostEntry(binding.Host);
                                var list  = entry.AddressList;
                                var found = false;
                                foreach (var address in list)
                                {
                                    if (adapters.Any(item => address.Equals(item)))
                                    {
                                        found = true;
                                        break;
                                    }

                                    if (address.Equals(IPAddress.Loopback))
                                    {
                                        found = true;
                                    }
                                }

                                if (!found)
                                {
                                    Warn($"   DNS query does not return a known IP address for any network adapter of this machine. Please review your DNS settings or modify the hosts file.");
                                }
                            }

                            if (binding.Protocol == "https")
                            {
                                Warn($"Please run SSL Diagnostics at server level to analyze SSL configuration. More information can be found at https://www.jexusmanager.com/en/latest/tutorials/ssl-diagnostics.html.");
                            }
                        }

                        Debug(string.Empty);
                    }
                }
                catch (CryptographicException ex)
                {
                    Debug(ex.ToString());
                    RollbarDotNet.Rollbar.Report(ex, custom: new Dictionary <string, object> {
                        { "hResult", ex.HResult }
                    });
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    RollbarDotNet.Rollbar.Report(ex);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSave, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var fileName = DialogHelper.ShowSaveFileDialog(null, "Text Files|*.txt|All Files|*.*");
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                File.WriteAllText(fileName, txtResult.Text);
            }));
        }
コード例 #43
0
        public ImportCertificateDialog(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbStore.SelectedIndex = 0;
            if (Environment.OSVersion.Version < Version.Parse("6.2"))
            {
                // IMPORTANT: WebHosting store is available since Windows 8.
                cbStore.Enabled = false;
            }

            if (!Helper.IsRunningOnMono())
            {
                JexusManager.NativeMethods.TryAddShieldToButton(btnOK);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowFileDialog(txtFile, ".pfx|*.pfx|*.*|*.*");
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtFile, "TextChanged")
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtFile.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                try
                {
                    // Load your certificate from file
                    Item        = new X509Certificate2(txtFile.Text, txtPassword.Text, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
                    Store       = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting";
                    var service = (IConfigurationService)GetService(typeof(IConfigurationService));
                    if (service.ServerManager.Mode == WorkingMode.Jexus)
                    {
                        var server = (JexusServerManager)service.Server;
                        // Public Key;
                        StringBuilder publicBuilder = new StringBuilder();
                        publicBuilder.AppendLine("-----BEGIN CERTIFICATE-----");
                        publicBuilder.AppendLine(Convert.ToBase64String(Item.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                        publicBuilder.AppendLine("-----END CERTIFICATE-----");
                        var file = AsyncHelper.RunSync(() => server.SaveCertificateAsync(publicBuilder.ToString()));
                        server.SetCertificate(file);
                        // Private Key
                        RSACryptoServiceProvider rsa    = (RSACryptoServiceProvider)Item.PrivateKey;
                        MemoryStream memoryStream       = new MemoryStream();
                        TextWriter streamWriter         = new StreamWriter(memoryStream);
                        PemWriter pemWriter             = new PemWriter(streamWriter);
                        AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa);
                        pemWriter.WriteObject(keyPair.Private);
                        streamWriter.Flush();
                        string output     = Encoding.ASCII.GetString(memoryStream.GetBuffer()).Trim();
                        int indexOfFooter = output.IndexOf("-----END RSA PRIVATE KEY-----", StringComparison.Ordinal);
                        memoryStream.Close();
                        streamWriter.Close();
                        string key  = output.Substring(0, indexOfFooter + 29);
                        var keyFile = AsyncHelper.RunSync(() => server.SaveKeyAsync(key));
                        server.SetKeyFile(keyFile);
                        service.ServerManager.CommitChanges();
                    }
                    else
                    {
                        try
                        {
                            using (var process = new Process())
                            {
                                // add certificate
                                var start       = process.StartInfo;
                                start.Verb      = "runas";
                                start.FileName  = "cmd";
                                start.Arguments = string.Format(
                                    "/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"",
                                    txtFile.Text,
                                    txtPassword.Text,
                                    Item.FriendlyName,
                                    cbStore.SelectedIndex == 0 ? "MY" : "WebHosting",
                                    Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe"));
                                start.CreateNoWindow = true;
                                start.WindowStyle    = ProcessWindowStyle.Hidden;
                                process.Start();
                                process.WaitForExit();
                                if (process.ExitCode == 0)
                                {
                                    DialogResult = DialogResult.OK;
                                }
                                else
                                {
                                    MessageBox.Show(process.ExitCode.ToString());
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // elevation is cancelled.
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowError(ex, string.Empty, false);
                }
            }));
        }
コード例 #44
0
 /// <summary>
 /// Helper function to add IDisposables to a composible disposable.
 /// This allows for easy chaining when using Reactive Extensions.
 /// </summary>
 /// <param name="disposable"></param>
 /// <param name="compositeDisposable"></param>
 public static void AddTo(this IDisposable disposable, CompositeDisposable compositeDisposable)
 {
     compositeDisposable.Add(disposable);
 }
コード例 #45
0
 public WebServerTests(ITestOutputHelper output)
 {
     _disposables.Add(output.SubscribeToPocketLogger());
 }
コード例 #46
0
 public CompositeKernelTests(ITestOutputHelper output)
 {
     _disposables.Add(output.SubscribeToPocketLogger());
 }
コード例 #47
0
ファイル: KernelTests.cs プロジェクト: harunpehlivan/try
 protected void DisposeAfterTest(IDisposable disposable)
 {
     _disposables.Add(disposable);
 }
コード例 #48
0
ファイル: Channel.cs プロジェクト: bushadam/NEventSocket
        public async Task BridgeTo(string destination, BridgeOptions options, Action<EventMessage> onProgress = null)
        {
            if (!IsAnswered && !IsPreAnswered)
            {
                return;
            }

            Log.Debug(() => "Channel {0} is attempting a bridge to {1}".Fmt(UUID, destination));

            if (string.IsNullOrEmpty(options.UUID))
            {
                options.UUID = Guid.NewGuid().ToString();
            }

            var subscriptions = new CompositeDisposable();

            subscriptions.Add(
                eventSocket.Events.Where(x => x.UUID == options.UUID)
                    .Take(1)
                    .Subscribe(x => Bridge = new BridgeStatus(false, "In Progress", new BridgedChannel(x, eventSocket))));

            if (onProgress != null)
            {
                subscriptions.Add(
                    eventSocket.Events.Where(x => x.UUID == options.UUID && x.EventName == EventName.ChannelProgress)
                        .Take(1)
                        .Subscribe(onProgress));
            }

            var result = await eventSocket.Bridge(UUID, destination, options).ConfigureAwait(false);

            Log.Debug(() => "Channel {0} bridge complete {1} {2}".Fmt(UUID, result.Success, result.ResponseText));
            subscriptions.Dispose();

            Bridge = new BridgeStatus(result.Success, result.ResponseText, Bridge.Channel);
        }
コード例 #49
0
        public SetRestrictionsDialog(IServiceProvider serviceProvider, ConfigurationSection section)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbDomain.Checked       = (bool)section["enableReverseDns"];
            cbAccess.SelectedIndex = (bool)section["allowUnlisted"] ? 0 : 1;
            cbProxy.Enabled        = section.Schema.AttributeSchemas["enabled"] != null;
            if (cbProxy.Enabled)
            {
                cbProxy.Checked = (bool)section["enableProxyMode"];
            }

            cbAction.Enabled = section.Schema.AttributeSchemas["denyAction"] != null;
            if (cbAction.Enabled)
            {
                var action = (long)section["denyAction"];
                if (action == 0L)
                {
                    cbAction.SelectedIndex = 0;
                }
                else if (action == 401L)
                {
                    cbAction.SelectedIndex = 1;
                }
                else if (action == 403L)
                {
                    cbAction.SelectedIndex = 2;
                }
                else
                {
                    cbAction.SelectedIndex = 3;
                }
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                section["enableReverseDns"] = cbDomain.Checked;
                section["allowUnlisted"]    = cbAccess.SelectedIndex == 0;
                if (cbProxy.Enabled)
                {
                    section["enableProxyMode"] = cbProxy.Checked;
                }

                if (cbAction.Enabled)
                {
                    if (cbAction.SelectedIndex == 0)
                    {
                        section["denyAction"] = 0L;
                    }
                    else if (cbAction.SelectedIndex == 1)
                    {
                        section["denyAction"] = 401L;
                    }
                    else if (cbAction.SelectedIndex == 2)
                    {
                        section["denyAction"] = 403L;
                    }
                    else
                    {
                        section["denyAction"] = 404L;
                    }
                }

                DialogResult = DialogResult.OK;
            }));
        }
コード例 #50
0
ファイル: Key.cs プロジェクト: Weetbix/OptiKey
        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            onUnloaded = new CompositeDisposable();

            var keyboardHost = VisualAndLogicalTreeHelper.FindVisualParent<KeyboardHost>(this);
            var mainViewModel = keyboardHost.DataContext as MainViewModel;
            var keyStateService = mainViewModel.KeyStateService;
            var capturingStateManager = mainViewModel.CapturingStateManager;

            //Calculate KeyDownState
            var keyStateSubscription = keyStateService.KeyDownStates[Value]
                .OnPropertyChanges(kds => kds.Value)
                .Subscribe(value => KeyDownState = value);
            onUnloaded.Add(keyStateSubscription);
            KeyDownState = keyStateService.KeyDownStates[Value].Value;

            //Calculate SelectionProgress
            var keySelectionProgressSubscription = keyStateService.KeySelectionProgress[Value]
                .OnPropertyChanges(ksp => ksp.Value)
                .Subscribe(value => SelectionProgress = value);
            onUnloaded.Add(keySelectionProgressSubscription);
            SelectionProgress = keyStateService.KeySelectionProgress[Value].Value;

            //Calculate IsEnabled
            Action calculateIsEnabled = () => IsEnabled = keyStateService.KeyEnabledStates[Value];
            var keyEnabledSubscription = keyStateService.KeyEnabledStates
                .OnAnyPropertyChanges()
                .Subscribe(_ => calculateIsEnabled());
            onUnloaded.Add(keyEnabledSubscription);
            calculateIsEnabled();

            //Calculate IsCurrent
            Action<KeyValue?> calculateIsCurrent = value => IsCurrent = value != null && value.Value.Equals(Value);
            var currentPositionSubscription = mainViewModel.OnPropertyChanges(vm => vm.CurrentPositionKey)
                .Subscribe(calculateIsCurrent);
            onUnloaded.Add(currentPositionSubscription);
            calculateIsCurrent(mainViewModel.CurrentPositionKey);

            //Calculate DisplayShiftDownText
            Action<KeyDownStates, bool> calculateDisplayShiftDownText = (shiftDownState, capturingMultiKeySelection) =>
                    DisplayShiftDownText = shiftDownState == KeyDownStates.LockedDown
                    || (shiftDownState == KeyDownStates.Down && !capturingMultiKeySelection);
            var capturingMultiKeySelectionSubscription = capturingStateManager
                .OnPropertyChanges(csm => csm.CapturingMultiKeySelection)
                .Subscribe(value => calculateDisplayShiftDownText(keyStateService.KeyDownStates[KeyValues.LeftShiftKey].Value, value));
            onUnloaded.Add(capturingMultiKeySelectionSubscription);
            var leftShiftKeyStateSubscription = keyStateService.KeyDownStates[KeyValues.LeftShiftKey]
                .OnPropertyChanges(sds => sds.Value)
                .Subscribe(value => calculateDisplayShiftDownText(value, capturingStateManager.CapturingMultiKeySelection));
            onUnloaded.Add(leftShiftKeyStateSubscription);
            calculateDisplayShiftDownText(keyStateService.KeyDownStates[KeyValues.LeftShiftKey].Value, capturingStateManager.CapturingMultiKeySelection);

            //Publish own version of KeySelection event
            var keySelectionSubscription = Observable.FromEventPattern<KeyValue>(
                handler => mainViewModel.KeySelection += handler,
                handler => mainViewModel.KeySelection -= handler)
                .Subscribe(pattern =>
                {
                    if (pattern.EventArgs.Equals(Value)
                        && Selection != null)
                    {
                        Selection(this, null);
                    }
                });
            onUnloaded.Add(keySelectionSubscription);
        }
コード例 #51
0
        public MainWindowViewModel()
        {
            CompositeDisposable.Add(new PropertyChangedEventListener(m_Model, (s, ev) =>
            {
                switch (ev.PropertyName)
                {
                case nameof(m_Model.LyricsSource):
                    RaisePropertyChanged(nameof(LyricsSource));
                    break;

                case nameof(m_Model.IsModified):
                    RaisePropertyChanged(nameof(IsModified));
                    break;

                case nameof(m_Model.SavedFileNameWithoutExtension):
                    RaisePropertyChanged(nameof(DocumentName));
                    break;
                }
            }));
            var synchronizationContext = SynchronizationContext.Current;

            Debug.Assert(synchronizationContext != null, "SynchronizationContext.Current is null");
            CompositeDisposable.Add(
                m_Model.AsPropertyChanged(nameof(m_Model.ParserErrors))
                .Throttle(TimeSpan.FromMilliseconds(1000))
                .ObserveOn(synchronizationContext)
                .Subscribe(_ =>
            {
                ParserErrors.Clear();
                foreach (var item in m_Model.ParserErrors)
                {
                    ParserErrors.Add(item);
                }
            })
                );
            CompositeDisposable.Add(new PropertyChangedEventListener(this, async(s, ev) =>
            {
                switch (ev.PropertyName)
                {
                case nameof(CaretLocation):
                    if (LyricsSource != null)
                    {
                        var logicalLineIndex = LyricsSource.LineMap.GetLogicalLineIndexByPhysical(CaretLocation.Line - 1);
                        if (logicalLineIndex >= 0)
                        {
                            await ForcusViewSyllableAsync(logicalLineIndex, 0);
                        }
                    }
                    break;

                case nameof(CurrentSyllable):
                    if (LyricsSource != null)
                    {
                        var physicalLineIndex = LyricsSource.LineMap.GetPhysicalLineIndexByLogical(CurrentSyllable.Line);
                        await FocusEditorCharacterAsync(physicalLineIndex + 1, -1, false);
                    }
                    break;
                }
            }));

            NewCommand = new HotKeyCommand(async() => await NewAsync())
            {
                Gesture = new KeyGesture(Key.N, ModifierKeys.Control)
            };
            OpenCommand = new HotKeyCommand(async() => await OpenAsync())
            {
                Gesture = new KeyGesture(Key.O, ModifierKeys.Control)
            };
            SaveAsCommand = new ViewModelCommand(async() => await SaveAsAsync());
            SaveCommand   = new HotKeyCommand(async() => await SaveAsync())
            {
                Gesture = new KeyGesture(Key.S, ModifierKeys.Control)
            };
            AutoSetRubyInSelectionCommand   = new ViewModelCommand(AutoSetRubyInSelection);
            HighlightFirstCommand           = new ViewModelCommand(async() => await HighlightLyricsAsync(LyricsHighlightRequest.First));
            HighlightNextCommand            = new ViewModelCommand(async() => await HighlightLyricsAsync(LyricsHighlightRequest.Next));
            HighlightPreviousCommand        = new ViewModelCommand(async() => await HighlightLyricsAsync(LyricsHighlightRequest.Previous));
            HighlightNextLineCommand        = new ViewModelCommand(async() => await HighlightLyricsAsync(LyricsHighlightRequest.NextLine));
            HighlightPreviousLineCommand    = new ViewModelCommand(async() => await HighlightLyricsAsync(LyricsHighlightRequest.PreviousLine));
            MoveCaretToSelectedErrorCommand = new ViewModelCommand(async() => await MoveCaretToSelectedErrorAsync());
        }
コード例 #52
0
        public NewRuleBlockingDialog(IServiceProvider serviceProvider, InboundFeature rewriteFeature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbMode.SelectedIndex     = 1;
            cbInput.SelectedIndex    = 0;
            cbMatch.SelectedIndex    = 0;
            cbResponse.SelectedIndex = 1;

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbInput, "SelectedIndexChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(cbMode, "SelectedIndexChanged"))
                .Subscribe(evt =>
            {
                switch (cbInput.SelectedIndex)
                {
                case 0:
                    lblPattern.Text = "Pattern (URL Path):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: IMG*.jpg" : "Example: ^IMG.*\\.jpg$";
                    break;

                case 1:
                    lblPattern.Text = "Pattern (User-agent Header):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: Mozilla/4*" : "Example: ^Mozilla/[1234].*";
                    break;

                case 2:
                    lblPattern.Text = "Pattern (IP Address):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Exmaple: 192.168.1.*" : "Example: 192\\.168\\.1\\.[1-9]";
                    break;

                case 3:
                    lblPattern.Text = "Pattern (Query String):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: *id=*&p=*" : "Example: id=[0-9]+&p=[a-z]+";
                    break;

                case 4:
                    lblPattern.Text = "Pattern (Referer):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: http://*.consoto.com" : "Example: http://(?:www\\.)?contoso\\.com$";
                    break;

                case 5:
                    lblPattern.Text = "Pattern (Host Header):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: *.consoto.com" : "Example: (?:www\\.)?contoso\\.com$";
                    break;
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtPattern, "TextChanged")
                .Sample(TimeSpan.FromSeconds(1))
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtPattern.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .Subscribe(evt =>
            {
                var inputType = cbInput.SelectedIndex;
                var pattern   = txtPattern.Text;
                var match     = cbMatch.SelectedIndex;
                var response  = cbResponse.SelectedIndex;
                var mode      = cbMode.SelectedIndex;

                int index = 0;
                string name;
                do
                {
                    index++;
                    name = string.Format("RequestBlockingRule{0}", index);
                }while (rewriteFeature.Items.All(item => item.Name != name));
                var newRule               = new InboundRule(null);
                newRule.Name              = name;
                newRule.Input             = "URL Path";
                newRule.Enabled           = true;
                newRule.PatternSyntax     = mode == 0 ? 0L : 1L;
                newRule.PatternUrl        = mode == 0 ? ".*" : "*";
                newRule.Type              = response == 3 ? 4L : 3L;
                newRule.ActionUrl         = "{C:1}";
                newRule.RedirectType      = 301;
                newRule.StatusCode        = GetStatusCode(response);
                newRule.SubStatusCode     = 0;
                newRule.StatusReason      = GetReason(response);
                newRule.StatusDescription = GetMessage(response);
                newRule.Conditions.Add(
                    new ConditionItem(null)
                {
                    Input      = GetInput(inputType),
                    MatchType  = match == 0 ? 4 : 5,
                    Pattern    = pattern,
                    IgnoreCase = true
                });
                rewriteFeature.AddItem(newRule);
                DialogResult = DialogResult.OK;
            }));
        }
コード例 #53
0
        private void ProcessSubscription(string subscriptionId,
                                         IMessage message,
                                         RequestStreamHandler <TRequest, TUpdate> requestStreamHandler)
        {
            // In order to prevent races/resource-leaks here we must:
            //  * Monitor session diconnections before attempting to create a request context.
            //      - Otherwise, a session could be destroyed and we would never clean up its resources, as we'd
            //        miss the notification.
            //  * Create the subscription to monitor sessions and add update our state all within a single
            //    critical region. In addition to this, we must ensure session destruction callbacks are
            //    fired on a different thread.
            //      - Otherwise, we may attempt to remove the session's resources before they are added.
            var sessionId        = message.SessionId;
            var replyDestination = message.ReplyTo;
            var subscription     = new CompositeDisposable();

            TRequest request;

            if (!TryDeserializeRequest(subscriptionId, message, out request))
            {
                return;
            }

            var clientId = message.Properties.GetString(OperationKeys.ClientId);

            if (clientId == null)
            {
                Log.Warning("No ClientId found. Ignoring.");
                return;
            }

            var sessionDestroyedHandler = new AnonymousUserSessionHandler(_ => { },
                                                                          _ =>
            {
                lock (_subscriptions)
                {
                    // TODO: Make the Java version clean all resources hooked up here.
                    // ReSharper disable once AccessToDisposedClosure
                    subscription.Dispose();
                    _subscriptions.Remove(subscriptionId);
                }
            });

            lock (_subscriptions)
            {
                // TODO: How do we clean up when IsSessionRequired == false?
                if (IsSessionRequired)
                {
                    subscription.Add(UserSessionCache.Subscribe(sessionId, sessionDestroyedHandler));
                }

                var context = CreateRequestContext(message);
                if (context == null)
                {
                    Log.Warning("Failed to create request context. Ignoring.");
                    subscription.Dispose(); // Don't listen for session destruction if it doesn't exist.
                    return;
                }

                // At this point we know the session exists or existed and we know it will be cleared up (after we
                // exit the critical region) by the sessionResourceCleaner if it is destroyed.
                _subscriptions.Add(subscriptionId, subscription);

                try
                {
                    const int notFinished              = 0;
                    const int finished                 = 1;
                    var       subscriptionState        = notFinished;
                    var       notificationSubscription = requestStreamHandler(context,
                                                                              request,
                                                                              new AnonymousStreamHandler <TUpdate>(
                                                                                  // TODO: I remove the session from the lookup AND ALSO dipose subscription here.
                                                                                  //       This is analagous to the AutoDetachObserver<T> in Rx. Should we do the same in the Java version?
                                                                                  //       Review with John. -ZB
                                                                                  update => OnUpdated(subscriptionId, replyDestination, update),
                                                                                  error =>
                    {
                        if (Interlocked.Exchange(ref subscriptionState, finished) ==
                            notFinished)
                        {
                            OnFailed(subscriptionId, replyDestination, error);
                        }
                    },
                                                                                  () =>
                    {
                        if (Interlocked.Exchange(ref subscriptionState, finished) ==
                            notFinished)
                        {
                            OnCompleted(subscriptionId, replyDestination);
                        }
                    }));
                    subscription.Add(Disposable.Create(() =>
                    {
                        var hasAlreadyFinished = Interlocked.Exchange(ref subscriptionState, finished) == finished;
                        if (!hasAlreadyFinished)
                        {
                            notificationSubscription.Dispose();
                        }
                    }));
                }
                catch (Exception e)
                {
                    const string error = "Failed to process request";
                    OnFailed(subscriptionId, replyDestination, new MessagingException(error, e));
                    Log.Error(error, e);
                }
            }

            SendAck(subscriptionId, replyDestination, clientId);
        }
コード例 #54
0
ファイル: CodeEditor.cs プロジェクト: yzchengrui/AvalonStudio
        public CodeEditor() : base(new TextArea(), null)
        {
            TextArea.IndentationStrategy = null;

            _shell = IoC.Get <IShell>();

            _snippetManager = IoC.Get <SnippetManager>();

            _lineNumberMargin = new LineNumberMargin(this);

            _breakpointMargin = new BreakPointMargin(this, IoC.Get <IDebugManager2>()?.Breakpoints);

            _selectedLineBackgroundRenderer    = new SelectedLineBackgroundRenderer(this);
            _bracketMatchingBackgroundRenderer = new BracketMatchingBackgroundRenderer(this);

            _selectedWordBackgroundRenderer = new SelectedWordBackgroundRenderer();

            _columnLimitBackgroundRenderer = new ColumnLimitBackgroundRenderer();

            _selectedDebugLineBackgroundRenderer = new SelectedDebugLineBackgroundRenderer();

            TextArea.TextView.Margin = new Thickness(10, 0, 0, 0);

            TextArea.TextView.BackgroundRenderers.Add(_selectedDebugLineBackgroundRenderer);
            TextArea.TextView.LineTransformers.Add(_selectedDebugLineBackgroundRenderer);
            TextArea.TextView.BackgroundRenderers.Add(_bracketMatchingBackgroundRenderer);

            TextArea.SelectionBrush        = Brush.Parse("#AA569CD6");
            TextArea.SelectionCornerRadius = 0;

            void tunneledKeyUpHandler(object send, KeyEventArgs ee)
            {
                if (CaretOffset > 0)
                {
                    _intellisenseManager?.OnKeyUp(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column);
                }
            }

            void tunneledKeyDownHandler(object send, KeyEventArgs ee)
            {
                if (CaretOffset > 0)
                {
                    _intellisenseManager?.OnKeyDown(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column);

                    if (ee.Key == Key.Tab && _currentSnippetContext == null && Editor is ICodeEditor codeEditor && codeEditor.LanguageService != null)
                    {
                        var wordStart = Document.FindPrevWordStart(CaretOffset);

                        if (wordStart > 0)
                        {
                            string word = Document.GetText(wordStart, CaretOffset - wordStart);

                            var codeSnippet = _snippetManager.GetSnippet(codeEditor.LanguageService, Editor.SourceFile.Project?.Solution, Editor.SourceFile.Project, word);

                            if (codeSnippet != null)
                            {
                                var snippet = SnippetParser.Parse(codeEditor.LanguageService, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column, codeSnippet.Snippet);

                                _intellisenseManager.CloseIntellisense();

                                using (Document.RunUpdate())
                                {
                                    Document.Remove(wordStart, CaretOffset - wordStart);

                                    _intellisenseManager.IncludeSnippets = false;
                                    _currentSnippetContext = snippet.Insert(TextArea);
                                }

                                if (_currentSnippetContext.ActiveElements.Count() > 0)
                                {
                                    IDisposable disposable = null;

                                    disposable = Observable.FromEventPattern <SnippetEventArgs>(_currentSnippetContext, nameof(_currentSnippetContext.Deactivated)).Take(1).Subscribe(o =>
                                    {
                                        _currentSnippetContext = null;
                                        _intellisenseManager.IncludeSnippets = true;

                                        disposable.Dispose();
                                    });
                                }
                                else
                                {
                                    _currentSnippetContext = null;
                                    _intellisenseManager.IncludeSnippets = true;
                                }
                            }
                        }
                    }
                }
            }

            _disposables = new CompositeDisposable {
                this.GetObservable(LineNumbersVisibleProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.LeftMargins.Add(_lineNumberMargin);
                    }
                    else
                    {
                        TextArea.LeftMargins.Remove(_lineNumberMargin);
                    }
                }),

                this.GetObservable(ShowBreakpointsProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.LeftMargins.Insert(0, _breakpointMargin);
                    }
                    else
                    {
                        TextArea.LeftMargins.Remove(_breakpointMargin);
                    }
                }),

                this.GetObservable(HighlightSelectedWordProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.TextView.BackgroundRenderers.Add(_selectedWordBackgroundRenderer);
                    }
                    else
                    {
                        TextArea.TextView.BackgroundRenderers.Remove(_selectedWordBackgroundRenderer);
                    }
                }),

                this.GetObservable(HighlightSelectedLineProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.TextView.BackgroundRenderers.Insert(0, _selectedLineBackgroundRenderer);
                    }
                    else
                    {
                        TextArea.TextView.BackgroundRenderers.Remove(_selectedLineBackgroundRenderer);
                    }
                }),

                this.GetObservable(ShowColumnLimitProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.TextView.BackgroundRenderers.Add(_columnLimitBackgroundRenderer);
                    }
                    else
                    {
                        TextArea.TextView.BackgroundRenderers.Remove(_columnLimitBackgroundRenderer);
                    }
                }),

                this.GetObservable(ColumnLimitProperty).Subscribe(limit =>
                {
                    _columnLimitBackgroundRenderer.Column = limit;
                    this.TextArea.TextView.InvalidateLayer(KnownLayer.Background);
                }),

                this.GetObservable(ContextActionsIconProperty).Subscribe(icon =>
                {
                    if (_contextActionsRenderer != null)
                    {
                        _contextActionsRenderer.IconImage = icon;
                    }
                }),

                this.GetObservable(ColorSchemeProperty).Subscribe(colorScheme =>
                {
                    if (colorScheme != null)
                    {
                        Background = colorScheme.Background;
                        Foreground = colorScheme.Text;

                        _lineNumberMargin.Background = colorScheme.Background;

                        if (_diagnosticMarkersRenderer != null)
                        {
                            _diagnosticMarkersRenderer.ColorScheme = colorScheme;
                        }

                        _textColorizer?.RecalculateBrushes();
                        TextArea.TextView.InvalidateLayer(KnownLayer.Background);
                        TextArea.TextView.Redraw();
                    }
                }),

                this.GetObservable(CaretOffsetProperty).Subscribe(s =>
                {
                    if (Document?.TextLength > s)
                    {
                        CaretOffset = s;
                        TextArea.Caret.BringCaretToView();
                    }
                }),

                BackgroundRenderersProperty.Changed.Subscribe(s =>
                {
                    if (s.Sender == this)
                    {
                        if (s.OldValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.OldValue)
                            {
                                TextArea.TextView.BackgroundRenderers.Remove(renderer);
                            }
                        }

                        if (s.NewValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.NewValue)
                            {
                                TextArea.TextView.BackgroundRenderers.Add(renderer);
                            }
                        }
                    }
                }),

                DocumentLineTransformersProperty.Changed.Subscribe(s =>
                {
                    if (s.Sender == this)
                    {
                        if (s.OldValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.OldValue)
                            {
                                TextArea.TextView.LineTransformers.Remove(renderer);
                            }
                        }

                        if (s.NewValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.NewValue)
                            {
                                TextArea.TextView.LineTransformers.Add(renderer);
                            }
                        }
                    }
                }),

                Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Subscribe(e =>
                {
                    if (_isLoaded && Document != null)
                    {
                        _lastLine = TextArea.Caret.Line;

                        EditorCaretOffset = TextArea.Caret.Offset;
                        Line   = TextArea.Caret.Line;
                        Column = TextArea.Caret.Column;

                        var location = new TextViewPosition(Document.GetLocation(CaretOffset));

                        var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                        var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                        var position = visualLocation - TextArea.TextView.ScrollOffset;
                        position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                        _intellisenseControl.SetLocation(position);
                    }
                }),

                Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Throttle(TimeSpan.FromMilliseconds(100)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(e =>
                {
                    if (Document != null)
                    {
                        var location = new TextViewPosition(Document.GetLocation(CaretOffset));

                        if (_intellisenseManager != null && !_textEntering)
                        {
                            if (TextArea.Selection.IsEmpty)
                            {
                                _intellisenseManager.SetCursor(CaretOffset, location.Line, location.Column, UnsavedFiles.ToList());
                            }
                            else if (_currentSnippetContext != null)
                            {
                                var offset = Document.GetOffset(TextArea.Selection.StartPosition.Location);
                                _intellisenseManager.SetCursor(offset, TextArea.Selection.StartPosition.Line, TextArea.Selection.StartPosition.Column, UnsavedFiles.ToList());
                            }
                        }

                        _selectedWordBackgroundRenderer.SelectedWord = GetWordAtOffset(CaretOffset);

                        TextArea.TextView.InvalidateLayer(KnownLayer.Background);
                    }
                }),

                this.WhenAnyValue(x => x.DebugHighlight).Where(loc => loc != null).Subscribe(location =>
                {
                    if (location.Line != -1)
                    {
                        SetDebugHighlight(location.Line, location.StartColumn, location.EndColumn);
                    }
                    else
                    {
                        ClearDebugHighlight();
                    }
                }),
                this.GetObservable(EditorProperty).Subscribe(editor =>
                {
                    if (editor != null)
                    {
                        if (editor.SourceFile.Project?.Solution != null)
                        {
                            _snippetManager.InitialiseSnippetsForSolution(editor.SourceFile.Project.Solution);
                        }

                        if (editor.SourceFile.Project != null)
                        {
                            _snippetManager.InitialiseSnippetsForProject(editor.SourceFile.Project);
                        }

                        SyntaxHighlighting = CustomHighlightingManager.Instance.GetDefinition(editor.SourceFile.ContentType);

                        if (editor.Document is AvalonStudioTextDocument td && Document != td.Document)
                        {
                            Document = td.Document;

                            if (editor.Offset <= Document.TextLength)
                            {
                                CaretOffset = editor.Offset;
                            }

                            _textColorizer = new TextColoringTransformer(Document);
                            _scopeLineBackgroundRenderer = new ScopeLineBackgroundRenderer(Document);


                            TextArea.TextView.BackgroundRenderers.Add(_scopeLineBackgroundRenderer);
                            TextArea.TextView.LineTransformers.Insert(0, _textColorizer);

                            _diagnosticMarkersRenderer = new TextMarkerService(Document);
                            _contextActionsRenderer    = new ContextActionsRenderer(this, _diagnosticMarkersRenderer);
                            TextArea.LeftMargins.Add(_contextActionsRenderer);
                            TextArea.TextView.BackgroundRenderers.Add(_diagnosticMarkersRenderer);
                        }

                        if (editor is ICodeEditor codeEditor)
                        {
                            if (codeEditor.Highlights != null)
                            {
                                _disposables.Add(
                                    Observable.FromEventPattern <NotifyCollectionChangedEventArgs>(codeEditor.Highlights, nameof(codeEditor.Highlights.CollectionChanged))
                                    .Subscribe(observer =>
                                {
                                    var e = observer.EventArgs;

                                    switch (e.Action)
                                    {
                                    case NotifyCollectionChangedAction.Add:
                                        foreach (var(tag, highlightList) in  e.NewItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>())
                                        {
                                            _textColorizer.SetTransformations(tag, highlightList);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Remove:
                                        foreach (var(tag, highlightList) in  e.OldItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>())
                                        {
                                            _textColorizer.RemoveAll(i => i.Tag == tag);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Reset:
                                        foreach (var(tag, highlightList) in  e.OldItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>())
                                        {
                                            _textColorizer.RemoveAll(i => true);
                                        }
                                        break;

                                    default:
                                        throw new NotSupportedException();
                                    }

                                    TextArea.TextView.Redraw();
                                }));

                                _disposables.Add(
                                    Observable.FromEventPattern <NotifyCollectionChangedEventArgs>(codeEditor.Diagnostics, nameof(codeEditor.Diagnostics.CollectionChanged))
                                    .Subscribe(observer =>
                                {
                                    var e = observer.EventArgs;

                                    switch (e.Action)
                                    {
                                    case NotifyCollectionChangedAction.Add:
                                        foreach (var(tag, diagnostics) in  e.NewItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>())
                                        {
                                            _diagnosticMarkersRenderer.SetDiagnostics(tag, diagnostics);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Remove:
                                        foreach (var(tag, diagnostics) in  e.OldItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>())
                                        {
                                            _diagnosticMarkersRenderer.RemoveAll(x => x.Tag == tag);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Reset:
                                        foreach (var(tag, diagnostics) in  e.OldItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>())
                                        {
                                            _diagnosticMarkersRenderer.RemoveAll(i => true);
                                        }
                                        break;

                                    default:
                                        throw new NotSupportedException();
                                    }

                                    TextArea.TextView.Redraw();
                                    _contextActionsRenderer.OnDiagnosticsUpdated();
                                }));

                                _disposables.Add(codeEditor.WhenAnyValue(x => x.CodeIndex).Subscribe(codeIndex =>
                                {
                                    _scopeLineBackgroundRenderer.ApplyIndex(codeIndex);
                                }));

                                _scopeLineBackgroundRenderer.ApplyIndex(codeEditor.CodeIndex);

                                foreach (var(tag, diagnostics) in codeEditor.Diagnostics)
                                {
                                    _diagnosticMarkersRenderer.SetDiagnostics(tag, diagnostics);
                                }

                                foreach (var(tag, highlights) in codeEditor.Highlights)
                                {
                                    _textColorizer.SetTransformations(tag, highlights);
                                }

                                TextArea.TextView.Redraw();
                            }

                            _intellisenseManager = new IntellisenseManager(editor, Intellisense, _completionAssistant, codeEditor.LanguageService, editor.SourceFile, offset =>
                            {
                                var location = new TextViewPosition(Document.GetLocation(offset));

                                var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                                var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                                var position = visualLocation - TextArea.TextView.ScrollOffset;
                                position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                                _completionAssistantControl.SetLocation(position);
                            });

                            _disposables.Add(_intellisenseManager);

                            foreach (var contextActionProvider in codeEditor.LanguageService.GetContextActionProviders())
                            {
                                _contextActionsRenderer.Providers.Add(contextActionProvider);
                            }
                        }

                        Dispatcher.UIThread.Post(() =>
                        {
                            TextArea.ScrollToLine(Line);
                            Focus();
                        });
                    }
                    else
                    {
                        if (Document != null)
                        {
                            Document = null;
                        }
                    }
                }),
                this.GetObservable(RenameOpenProperty).Subscribe(open =>
                {
                    if (_isLoaded && Editor != null)
                    {
                        var token    = Editor.Document.GetToken(CaretOffset);
                        var location = new TextViewPosition(Document.GetLocation(token.Offset));

                        var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                        var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                        var position = visualLocation - TextArea.TextView.ScrollOffset;
                        position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                        _renameControl.SetLocation(position);
                        _renameControl.Open(this, Editor.Document.GetText(token));
                    }
                }),

                AddHandler(KeyDownEvent, tunneledKeyDownHandler, RoutingStrategies.Tunnel),
                AddHandler(KeyUpEvent, tunneledKeyUpHandler, RoutingStrategies.Tunnel)
            };

            Options = new AvaloniaEdit.TextEditorOptions
            {
                ConvertTabsToSpaces   = true,
                IndentationSize       = 4,
                EnableHyperlinks      = false,
                EnableEmailHyperlinks = false,
            };

            //BackgroundRenderersProperty.Changed.Subscribe(s =>
            //{
            //    if (s.Sender == this)
            //    {
            //        if (s.OldValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IBackgroundRenderer>)s.OldValue)
            //            {
            //                TextArea.TextView.BackgroundRenderers.Remove(renderer);
            //            }
            //        }

            //        if (s.NewValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IBackgroundRenderer>)s.NewValue)
            //            {
            //                TextArea.TextView.BackgroundRenderers.Add(renderer);
            //            }
            //        }
            //    }
            //});

            //DocumentLineTransformersProperty.Changed.Subscribe(s =>
            //{
            //    if (s.Sender == this)
            //    {
            //        if (s.OldValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IVisualLineTransformer>)s.OldValue)
            //            {
            //                TextArea.TextView.LineTransformers.Remove(renderer);
            //            }
            //        }

            //        if (s.NewValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IVisualLineTransformer>)s.NewValue)
            //            {
            //                TextArea.TextView.LineTransformers.Add(renderer);
            //            }
            //        }
            //    }
            //});


            /*_analysisTriggerEvents.Select(_ => Observable.Timer(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance)
             * .SelectMany(o => DoCodeAnalysisAsync())).Switch().Subscribe(_ => { });*/

            Intellisense = new IntellisenseViewModel();

            _completionAssistant = new CompletionAssistantViewModel(Intellisense);

            TextArea.TextEntering += TextArea_TextEntering;

            TextArea.TextEntered += TextArea_TextEntered;
        }

        ~CodeEditor()
        {
        }
コード例 #55
0
 public MainWindowViewModel()
 {
     CompositeDisposable.Add(SubWindowViewModel);
 }
コード例 #56
0
        public static Parser Create(
            IServiceCollection services,
            StartServer startServer = null,
            Jupyter jupyter         = null,
            StartStdIO startStdIO   = null,
            StartHttp startHttp     = null,
            ITelemetry telemetry    = null,
            IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var disposeOnQuit = new CompositeDisposable();

            startServer ??= (startupOptions, invocationContext) =>
            {
                var webHost = Program.ConstructWebHost(startupOptions);
                disposeOnQuit.Add(webHost);
                webHost.Run();
            };

            jupyter ??= JupyterCommand.Do;

            startStdIO ??= StdIOCommand.Do;

            startHttp ??= HttpCommand.Do;

            // Setup first time use notice sentinel.
            firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion);

            var clearTextProperties = new[]
            {
                "frontend"
            };

            // Setup telemetry.
            telemetry ??= new Telemetry.Telemetry(
                VersionSensor.Version().AssemblyInformationalVersion,
                firstTimeUseNoticeSentinel,
                "dotnet/interactive/cli");

            var filter = new TelemetryFilter(
                Sha256Hasher.HashWithNormalizedCasing,
                clearTextProperties,
                (commandResult, directives, entryItems) =>
            {
                // add frontend
                var frontendTelemetryAdded = false;
                foreach (var directive in directives)
                {
                    switch (directive.Key)
                    {
                    case "vscode":
                    case "jupyter":
                    case "synapse":
                        frontendTelemetryAdded = true;
                        entryItems.Add(new KeyValuePair <string, string>("frontend", directive.Key));
                        break;
                    }
                }

                if (!frontendTelemetryAdded)
                {
                    if (commandResult.Command.Name == "jupyter")
                    {
                        entryItems.Add(new KeyValuePair <string, string>("frontend", "jupyter"));
                    }
                }
            });

            var verboseOption = new Option <bool>(
                "--verbose",
                "Enable verbose logging to the console");

            var logPathOption = new Option <DirectoryInfo>(
                "--log-path",
                "Enable file logging to the specified directory");

            var pathOption = new Option <DirectoryInfo>(
                "--path",
                "Installs the kernelspecs to the specified directory")
                             .ExistingOnly();

            var defaultKernelOption = new Option <string>(
                "--default-kernel",
                description: "The default language for the kernel",
                getDefaultValue: () => "csharp");

            var rootCommand = DotnetInteractive();

            rootCommand.AddCommand(Jupyter());
            rootCommand.AddCommand(StdIO());
            rootCommand.AddCommand(HttpServer());

            return(new CommandLineBuilder(rootCommand)
                   .UseDefaults()
                   .UseMiddleware(async(context, next) =>
            {
                if (context.ParseResult.Errors.Count == 0)
                {
                    telemetry.SendFiltered(filter, context.ParseResult);
                }

                // If sentinel does not exist, print the welcome message showing the telemetry notification.
                if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.Telemetry.SkipFirstTimeExperience)
                {
                    context.Console.Out.WriteLine();
                    context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage);

                    firstTimeUseNoticeSentinel.CreateIfNotExists();
                }

                await next(context);
            })
                   .Build());

            RootCommand DotnetInteractive()
            {
                var command = new RootCommand
                {
                    Name        = "dotnet-interactive",
                    Description = "Interactive programming for .NET."
                };

                command.AddGlobalOption(logPathOption);
                command.AddGlobalOption(verboseOption);

                return(command);
            }

            Command Jupyter()
            {
                var httpPortRangeOption = new Option <HttpPortRange>(
                    "--http-port-range",
                    parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result),
                    description: "Specifies the range of ports to use to enable HTTP services",
                    isDefault: true);

                var command = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel")
                {
                    defaultKernelOption,
                    httpPortRangeOption,
                    new Argument <FileInfo>
                    {
                        Name = "connection-file"
                    }.ExistingOnly()
                };

                command.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext, CancellationToken>(JupyterHandler);

                var installCommand = new Command("install", "Install the .NET kernel for Jupyter")
                {
                    httpPortRangeOption,
                    pathOption
                };

                installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, HttpPortRange, DirectoryInfo>(InstallHandler);

                command.AddCommand(installCommand);

                return(command);

                Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context, CancellationToken cancellationToken)
                {
                    services = RegisterKernelInServiceCollection(
                        services,
                        startupOptions,
                        options.DefaultKernel,
                        serviceCollection =>
                    {
                        serviceCollection.AddSingleton(_ => new HtmlNotebookFrontedEnvironment());
                        serviceCollection.AddSingleton <FrontendEnvironment>(c =>
                                                                             c.GetService <HtmlNotebookFrontedEnvironment>());
                    });

                    services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile))
                    .AddSingleton(c =>
                    {
                        return(CommandScheduler.Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >()
                                                                               .Trace()
                                                                               .Handle(delivery)));
                    })
                    .AddSingleton(c => new JupyterRequestContextHandler(
                                      c.GetRequiredService <IKernel>())
                                  .Trace())
                    .AddSingleton <IHostedService, Shell>()
                    .AddSingleton <IHostedService, Heartbeat>();

                    return(jupyter(startupOptions, console, startServer, context));
                }

                Task <int> InstallHandler(IConsole console, InvocationContext context, HttpPortRange httpPortRange, DirectoryInfo path)
                {
                    var jupyterInstallCommand = new JupyterInstallCommand(console, new JupyterKernelSpecInstaller(console), httpPortRange, path);

                    return(jupyterInstallCommand.InvokeAsync());
                }
            }

            Command HttpServer()
            {
                var httpPortOption = new Option <HttpPort>(
                    "--http-port",
                    description: "Specifies the port on which to enable HTTP services",
                    parseArgument: result =>
                {
                    if (result.Tokens.Count == 0)
                    {
                        return(HttpPort.Auto);
                    }

                    var source = result.Tokens[0].Value;

                    if (source == "*")
                    {
                        return(HttpPort.Auto);
                    }

                    if (!int.TryParse(source, out var portNumber))
                    {
                        result.ErrorMessage = "Must specify a port number or *.";
                        return(null);
                    }

                    return(new HttpPort(portNumber));
                },
                    isDefault: true);

                var command = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http")
                {
                    defaultKernelOption,
                    httpPortOption
                };

                command.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>(
                    (startupOptions, options, console, context) =>
                {
                    RegisterKernelInServiceCollection(
                        services,
                        startupOptions,
                        options.DefaultKernel,
                        serviceCollection =>
                    {
                        serviceCollection.AddSingleton(_ =>
                        {
                            var frontendEnvironment = new BrowserFrontendEnvironment();
                            return(frontendEnvironment);
                        });
                        serviceCollection.AddSingleton <FrontendEnvironment>(c => c.GetRequiredService <BrowserFrontendEnvironment>());
                    });
                    return(startHttp(startupOptions, console, startServer, context));
                });

                return(command);
            }

            Command StdIO()
            {
                var httpPortRangeOption = new Option <HttpPortRange>(
                    "--http-port-range",
                    parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result),
                    description: "Specifies the range of ports to use to enable HTTP services");

                var command = new Command(
                    "stdio",
                    "Starts dotnet-interactive with kernel functionality exposed over standard I/O")
                {
                    defaultKernelOption,
                    httpPortRangeOption
                };

                command.Handler = CommandHandler.Create <StartupOptions, StdIOOptions, IConsole, InvocationContext, CancellationToken>(
                    (startupOptions, options, console, context, cancellationToken) =>
                {
                    if (startupOptions.EnableHttpApi)
                    {
                        RegisterKernelInServiceCollection(
                            services,
                            startupOptions,
                            options.DefaultKernel,
                            serviceCollection =>
                        {
                            serviceCollection.AddSingleton(_ => new HtmlNotebookFrontedEnvironment());
                            serviceCollection.AddSingleton <FrontendEnvironment>(c =>
                                                                                 c.GetService <HtmlNotebookFrontedEnvironment>());
                        }, kernel =>
                        {
                            StdIOCommand.CreateServer(kernel, console);

                            kernel.UseQuiCommand(disposeOnQuit, cancellationToken);
                        });

                        return(startHttp(startupOptions, console, startServer, context));
                    }

                    {
                        var kernel = CreateKernel(options.DefaultKernel, new BrowserFrontendEnvironment(),
                                                  startupOptions);
                        disposeOnQuit.Add(kernel);
                        kernel.UseQuiCommand(disposeOnQuit, cancellationToken);


                        return(startStdIO(
                                   startupOptions,
                                   kernel,
                                   console));
                    }
                });

                return(command);
            }
コード例 #57
0
 public PackageTests(ITestOutputHelper output)
 {
     _disposables.Add(output.SubscribeToPocketLogger());
     _disposables.Add(VirtualClock.Start());
 }
コード例 #58
-1
 private static ISampleProvider ReadWaveFile(WaveFileReader reader, CompositeDisposable disposables)
 {
     disposables.Add(reader);
     // if resampling is needed, do it.
     if (reader.WaveFormat.SampleRate != SampleRate)
     {
         var resampler = new MediaFoundationResampler(reader,
                 WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, ChannelCount));
         disposables.Add(resampler);
         return resampler.ToSampleProvider();
     }
     return reader.ToSampleProvider();
 }