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;
        }
        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;
                });
        }
Ejemplo n.º 3
0
        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;
            }
        }
Ejemplo n.º 4
0
    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));
        }
      }
    }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes the listener with the given port.
        /// </summary>
        public ReactiveListener(int port)
        {
            this.port = port;
            tracer.ReactiveListenerCreated(port);

            this.socketDisposable = new CompositeDisposable();
        }
Ejemplo n.º 6
0
 public static void PlaySound(string fileName)
 {
     var disposables = new CompositeDisposable();
     var sampleProvider = GetSampleProvider(fileName, disposables);
     var wrapper = new AutoDisposeSampleProvider(sampleProvider, (IDisposable)disposables);
     AddMixerInput(wrapper);
 }
        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;
            });
        }
Ejemplo n.º 8
0
        public ExecutionContext(TimeSpan skipAhead = default(TimeSpan))
        {
            this.disposables = new CompositeDisposable();
            this.cancelRequested = new BehaviorSubject<bool>(false)
                .AddTo(this.disposables);
            this.progressDeltas = new Subject<TimeSpan>()
                .AddTo(this.disposables);

            this
                .cancelRequested
                .Where(x => x)
                .Subscribe(_ => this.IsCancelled = true)
                .AddTo(this.disposables);

            this
                .progressDeltas
                .Scan((running, next) => running + next)
                .Subscribe(x => this.Progress = x)
                .AddTo(this.disposables);

            this
                .WhenAnyValue(x => x.CurrentExercise)
                .Select(x => this.progressDeltas.StartWith(TimeSpan.Zero).Scan((running, next) => running + next))
                .Switch()
                .Subscribe(x => this.CurrentExerciseProgress = x)
                .AddTo(this.disposables);

            this
                .progressDeltas
                .StartWith(skipAhead)
                .Scan((running, next) => running - next)
                .Select(x => x < TimeSpan.Zero ? TimeSpan.Zero : x)
                .Subscribe(x => this.SkipAhead = x)
                .AddTo(this.disposables);
        }
 public AutoDisposeSampleProvider(ISampleProvider provider,
      IEnumerable<IDisposable> disposables)
 {
     this._provider = provider;
     this._disposables = new CompositeDisposable(disposables);
     this.WaveFormat = provider.WaveFormat;
 }
        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;
            });
        }
        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;
            });
        }
        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;
            });
        }
        public PressableController(FrameworkElement element, PressableModel model, KinectRegion kinectRegion)
        {
            this.element = new WeakReference(element);
            this.kinectRegion = kinectRegion;
            this.inputModel = model;

            if (this.inputModel == null)
                return;

            this.eventSubscriptions = new CompositeDisposable 
            {
                this.inputModel.PressingStartedObservable()
                               .Subscribe(_ => VisualStateManager.GoToState(this.Control, "Focused", true)),

                this.inputModel.HoldingObservable()
                               .Subscribe(_ => Debug.WriteLine(string.Format("Holding: {0}, ", DateTime.Now))),

                this.inputModel.PressingUpdatedObservable()
                               .Subscribe(_ => Debug.WriteLine(string.Format("PressingUpdated: {0}, ", DateTime.Now))),

                this.inputModel.PressingCompletedObservable()
                               .Subscribe(_ => VisualStateManager.GoToState(this.Control, "Unfocused", true)),

                this.inputModel.TappedObservable()
                               .Subscribe(_ => Debug.WriteLine(string.Format("Tapped: {0}, ", DateTime.Now))),
            };
        }
 public void Clear()
 {
     var d = new CompositeDisposable (Disposable.Empty);
     Assert.AreEqual (1, d.Count, "#1");
     d.Clear ();
     Assert.AreEqual (0, d.Count, "#2");
 }
 /// <summary>
 /// This method is to setup an listeners on the EventAggregator, or other initialization requirements.
 /// </summary>
 public virtual void Setup()
 {
     if (Disposer.IsDisposed)
     {
         Disposer = new CompositeDisposable();
     }
 }
        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()
 {
     Command<CustomerAccount>.AuthorizeDefault = (order, command) => true;
     Command<Order>.AuthorizeDefault = (order, command) => true;
     var configuration = new Configuration()
         .UseInMemoryEventStore();
     disposables = new CompositeDisposable(ConfigurationContext.Establish(configuration));
 }
Ejemplo n.º 18
0
 public static void WhenActivated(this IActivatable instance, Action<CompositeDisposable> activate)
 {
   instance.WhenActivated(d => {
     var cd = new CompositeDisposable();
     activate(cd);
     d(cd);
   });
 }
        public void SetUp()
        {
            disposables = new CompositeDisposable();

            Command<Order>.AuthorizeDefault = (order, command) => true;
            EventStoreDbTest.SetConnectionStrings();
            configuration = GetConfiguration();
            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);
        }
        public IDisposable DisplayUndoable(IModelDoc2 modelDoc, double framerate = 30, int layer = 0)
        {
            OnStart(DateTime.Now);

            var d = new CompositeDisposable();
            OpenGlRenderer.DisplayUndoable(this, modelDoc, layer).DisposeWith(d);
            Redraw(modelDoc, framerate).DisposeWith(d);
            return d;
        }
        public ExerciseViewModel(ISchedulerService schedulerService, Exercise model, IObservable<ExecutionContext> executionContext)
        {
            schedulerService.AssertNotNull(nameof(schedulerService));
            model.AssertNotNull(nameof(model));
            executionContext.AssertNotNull(nameof(executionContext));

            this.disposables = new CompositeDisposable();
            this.model = model;

            executionContext
                .ObserveOn(schedulerService.MainScheduler)
                .Subscribe(x => this.ExecutionContext = x)
                .AddTo(this.disposables);

            Observable
                .CombineLatest(
                    this
                        .WhenAnyValue(x => x.ExecutionContext)
                        .Select(ec => ec == null ? Observable.Never<TimeSpan>() : ec.WhenAnyValue(x => x.SkipAhead))
                        .Switch(),
                    this
                        .WhenAnyValue(x => x.ExecutionContext)
                        .Select(ec => ec == null ? Observable.Never<Exercise>() : ec.WhenAnyValue(x => x.CurrentExercise))
                        .Switch(),
                    (skip, current) => skip == TimeSpan.Zero && current == this.model)
                .ObserveOn(schedulerService.MainScheduler)
                .Subscribe(x => this.IsActive = x)
                .AddTo(this.disposables);

            this
                .WhenAnyValue(x => x.ExecutionContext)
                .Select(
                    ec =>
                        ec == null
                            ? Observable.Return(TimeSpan.Zero)
                            : ec
                                .WhenAnyValue(x => x.CurrentExerciseProgress)
                                .Where(_ => ec.CurrentExercise == this.model)
                                .StartWith(TimeSpan.Zero))
                .Switch()
                .ObserveOn(schedulerService.MainScheduler)
                .Subscribe(x => this.ProgressTimeSpan = x)
                .AddTo(this.disposables);

            this
                .WhenAny(
                    x => x.Duration,
                    x => x.ProgressTimeSpan,
                    (duration, progressTimeSpan) => progressTimeSpan.Value.TotalMilliseconds / duration.Value.TotalMilliseconds)
                .Select(progressRatio => double.IsNaN(progressRatio) || double.IsInfinity(progressRatio) ? 0d : progressRatio)
                .Select(progressRatio => Math.Min(1d, progressRatio))
                .Select(progressRatio => Math.Max(0d, progressRatio))
                .ObserveOn(schedulerService.MainScheduler)
                .Subscribe(x => this.Progress = x)
                .AddTo(this.disposables);
        }
Ejemplo n.º 23
0
        public Rfq(IRfqService rfqService, IConcurrencyService concurrencyService)
        {
            _rfqService = rfqService;
            _concurrencyService = concurrencyService;
            _stateMachine = new StateMachine<RfqState, RfqEvent>(RfqState.Input);
            _rfqUpdateSubject = new BehaviorSubject<RfqUpdate>(new RfqUpdate(RfqState.Input, null, null));
            _disposables = new CompositeDisposable(_cancellationSubscription, _executionSubscription, _requestSubscription);

            CreateStateMachine();
        }
        public void DisposeTest()
        {
            var disposes = new CompositeDisposable();
            var dis1 = new DisposeObject1();
           
            disposes.Dispose();
         

            disposes.AddDisposable(new DisposeObject1());
        }
        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));
        }
Ejemplo n.º 26
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();
					});
				});
			}
Ejemplo n.º 27
0
        public MainViewController(IDomainContext context, IRepository<MinionContract> repository, ITransactionRepository transactionRepository)
            : base("MainViewController", null)
        {
            this.context = context;
            this.repository = repository;
            this.transactionRepository = transactionRepository;
            this.lifetime = new CompositeDisposable();

            // TODO: observe deleted events and name changes
               // this.lifetime.Add(this.context.EventBus.Subscribe<IEvent>(this.OnNextEvent));
        }
        public void SetUp()
        {
            Command<Order>.AuthorizeDefault = (order, command) => true;

            disposables = new CompositeDisposable();

            var configuration = new Configuration()
                .UseInMemoryEventStore()
                .UseInMemoryCommandScheduling();
            disposables.Add(ConfigurationContext.Establish(configuration));
        }
Ejemplo n.º 29
0
        public void AddDisposableOnDestroy(IDisposable disposable)
        {
            if (calledDestroy)
            {
                disposable.Dispose();
                return;
            }

            if (disposablesOnDestroy == null) disposablesOnDestroy = new CompositeDisposable();
            disposablesOnDestroy.Add(disposable);
        }
Ejemplo n.º 30
0
        public void DisposeWithOfT_WithTIsNotDiposable_ShouldReturnSut(
            CompositeDisposable compositeDisposable,
            object sut)
        {
            //arrange

            //act
            var actual = sut.DisposeWith(compositeDisposable);

            //assert
            actual.Should().Be(sut);
        }
Ejemplo n.º 31
0
        public SelfCertificateDialog(IServiceProvider serviceProvider, CertificatesFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbStore.SelectedIndex   = 0;
            cbLength.SelectedIndex  = 3;
            cbHashing.SelectedIndex = 1;
            txtCommonName.Text      = Environment.MachineName;
            dtpFrom.Value           = DateTime.Now;
            dtpTo.Value             = dtpFrom.Value.AddYears(1);

            if (Environment.OSVersion.Version < Version.Parse("6.2"))
            {
                // IMPORTANT: WebHosting store is available since Windows 8.
                cbStore.Enabled = false;
            }

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

            var container = new CompositeDisposable();

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

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var names = txtCommonName.Text;
                if (string.IsNullOrWhiteSpace(names))
                {
                    ShowMessage("DNS names cannot be empty.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }

                var dnsNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(item => item.Trim()).ToArray();
                if (dnsNames.Length == 0)
                {
                    ShowMessage("DNS names cannot be empty.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }

                // Generate certificate
                string defaultIssuer  = string.Format("CN={0}", dnsNames[0]);
                string defaultSubject = defaultIssuer;

                string subject = defaultSubject;
                string issuer  = defaultIssuer;

                if (subject == null)
                {
                    throw new Exception("Missing Subject Name");
                }

                DateTime notBefore = dtpFrom.Value;
                DateTime notAfter  = dtpTo.Value;

                var random = new SecureRandom(new CryptoApiRandomGenerator());
                var kpgen  = new RsaKeyPairGenerator();
                kpgen.Init(new KeyGenerationParameters(random, int.Parse(cbLength.Text)));
                var cerKp = kpgen.GenerateKeyPair();

                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(new X509Name(issuer));
                certGen.SetNotBefore(notBefore);
                certGen.SetNotAfter(notAfter);
                if (dnsNames.Length == 1)
                {
                    certGen.SetSubjectDN(new X509Name(subject));
                }

                certGen.SetPublicKey(cerKp.Public);
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

                var keyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cerKp.Public);
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, true, new SubjectKeyIdentifier(keyInfo));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(keyInfo));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

                if (cbGenerate.Checked)
                {
                    var subjectAlternativeNames = new List <Asn1Encodable>();
                    foreach (var item in dnsNames)
                    {
                        subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, item));
                    }
                    var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames.ToArray());
                    certGen.AddExtension(X509Extensions.SubjectAlternativeName, true, subjectAlternativeNamesExtension);
                }

                string hashName = cbHashing.SelectedIndex == 0 ? "SHA1WithRSA" : "SHA256WithRSA";
                var factory     = new Asn1SignatureFactory(hashName, cerKp.Private, random);

                string p12File = Path.GetTempFileName();
                string p12pwd  = "test";

                try
                {
                    Org.BouncyCastle.X509.X509Certificate x509 = certGen.Generate(factory);
                    var store            = new Pkcs12Store();
                    var certificateEntry = new X509CertificateEntry(x509);
                    var friendlyName     = txtName.Text;
                    store.SetCertificateEntry(friendlyName, certificateEntry);
                    store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(cerKp.Private), new[] { certificateEntry });
                    var stream = new MemoryStream();
                    store.Save(stream, p12pwd.ToCharArray(), random);
                    File.WriteAllBytes(p12File, stream.ToArray());

                    Item = new X509Certificate2(p12File, p12pwd)
                    {
                        FriendlyName = friendlyName
                    };
                    Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting";

                    try
                    {
                        using var process = new Process();
                        // add certificate
                        var start             = process.StartInfo;
                        start.Verb            = "runas";
                        start.UseShellExecute = true;
                        start.FileName        = "cmd";
                        start.Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /f:\"{p12File}\" /p:{p12pwd} /n:\"{txtName.Text}\" /s:{(cbStore.SelectedIndex == 0 ? "MY" : "WebHosting")}\"";
                        start.CreateNoWindow  = true;
                        start.WindowStyle     = ProcessWindowStyle.Hidden;
                        process.Start();
                        process.WaitForExit();
                        File.Delete(p12File);
                        if (process.ExitCode == 0)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        else
                        {
                            ShowMessage(process.ExitCode.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        }
                    }
                    catch (Win32Exception ex)
                    {
                        // elevation is cancelled.
                        if (!Microsoft.Web.Administration.NativeMethods.ErrorCancelled(ex.NativeErrorCode))
                        {
                            RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                                { "native", ex.NativeErrorCode }
                            });
                            // throw;
                        }
                    }
                    catch (Exception ex)
                    {
                        RollbarLocator.RollbarInstance.Error(ex);
                    }
                }
                catch (Exception ex)
                {
                    RollbarLocator.RollbarInstance.Error(ex);
                    ShowError(ex, Text, false);
                    return;
                }
            }));

            container.Add(
                Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(EnvironmentVariableTarget =>
            {
                feature.ShowHelp();
            }));
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            // host and port can be specified in the constructor or Connect()
            using (var client = new TwsClient(clientId: 1, host: "127.0.0.1", port: 7496))
                using (var subscriptions = new CompositeDisposable())
                {
                    // The errors observable is always available
                    // Here we just print them all to the console
                    subscriptions.Add(client.Errors.Subscribe(
                                          et => Console.WriteLine("TWS {2} #{0}: {1}", et.Code, et.Message, et.IsError()? "error" : "message"),
                                          ex => Console.WriteLine("TWS Exception: {0}", ex.Message)
                                          ));

                    Console.WriteLine("Connecting to TWS...");
                    try
                    {
                        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
                        client.Connect(ct: cts.Token); // disposing will disconnect
                    }
                    catch
                    {
                        Console.WriteLine("Connection failed, exiting...");
                        return;
                    }
                    Console.WriteLine("Connected.");


                    var contract = new Contract()
                    {
                        Symbol   = "MSFT",
                        Exchange = "SMART",
                        SecType  = "STK",
                        Currency = "USD",
                    };

                    Console.WriteLine("Intraday data:");
                    IObservable <Bar> hdata = client.RequestHistoricalData(
                        contract,
                        DateTime.Now,
                        duration: "1 D", // 1 day window
                        barSizeSetting: "30 mins",
                        whatToShow: "TRADES",
                        useRTH: true
                        );
                    // hdata is a cold observable; the request to TWS is sent on subscription
                    // Since Main() is not async, we cannot use await here
                    try
                    {
                        hdata.Do(Console.WriteLine).Timeout(TimeSpan.FromSeconds(15)).Wait();
                    }
                    catch (TimeoutException ex)
                    {
                        Console.WriteLine(ex.Message);
                        return;
                    }

                    // Example: this is what it would look like with await
                    //await hdata.Do(Console.WriteLine);

                    // It also can be done w/o using Do() but with more ceremony.
                    // Since it is a cold observable, it has to be turned hot with Publish()
                    //var pub = hdata.Publish();
                    //var subj = pub.Subscribe(Console.WriteLine);
                    //var con = pub.Connect();
                    //await pub;
                    //subj.Dispose();
                    //con.Dispose();

                    Console.WriteLine("Daily data:");
                    IObservable <Bar> hdata2 = client.RequestHistoricalData(
                        contract,
                        DateTime.Now,
                        duration: "1 W", // 1 week window
                        barSizeSetting: "1 day",
                        whatToShow: "TRADES",
                        useRTH: true
                        );
                    hdata2.Do(bar => Console.WriteLine(bar.ToString(TimeZoneInfo.Utc))).Wait();

                    Console.WriteLine("Press ENTER to disconnect.");
                    Console.ReadLine();
                }
            Console.WriteLine("Finished.");
        }
Ejemplo n.º 33
0
 public MediaInfoViewModel()
 {
     _CompositeDisposable = new CompositeDisposable();
 }
Ejemplo n.º 34
0
        public BindingDialog(IServiceProvider serviceProvider, Binding binding1, Site site)
            : base(serviceProvider)
        {
            InitializeComponent();
            Binding = binding1;
            Text    = Binding == null ? "Create Site Binding" : "Edit Site Binding";
            DialogHelper.LoadAddresses(cbAddress);
            txtPort.Text         = "80";
            cbType.SelectedIndex = 0;
            if (!site.Server.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }

            if (Binding == null)
            {
                txtHost.Text = site.Server.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
            }
            else
            {
                cbType.Text    = Binding.Protocol;
                cbType.Enabled = Binding == null;
                cbAddress.Text = Binding.EndPoint.Address.AddressToCombo();
                txtPort.Text   = Binding.EndPoint.Port.ToString();
                txtHost.Text   = Binding.Host.HostToDisplay();
                if (site.Server.SupportsSni)
                {
                    cbSniRequired.Checked = Binding.GetIsSni();
                }
            }

            var container = new CompositeDisposable();

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                IPAddress address;
                try
                {
                    address = cbAddress.Text.ComboToAddress();
                }
                catch (Exception)
                {
                    MessageBox.Show("The specified IP address is invalid. Specify a valid IP address.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                int port;
                try
                {
                    port = int.Parse(txtPort.Text);
                }
                catch (Exception)
                {
                    MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (port < 1 || port > 65535)
                {
                    MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();
                foreach (var ch in invalid)
                {
                    if (txtHost.Text.Contains(ch))
                    {
                        MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (site.Server.Mode == WorkingMode.IisExpress)
                {
                    if (txtHost.Text != "localhost")
                    {
                        MessageBox.Show(
                            "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                            Text,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }

                var certificate = cbCertificates.SelectedItem as CertificateInfo;
                var host        = txtHost.Text.DisplayToHost();
                var binding     = new Binding(
                    cbType.Text,
                    $"{address.AddressToDisplay()}:{port}:{host.HostToDisplay()}",
                    cbType.Text == "https" ? certificate?.Certificate.GetCertHash() : new byte[0],
                    cbType.Text == "https" ? certificate?.Store : null,
                    cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                    site.Bindings);
                var matched = site.Parent.FindDuplicate(binding, site, Binding);
                if (matched == true)
                {
                    var result = ShowMessage(
                        $"The binding '{Binding}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button1);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (matched == null)
                {
                    ShowMessage(
                        "The specific port is being used by a different binding.",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                if (Binding == null)
                {
                    Binding = binding;
                }
                else
                {
                    Binding.Reinitialize(binding);
                }

                if (site.Server.Mode == WorkingMode.IisExpress)
                {
                    var result = Binding.FixCertificateMapping(certificate?.Certificate);
                    if (!string.IsNullOrEmpty(result))
                    {
                        MessageBox.Show($"The binding '{Binding}' is invalid: {result}", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbType, "SelectedIndexChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtPort.Text            = cbType.Text == "http" ? "80" : "443";
                txtCertificates.Visible = cbType.SelectedIndex == 1;
                cbSniRequired.Visible   = cbType.SelectedIndex == 1;
                cbCertificates.Visible  = cbType.SelectedIndex == 1;
                btnSelect.Visible       = cbType.SelectedIndex == 1;
                btnView.Visible         = cbType.SelectedIndex == 1;
            }));

            var certificatesSelected = Observable.FromEventPattern <EventArgs>(cbCertificates, "SelectedIndexChanged");

            container.Add(
                certificatesSelected
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnView.Enabled = cbCertificates.SelectedIndex > 0;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbAddress, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPort, "TextChanged"))
                .Merge(certificatesSelected)
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Helper.IsRunningOnMono())
                {
                    return;
                }

                var toElevate = BindingUtility.Verify(cbType.Text, cbAddress.Text, txtPort.Text, cbCertificates.SelectedItem as CertificateInfo);
                btnOK.Enabled = toElevate != null;
                if (!toElevate.HasValue || !toElevate.Value)
                {
                    JexusManager.NativeMethods.RemoveShieldFromButton(btnOK);
                }
                else
                {
                    JexusManager.NativeMethods.TryAddShieldToButton(btnOK);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnView, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.DisplayCertificate(((CertificateInfo)cbCertificates.SelectedItem).Certificate, Handle);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSelect, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                // TODO:
            }));
        }
Ejemplo n.º 35
0
        public VideoInfoControlViewModel(NicoVideo nicoVideo, PageManager pageManager, bool isNgEnabled = true, PlaylistItem playlistItem = null)
        {
            PageManager          = pageManager;
            HohoemaPlaylist      = nicoVideo.HohoemaApp.Playlist;
            NicoVideo            = nicoVideo;
            PlaylistItem         = playlistItem;
            _CompositeDisposable = new CompositeDisposable();

            _IsNGEnabled = isNgEnabled;

            Title      = nicoVideo.Title;
            RawVideoId = nicoVideo.RawVideoId;
            VideoId    = nicoVideo.VideoId;

            if (nicoVideo.IsDeleted)
            {
                Description = "Deleted";
            }

            IsRequireConfirmDelete = new ReactiveProperty <bool>(nicoVideo.IsRequireConfirmDelete);
            PrivateReasonText      = nicoVideo.PrivateReasonType.ToString() ?? "";

            SetupFromThumbnail(nicoVideo);


            QualityDividedVideos = new ObservableCollection <QualityDividedNicoVideoListItemViewModel>();
            NicoVideo.QualityDividedVideos.CollectionChangedAsObservable()
            .Subscribe(_ => ResetQualityDivideVideosVM())
            .AddTo(_CompositeDisposable);

            if (QualityDividedVideos.Count == 0 && NicoVideo.QualityDividedVideos.Count != 0)
            {
                ResetQualityDivideVideosVM();
            }


            IsCacheRequested = NicoVideo.QualityDividedVideos
                               .ObserveElementProperty(x => x.IsCacheRequested)
                               .Select(x => NicoVideo.QualityDividedVideos.Any(y => y.IsCacheRequested))
                               .ToReadOnlyReactiveProperty()
                               .AddTo(_CompositeDisposable);

            IsCacheEnabled = nicoVideo.HohoemaApp.UserSettings.CacheSettings.IsEnableCache;

            Observable.CombineLatest(
                IsCacheRequested,
                NicoVideo.ObserveProperty(x => x.IsPlayed)
                )
            .Select(x =>
            {
                if (x[0])
                {
                    return(Windows.UI.Colors.Green);
                }
                else if (x[1])
                {
                    return(Windows.UI.Colors.Transparent);
                }
                else
                {
                    return(Windows.UI.Colors.Gray);
                }
            })
            .Subscribe(color => ThemeColor = color)
            .AddTo(_CompositeDisposable);
        }
Ejemplo n.º 36
0
        public CodeEditor()
        {
            _codeAnalysisRunner = new JobRunner(1);

            _shell = IoC.Get <IShell>();

            _snippetManager = IoC.Get <SnippetManager>();

            _renameManager = new RenameManager(this);

            _lineNumberMargin = new LineNumberMargin(this);

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

            _selectedLineBackgroundRenderer = new SelectedLineBackgroundRenderer(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.SelectionBrush        = Brush.Parse("#AA569CD6");
            TextArea.SelectionCornerRadius = 0;

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

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

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

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

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

                            if (codeSnippet != null)
                            {
                                var snippet = SnippetParser.Parse(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(ColorSchemeProperty).Subscribe(colorScheme =>
                {
                    if (colorScheme != null)
                    {
                        Background = colorScheme.Background;
                        Foreground = colorScheme.Text;

                        _lineNumberMargin.Background = colorScheme.BackgroundAccent;
                        if (_textColorizer != null)
                        {
                            _textColorizer.ColorScheme = colorScheme;
                        }

                        TextArea.TextView.InvalidateLayer(KnownLayer.Background);

                        TriggerCodeAnalysis();
                    }
                }),

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

                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.Throttle(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(async _ =>
                {
                    await DoCodeAnalysisAsync();
                }),

                this.GetObservableWithHistory(SourceFileProperty).Subscribe((file) =>
                {
                    if (file.Item1 != file.Item2)
                    {
                        using (var fs = file.Item2.OpenText())
                        {
                            using (var reader = new StreamReader(fs))
                            {
                                Document = new TextDocument(reader.ReadToEnd())
                                {
                                    FileName = file.Item2.Location
                                };
                            }
                        }

                        DocumentAccessor = new EditorAdaptor(this);

                        _isLoaded = true;

                        RegisterLanguageService(file.Item2);

                        TextArea.TextView.Redraw();

                        SourceText = Text;
                    }
                }),

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

                        if (line.Length == 0)
                        {
                            _suppressIsDirtyNotifications = true;
                            LanguageService.IndentationStrategy?.IndentLine(Document, line);
                            _suppressIsDirtyNotifications = false;
                        }
                    }

                    _lastLine = TextArea.Caret.Line;
                }),

                Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Throttle(TimeSpan.FromMilliseconds(100)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(e =>
                {
                    if (_intellisenseManager != null && !_textEntering)
                    {
                        if (TextArea.Selection.IsEmpty)
                        {
                            var location = Document.GetLocation(CaretOffset);
                            _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());
                        }
                    }

                    if (CaretOffset > 0)
                    {
                        var prevLocation = new TextViewPosition(Document.GetLocation(CaretOffset - 1));

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

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

                        _intellisenseControl.SetLocation(position);

                        _selectedWordBackgroundRenderer.SelectedWord = GetWordAtOffset(CaretOffset);

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

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

                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);
        }
Ejemplo n.º 37
0
        public PlayViewModel(IScreen screen, ILoginMethods loginMethods)
        {
            HostScreen = screen;
            TogglePlay = new ReactiveCommand();
            Logout     = new ReactiveCommand();
            Search     = new ReactiveCommand();

            // XXX: God I hate that I have to do this
            Observable.Never <Song>().ToProperty(this, x => x.CurrentSong);
            Observable.Never <IEnumerable <Song> >().ToProperty(this, x => x.Queue);
            Observable.Never <IEnumerable <SongTileViewModel> >().ToProperty(this, x => x.AllSongs);

            this.WhenNavigatedTo(() => {
                var playApi = loginMethods.CurrentAuthenticatedClient;
                if (playApi == null)
                {
                    loginMethods.EraseCredentialsAndNavigateToLogin();
                    return(null);
                }

                // Get the Listen URL or die trying
                Observable.Defer(playApi.ListenUrl)
                .Timeout(TimeSpan.FromSeconds(30), RxApp.TaskpoolScheduler)
                .Retry()
                .ToProperty(this, x => x.ListenUrl);

                var pusherSubj = playApi.ConnectToSongChangeNotifications()
                                 .Retry(25)
                                 .Multicast(new Subject <Unit>());

                var shouldUpdate = Observable.Defer(() =>
                                                    pusherSubj.Take(1).Timeout(TimeSpan.FromMinutes(2.0), RxApp.TaskpoolScheduler)).Catch(Observable.Return(Unit.Default))
                                   .Repeat()
                                   .StartWith(Unit.Default)
                                   .Multicast(new Subject <Unit>());

                var nowPlaying = shouldUpdate.SelectMany(_ => playApi.NowPlaying()).Multicast(new Subject <Song>());
                shouldUpdate.SelectMany(_ => playApi.Queue())
                .Catch(Observable.Return(Enumerable.Empty <Song>()))
                .ToProperty(this, x => x.Queue);

                nowPlaying
                .Catch(Observable.Return(new Song()))
                .ToProperty(this, x => x.CurrentSong);

                this.WhenAny(x => x.CurrentSong, x => x.Queue,
                             (song, queue) => (queue.Value != null && song.Value != null ? queue.Value.StartWith(song.Value) : Enumerable.Empty <Song>()))
                .Do(x => this.Log().Info("Found {0} items", x.Count()))
                .Select(x => x.Select(y => new SongTileViewModel(y, loginMethods.CurrentAuthenticatedClient)
                {
                    QueueSongVisibility = Visibility.Collapsed
                }))
                .ToProperty(this, x => x.AllSongs);

                MessageBus.Current.RegisterMessageSource(this.WhenAny(x => x.IsPlaying, x => x.Value), "IsPlaying");

                var ret = new CompositeDisposable();
                ret.Add(nowPlaying.Connect());
                ret.Add(shouldUpdate.Connect());
                ret.Add(pusherSubj.Connect());
                return(ret);
            });

            Logout.Subscribe(_ => loginMethods.EraseCredentialsAndNavigateToLogin());
            Search.Subscribe(_ => screen.Router.Navigate.Execute(RxApp.GetService <ISearchViewModel>()));
        }
Ejemplo n.º 38
0
        private static IDisposable InnerCreateLayer(UIElement owner, LayoutState state)
        {
            var parent          = owner.Visual;
            var compositor      = parent.Compositor;
            var area            = owner.LayoutRound(state.Area);
            var background      = state.Background;
            var borderThickness = owner.LayoutRound(state.BorderThickness);
            var borderBrush     = state.BorderBrush;
            var cornerRadius    = state.CornerRadius;

            var disposables = new CompositeDisposable();
            var sublayers   = new List <Visual>();

            var heightOffset = ((float)borderThickness.Top / 2) + ((float)borderThickness.Bottom / 2);
            var widthOffset  = ((float)borderThickness.Left / 2) + ((float)borderThickness.Right / 2);
            var halfWidth    = (float)area.Width / 2;
            var halfHeight   = (float)area.Height / 2;
            var adjustedArea = area;

            adjustedArea = adjustedArea.DeflateBy(borderThickness);

            if (cornerRadius != CornerRadius.None)
            {
                var maxOuterRadius = Math.Max(0, Math.Min(halfWidth - widthOffset, halfHeight - heightOffset));
                var maxInnerRadius = Math.Max(0, Math.Min(halfWidth, halfHeight));

                cornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxOuterRadius),
                    Math.Min(cornerRadius.TopRight, maxOuterRadius),
                    Math.Min(cornerRadius.BottomRight, maxOuterRadius),
                    Math.Min(cornerRadius.BottomLeft, maxOuterRadius));

                var innerCornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxInnerRadius),
                    Math.Min(cornerRadius.TopRight, maxInnerRadius),
                    Math.Min(cornerRadius.BottomRight, maxInnerRadius),
                    Math.Min(cornerRadius.BottomLeft, maxInnerRadius));

                var borderShape     = compositor.CreateSpriteShape();
                var backgroundShape = compositor.CreateSpriteShape();
                var outerShape      = compositor.CreateSpriteShape();

                // Border brush
                Brush.AssignAndObserveBrush(borderBrush, compositor, brush => borderShape.FillBrush = brush)
                .DisposeWith(disposables);

                // Background brush
                if (background is ImageBrush imgBackground)
                {
                    adjustedArea = CreateImageLayer(compositor, disposables, borderThickness, adjustedArea, backgroundShape, adjustedArea, imgBackground);
                }
                else
                {
                    Brush.AssignAndObserveBrush(background, compositor, brush => backgroundShape.FillBrush = brush)
                    .DisposeWith(disposables);
                }

                var borderPath     = GetRoundedRect(cornerRadius, innerCornerRadius, area, adjustedArea);
                var backgroundPath = GetRoundedPath(cornerRadius, adjustedArea);
                var outerPath      = GetRoundedPath(cornerRadius, area);

                backgroundShape.Geometry = compositor.CreatePathGeometry(backgroundPath);
                borderShape.Geometry     = compositor.CreatePathGeometry(borderPath);
                outerShape.Geometry      = compositor.CreatePathGeometry(outerPath);

                var borderVisual     = compositor.CreateShapeVisual();
                var backgroundVisual = compositor.CreateShapeVisual();
                backgroundVisual.Shapes.Add(backgroundShape);
                borderVisual.Shapes.Add(borderShape);

                sublayers.Add(backgroundVisual);
                sublayers.Add(borderVisual);
                parent.Children.InsertAtBottom(backgroundVisual);
                parent.Children.InsertAtTop(borderVisual);

                owner.ClippingIsSetByCornerRadius = cornerRadius != CornerRadius.None;
                if (owner.ClippingIsSetByCornerRadius)
                {
                    parent.Clip = compositor.CreateGeometricClip(outerShape.Geometry);
                }
            }
            else
            {
                var shapeVisual = compositor.CreateShapeVisual();

                var backgroundShape = compositor.CreateSpriteShape();

                var backgroundArea = area;

                // Background brush
                if (background is ImageBrush imgBackground)
                {
                    backgroundArea = CreateImageLayer(compositor, disposables, borderThickness, adjustedArea, backgroundShape, backgroundArea, imgBackground);
                }
                else
                {
                    Brush.AssignAndObserveBrush(background, compositor, brush => backgroundShape.FillBrush = brush)
                    .DisposeWith(disposables);

                    // This is required because changing the CornerRadius changes the background drawing
                    // implementation and we don't want a rectangular background behind a rounded background.
                    Disposable.Create(() => backgroundShape.FillBrush = null)
                    .DisposeWith(disposables);
                }

                var geometrySource = new SkiaGeometrySource2D();
                var geometry       = geometrySource.Geometry;

                geometry.AddRect(backgroundArea.ToSKRect());

                backgroundShape.Geometry = compositor.CreatePathGeometry(new CompositionPath(geometrySource));

                shapeVisual.Shapes.Add(backgroundShape);

                if (borderThickness != Thickness.Empty)
                {
                    Action <Action <CompositionSpriteShape, SKPath> > createLayer = builder =>
                    {
                        var spriteShape = compositor.CreateSpriteShape();
                        var geometry    = new SkiaGeometrySource2D();

                        // Border brush
                        Brush.AssignAndObserveBrush(borderBrush, compositor, brush => spriteShape.StrokeBrush = brush)
                        .DisposeWith(disposables);

                        builder(spriteShape, geometry.Geometry);
                        spriteShape.Geometry = compositor.CreatePathGeometry(new CompositionPath(geometry));

                        shapeVisual.Shapes.Add(spriteShape);
                    };

                    if (borderThickness.Top != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.StrokeThickness         = (float)borderThickness.Top;
                            var StrokeThicknessAdjust = (float)(borderThickness.Top / 2);
                            path.MoveTo((float)(area.X + borderThickness.Left), (float)(area.Y + StrokeThicknessAdjust));
                            path.LineTo((float)(area.X + area.Width - borderThickness.Right), (float)(area.Y + StrokeThicknessAdjust));
                            path.Close();
                        });
                    }

                    if (borderThickness.Bottom != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.StrokeThickness         = (float)borderThickness.Bottom;
                            var StrokeThicknessAdjust = borderThickness.Bottom / 2;
                            path.MoveTo((float)(area.X + (float)borderThickness.Left), (float)(area.Y + area.Height - StrokeThicknessAdjust));
                            path.LineTo((float)(area.X + area.Width - (float)borderThickness.Right), (float)(area.Y + area.Height - StrokeThicknessAdjust));
                            path.Close();
                        });
                    }

                    if (borderThickness.Left != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.StrokeThickness         = (float)borderThickness.Left;
                            var StrokeThicknessAdjust = borderThickness.Left / 2;
                            path.MoveTo((float)(area.X + StrokeThicknessAdjust), (float)area.Y);
                            path.LineTo((float)(area.X + StrokeThicknessAdjust), (float)(area.Y + area.Height));
                            path.Close();
                        });
                    }

                    if (borderThickness.Right != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.StrokeThickness         = (float)borderThickness.Right;
                            var StrokeThicknessAdjust = borderThickness.Right / 2;
                            path.MoveTo((float)(area.X + area.Width - StrokeThicknessAdjust), (float)area.Y);
                            path.LineTo((float)(area.X + area.Width - StrokeThicknessAdjust), (float)(area.Y + area.Height));
                            path.Close();
                        });
                    }
                }

                sublayers.Add(shapeVisual);

                // Must be inserted below the other subviews, which may happen when
                // the current view has subviews.
                parent.Children.InsertAtBottom(shapeVisual);
            }

            disposables.Add(() =>
            {
                owner.ClippingIsSetByCornerRadius = false;

                foreach (var sv in sublayers)
                {
                    parent.Children.Remove(sv);
                    sv.Dispose();
                }
            }
                            );

            compositor.InvalidateRender();

            return(disposables);
        }
Ejemplo n.º 39
0
        internal LowryViewModel(IAppService appService, IAppSettings appSettings, LowryState lowryState)
        {
            _appService  = appService;
            _appSettings = appSettings;
            _lowryState  = lowryState;

            PlotModel = new PlotModel
            {
                Title           = _lowryState.ChartTitle,
                IsLegendVisible = true,
                LegendPosition  = LegendPosition.BottomRight
            };

            PlotModel.MouseDown += HandlePlotModelMouseDown;

            _lowryStackAxis = new CategoryAxis
            {
                Position      = AxisPosition.Bottom,
                Key           = nameof(_lowryStackAxis),
                Title         = _lowryState.XAxisTitle,
                Angle         = -35,
                IsZoomEnabled = false,
                IsPanEnabled  = false
            };
            PlotModel.Axes.Add(_lowryStackAxis);

            _lowrySmokeAxis = new LinearAxis
            {
                Position        = AxisPosition.Bottom,
                MinimumPadding  = 0,
                MaximumPadding  = 0.06,
                AbsoluteMinimum = 0,
                Minimum         = 0,
                Key             = nameof(_lowrySmokeAxis),
                IsAxisVisible   = false,
                IsZoomEnabled   = false,
                IsPanEnabled    = false
            };
            PlotModel.Axes.Add(_lowrySmokeAxis);

            _lowryVerticalAxis = new LinearAxis
            {
                Position        = AxisPosition.Left,
                MinimumPadding  = 0,
                MaximumPadding  = 0.06,
                AbsoluteMinimum = 0,
                AbsoluteMaximum = 1.0,
                Minimum         = 0.0,
                Maximum         = 1.0,
                Title           = _lowryState.YAxisTitle,
                IsZoomEnabled   = false,
                IsPanEnabled    = false
            };
            PlotModel.Axes.Add(_lowryVerticalAxis);

            _mainEffectsSeries = new ColumnSeries
            {
                Title           = "Main Effects",
                IsStacked       = true,
                StrokeColor     = OxyColors.Black,
                StrokeThickness = 1,
                FillColor       = _lowryState.MainEffectsFillColor ?? OxyColors.ForestGreen,
                XAxisKey        = nameof(_lowryStackAxis)
            };
            _mainEffectsSeries.MouseDown += HandleMainEffectsSeriesMouseDown;

            PlotModel.Series.Add(_mainEffectsSeries);

            _interactionsSeries = new ColumnSeries
            {
                Title           = "Interactions",
                IsStacked       = true,
                StrokeColor     = OxyColors.Black,
                StrokeThickness = 1,
                FillColor       = _lowryState.InteractionsFillColor ?? OxyColors.DarkGoldenrod,
                XAxisKey        = nameof(_lowryStackAxis)
            };
            _interactionsSeries.MouseDown += HandleInteractionsSeriesMouseDown;

            PlotModel.Series.Add(_interactionsSeries);

            _smokeSeries = new AreaSeries
            {
                DataFieldX2     = "IndependentVar",
                DataFieldY2     = "Minimum",
                Fill            = _lowryState.SmokeFill ?? OxyColors.LightBlue,
                Color           = OxyColors.Red,
                MarkerFill      = OxyColors.Transparent,
                StrokeThickness = 0,
                DataFieldX      = "IndependentVar",
                DataFieldY      = "Maximum",
                Title           = "Maximum/Minimum",
                XAxisKey        = nameof(_lowrySmokeAxis),
                RenderInLegend  = false
            };
            PlotModel.Series.Add(_smokeSeries);

            PlotModel.ApplyThemeToPlotModelAndAxes();

            UpdateSize  = ReactiveCommand.Create(HandleUpdateSize);
            ResetAxes   = ReactiveCommand.Create(HandleResetAxes);
            ShowOptions = ReactiveCommand.Create(HandleShowOptions);
            ExportImage = ReactiveCommand.Create(HandleExportImage);

            _reactiveSafeInvoke = appService.GetReactiveSafeInvoke();

            _subscriptions = new CompositeDisposable(

                _appSettings
                .GetWhenPropertyChanged()
                .Subscribe(
                    _reactiveSafeInvoke.SuspendAndInvoke <string?>(
                        ObserveAppSettingsPropertyChange
                        )
                    )

                );
        }
Ejemplo n.º 40
0
        public SslDiagDialog(IServiceProvider provider, ServerManager server)
            : base(provider)
        {
            InitializeComponent();

            // from https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.ikya100/sigalg.htm
            var wellKnownSignatureAlgorithms = new Dictionary <string, bool>
            {
                { "1.2.840.113549.1.1.5", false }, // sha1RSA, not secure
                { "1.2.840.113549.1.1.14", true }, // sha224RSA, secure
                { "1.2.840.113549.1.1.11", true }, // sha256RSA, secure
                { "1.2.840.113549.1.1.12", true }, // sha384RSA, secure
                { "1.2.840.113549.1.1.13", true }, // sha512RSA, secure
                { "1.2.840.10040.4.3", false },    // sha1DSA, not secure
                { "1.2.840.10045.4.1", false },    // sha1ECDSA, not secure
                { "1.2.840.10045.4.3.1", true },   // sha224ECDSA, secure
                { "1.2.840.10045.4.3.2", true },   // sha256ECDSA, secure
                { "1.2.840.10045.4.3.3", true },   // sha384ECDSA, secure
                { "1.2.840.10045.4.3.4", true },   // sha512ECDSA, secure
            };

            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: {server.Mode.AsString(EnumFormat.Description)}");
                    Debug(string.Empty);
                    Debug($"SERVER SSL PROTOCOLS{Environment.NewLine}");
                    bool ssl10Enabled = GetProtocol("PCT 1.0");
                    Debug($"PCT 1.0: {ssl10Enabled}");
                    if (ssl10Enabled)
                    {
                        Warn("PCT 1.0 is not secure. Please disable it.");
                    }

                    bool ssl20Enabled = GetProtocol("SSL 2.0");
                    Debug($"SSL 2.0: {ssl20Enabled}");
                    if (ssl20Enabled)
                    {
                        Warn("SSL 2.0 is not secure. Please disable it.");
                    }

                    bool ssl30Enabled = GetProtocol("SSL 3.0");
                    Debug($"SSL 3.0: {ssl30Enabled}");
                    if (ssl30Enabled)
                    {
                        Warn("SSL 3.0 is not secure. Please disable it.");
                    }

                    Debug($"TLS 1.0: {GetProtocol("TLS 1.0")}");
                    Debug($"TLS 1.1: {GetProtocol("TLS 1.1")}");
                    Debug($"TLS 1.2: {GetProtocol("TLS 1.2")}");
                    Debug($"SChannel EventLogging: {GetEventLogging()} (hex)");
                    Warn($"To tune TLS related settings, try out IIS Crypto from https://www.nartac.com/Products/IISCrypto/.");
                    Debug("-----");

                    foreach (Site site in server.Sites)
                    {
                        Debug($"[W3SVC/{site.Id}]");
                        Debug($"ServerComment  : {site.Name}");
                        Debug($"ServerAutoStart: {site.ServerAutoStart}");
                        Debug($"ServerState    : {site.State}");
                        Debug(string.Empty);
                        foreach (Binding binding in site.Bindings)
                        {
                            Info($"BINDING: {binding.Protocol} {binding}");
                            if (binding.Protocol == "https")
                            {
                                if (binding.CertificateHash == null)
                                {
                                    // SNI mapping missing.
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                    if (binding.SslFlags == SslFlags.Sni)
                                    {
                                        Error(
                                            $"Cannot find {binding.Host}:{binding.EndPoint.Port} combination for this SNI binding.");
                                    }
                                    else
                                    {
                                        var querySslCertificateInfo = Microsoft.Web.Administration.NativeMethods.QuerySslCertificateInfo(
                                            binding.EndPoint);
                                        Error(
                                            querySslCertificateInfo == null
                                                    ? $"Cannot find {binding.EndPoint} combination for this IP based binding."
                                                    : $"Cannot find certificate with thumpprint {querySslCertificateInfo.Hash} in store {querySslCertificateInfo.StoreName}.");
                                    }

                                    Debug(string.Empty);
                                    continue;
                                }

                                var hashString = Hex.ToHexString(binding.CertificateHash);
                                Debug($"SSLCertHash: {hashString}");
                                if (site.Server.SupportsSni)
                                {
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                }

                                Debug("Testing EndPoint: 127.0.0.1");

                                var personal = new X509Store(binding.CertificateStoreName, StoreLocation.LocalMachine);
                                try
                                {
                                    personal.Open(OpenFlags.MaxAllowed);
                                    var selectedItem = personal.Certificates.Find(X509FindType.FindByThumbprint, hashString, false);
                                    if (selectedItem.Count == 0)
                                    {
                                        Error($"Cannot find certificate with thumbprint {hashString} in store {binding.CertificateStoreName}.");
                                    }
                                    else
                                    {
                                        var cert = selectedItem[0];
                                        Debug($"#CertName: {cert.FriendlyName}");
                                        Debug($"#Version: {cert.Version}");
                                        if (cert.HasPrivateKey)
                                        {
                                            if (PublicNativeMethods.IsProcessElevated)
                                            {
                                                var newHandle     = IntPtr.Zero;
                                                int newCount      = 0;
                                                var shouldRelease = false;
                                                if (NativeMethods.CryptAcquireCertificatePrivateKey(
                                                        cert.Handle, 0, IntPtr.Zero, ref newHandle, ref newCount,
                                                        ref shouldRelease))
                                                {
                                                    Debug(
                                                        "#You have a private key that corresponds to this certificate.");
                                                }
                                                else
                                                {
                                                    Error("#You have a private key that corresponds to this certificate but CryptAcquireCertificatePrivateKey failed.");
                                                    RollbarDotNet.Rollbar.Report(
                                                        "CryptAcquireCertificatePrivateKey failed");
                                                }

                                                if (shouldRelease)
                                                {
                                                    NativeMethods.CloseHandle(newHandle);
                                                }
                                            }
                                            else
                                            {
                                                Warn("It seems that you have a private key that corresponds to this certificate. Please run Jexus Manager as administrator and SSL Diag can report in more details.");
                                            }
                                        }
                                        else
                                        {
                                            Error(
                                                "#You don't have a private key that corresponds to this certificate.");
                                        }

                                        var key = cert.PublicKey.Key;
                                        var signatureAlgorithm = cert.SignatureAlgorithm;
                                        Debug($"#Signature Algorithm: {signatureAlgorithm.FriendlyName}");
                                        if (wellKnownSignatureAlgorithms.ContainsKey(signatureAlgorithm.Value))
                                        {
                                            if (!wellKnownSignatureAlgorithms[signatureAlgorithm.Value])
                                            {
                                                Warn("Modern web browsers require signature algorithm to be secure. This signature algorithm is not secure, and might trigger warnings and/or errors.");
                                            }
                                        }
                                        else
                                        {
                                            Warn("This certificate uses a not-well-known signature algorithm, which might not be supported by all web browsers and servers.");
                                        }

                                        Debug($"#Key Exchange Algorithm: {key.KeyExchangeAlgorithm} Key Size: {key.KeySize}");
                                        Debug($"#Subject: {cert.Subject}");
                                        Debug($"#Issuer: {cert.Issuer}");
                                        Debug($"#Validity: From {cert.NotBefore:G} To {cert.NotAfter:G}");
                                        var now = DateTime.UtcNow;
                                        if (now < cert.NotBefore)
                                        {
                                            Warn("This certificate is not yet valid.");
                                        }

                                        if (cert.NotAfter < now)
                                        {
                                            Error("This certificate is already expired.");
                                        }

                                        Debug($"#Serial Number: {cert.SerialNumber}");
                                        Debug($"DS Mapper Usage: {(binding.UseDsMapper ? "Enabled" : "Disabled")}");
                                        Debug($"Archived: {cert.Archived}");

                                        var hasSAN = false;
                                        foreach (var extension in cert.Extensions)
                                        {
                                            if (extension.Oid.Value == "2.5.29.15")
                                            {
                                                Debug($"#Key Usage: {((X509KeyUsageExtension)extension).KeyUsages}");
                                                continue;
                                            }

                                            if (extension.Oid.Value == "2.5.29.37")
                                            {
                                                var usages           = ((X509EnhancedKeyUsageExtension)extension).EnhancedKeyUsages;
                                                var enhancedKeyUsage = usages.Cast <Oid>().Select(usage => $"{usage.FriendlyName} ({usage.Value})")
                                                                       .Combine(",");

                                                Debug($"#Enhanced Key Usage: {enhancedKeyUsage}");
                                                continue;
                                            }

                                            if (extension.Oid.Value == "2.5.29.17")
                                            {
                                                var data = extension.RawData;
                                                AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                                                var name = asndata.Format(true).TrimEnd();
                                                Debug($"#Subject Alternative Name: {name}");
                                                hasSAN = true;
                                                continue;
                                            }

                                            if (extension.Oid.FriendlyName == "Basic Constraints")
                                            {
                                                var ext = (X509BasicConstraintsExtension)extension;
                                                Debug(
                                                    $"#Basic Constraints: Subject Type={(ext.CertificateAuthority ? "CA" : "End Entity")}, Path Length Constraint={(ext.HasPathLengthConstraint ? ext.PathLengthConstraint.ToString() : "None")}");
                                            }
                                        }

                                        if (!hasSAN)
                                        {
                                            Warn("Modern web browsers require Subject Alternative Name extension to present. This certificate does not have SAN extension, so might trigger warnings and/or errors.");
                                        }

                                        X509Chain chain   = X509Chain.Create();
                                        chain.ChainPolicy = new X509ChainPolicy
                                        {
                                            RevocationMode = X509RevocationMode.Online
                                        };
                                        bool valid = chain.Build(cert);
                                        if (valid)
                                        {
                                            Debug("Certificate verified.");
                                        }
                                        else
                                        {
                                            Error("Certificate validation failed.");
                                        }

                                        foreach (var item in chain.ChainStatus)
                                        {
                                            Warn(item.StatusInformation);
                                        }
                                    }

                                    personal.Close();
                                }
                                catch (CryptographicException ex)
                                {
                                    if (ex.HResult != Microsoft.Web.Administration.NativeMethods.NonExistingStore)
                                    {
                                        throw;
                                    }

                                    Error($"Invalid certificate store {binding.CertificateStoreName}.");
                                }
                            }

                            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);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnVerify, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
            }));
        }
 public SynesisAnnotationView()
 {
     InitializeComponent();
     disposables = new CompositeDisposable();
 }
Ejemplo n.º 42
0
        private static IDisposable InnerCreateLayer(CALayer parent, CGRect area, Brush background, Thickness borderThickness, Brush borderBrush, CornerRadius cornerRadius)
        {
            var disposables = new CompositeDisposable();
            var sublayers   = new List <CALayer>();

            var adjustedLineWidth       = borderThickness.Top;
            var adjustedLineWidthOffset = adjustedLineWidth / 2;

            var adjustedArea = area;

            adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

            if (cornerRadius != CornerRadius.None)
            {
                var maxRadius = Math.Max(0, Math.Min((float)area.Width / 2 - adjustedLineWidthOffset, (float)area.Height / 2 - adjustedLineWidthOffset));
                cornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxRadius),
                    Math.Min(cornerRadius.TopRight, maxRadius),
                    Math.Min(cornerRadius.BottomRight, maxRadius),
                    Math.Min(cornerRadius.BottomLeft, maxRadius));

                CAShapeLayer layer = new CAShapeLayer();
                layer.LineWidth = (nfloat)adjustedLineWidth;
                layer.FillColor = null;

                var path = new CGPath();

                Brush.AssignAndObserveBrush(borderBrush, color => layer.StrokeColor = color)
                .DisposeWith(disposables);

                // How AddArcToPoint works:
                // http://www.twistedape.me.uk/blog/2013/09/23/what-arctopointdoes/

                path.MoveToPoint(adjustedArea.GetMidX(), adjustedArea.Y);
                path.AddArcToPoint(adjustedArea.Right, adjustedArea.Top, adjustedArea.Right, adjustedArea.GetMidY(), (float)cornerRadius.TopRight);
                path.AddArcToPoint(adjustedArea.Right, adjustedArea.Bottom, adjustedArea.GetMidX(), adjustedArea.Bottom, (float)cornerRadius.BottomRight);
                path.AddArcToPoint(adjustedArea.Left, adjustedArea.Bottom, adjustedArea.Left, adjustedArea.GetMidY(), (float)cornerRadius.BottomLeft);
                path.AddArcToPoint(adjustedArea.Left, adjustedArea.Top, adjustedArea.GetMidX(), adjustedArea.Top, (float)cornerRadius.TopLeft);

                path.CloseSubpath();

                var lgbBackground  = background as LinearGradientBrush;
                var scbBackground  = background as SolidColorBrush;
                var imgBackground  = background as ImageBrush;
                var insertionIndex = 0;

                if (lgbBackground != null)
                {
                    var fillMask = new CAShapeLayer()
                    {
                        Path  = path,
                        Frame = area,
                        // We only use the fill color to create the mask area
                        FillColor = _Color.White.CGColor,
                    };

                    // We reduce the adjustedArea again so that the gradient is inside the border (like in Windows)
                    adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

                    CreateLinearGradientBrushLayers(area, adjustedArea, parent, sublayers, ref insertionIndex, lgbBackground, fillMask);
                }
                else if (scbBackground != null)
                {
                    Brush.AssignAndObserveBrush(scbBackground, color => layer.FillColor = color)
                    .DisposeWith(disposables);
                }
                else if (imgBackground != null)
                {
                    var uiImage = imgBackground.ImageSource?.ImageData;
                    if (uiImage != null && uiImage.Size != CGSize.Empty)
                    {
                        var fillMask = new CAShapeLayer()
                        {
                            Path  = path,
                            Frame = area,
                            // We only use the fill color to create the mask area
                            FillColor = _Color.White.CGColor,
                        };

                        // We reduce the adjustedArea again so that the image is inside the border (like in Windows)
                        adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

                        CreateImageBrushLayers(area, adjustedArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask);
                    }
                }
                else
                {
                    layer.FillColor = Colors.Transparent;
                }

                layer.Path = path;

                sublayers.Add(layer);
                parent.InsertSublayer(layer, insertionIndex);
            }
            else
            {
                var lgbBackground = background as LinearGradientBrush;
                var scbBackground = background as SolidColorBrush;
                var imgBackground = background as ImageBrush;

                if (lgbBackground != null)
                {
                    var fullArea = new CGRect(
                        area.X + borderThickness.Left,
                        area.Y + borderThickness.Top,
                        area.Width - borderThickness.Left - borderThickness.Right,
                        area.Height - borderThickness.Top - borderThickness.Bottom);

                    var insideArea     = new CGRect(CGPoint.Empty, fullArea.Size);
                    var insertionIndex = 0;

                    CreateLinearGradientBrushLayers(fullArea, insideArea, parent, sublayers, ref insertionIndex, lgbBackground, fillMask: null);
                }
                else if (scbBackground != null)
                {
                    Brush.AssignAndObserveBrush(scbBackground, c => parent.BackgroundColor = c)
                    .DisposeWith(disposables);

                    // This is required because changing the CornerRadius changes the background drawing
                    // implementation and we don't want a rectangular background behind a rounded background.
                    Disposable.Create(() => parent.BackgroundColor = null)
                    .DisposeWith(disposables);
                }
                else if (imgBackground != null)
                {
                    var uiImage = imgBackground.ImageSource?.ImageData;
                    if (uiImage != null && uiImage.Size != CGSize.Empty)
                    {
                        var fullArea = new CGRect(
                            area.X + borderThickness.Left,
                            area.Y + borderThickness.Top,
                            area.Width - borderThickness.Left - borderThickness.Right,
                            area.Height - borderThickness.Top - borderThickness.Bottom);

                        var insideArea     = new CGRect(CGPoint.Empty, fullArea.Size);
                        var insertionIndex = 0;

                        CreateImageBrushLayers(fullArea, insideArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask: null);
                    }
                }
                else
                {
                    parent.BackgroundColor = Colors.Transparent;
                }

                if (borderThickness != Thickness.Empty)
                {
                    var strokeColor = borderBrush ?? SolidColorBrushHelper.Transparent;

                    Action <Action <CAShapeLayer, CGPath> > createLayer = builder =>
                    {
                        CAShapeLayer layer = new CAShapeLayer();
                        var          path  = new CGPath();

                        Brush.AssignAndObserveBrush(borderBrush, c => layer.StrokeColor = c)
                        .DisposeWith(disposables);

                        builder(layer, path);
                        layer.Path = path;

                        // Must be inserted below the other subviews, which may happen when
                        // the current view has subviews.
                        sublayers.Add(layer);
                        parent.InsertSublayer(layer, 0);
                    };

                    if (borderThickness.Top != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Top;
                            var lineWidthAdjust = (nfloat)(borderThickness.Top / 2);
                            path.MoveToPoint(area.X + (nfloat)borderThickness.Left, area.Y + lineWidthAdjust);
                            path.AddLineToPoint(area.X + area.Width - (nfloat)borderThickness.Right, area.Y + lineWidthAdjust);
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Bottom != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Bottom;
                            var lineWidthAdjust = borderThickness.Bottom / 2;
                            path.MoveToPoint(area.X + (nfloat)borderThickness.Left, (nfloat)(area.Y + area.Height - lineWidthAdjust));
                            path.AddLineToPoint(area.X + area.Width - (nfloat)borderThickness.Right, (nfloat)(area.Y + area.Height - lineWidthAdjust));
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Left != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Left;
                            var lineWidthAdjust = borderThickness.Left / 2;
                            path.MoveToPoint((nfloat)(area.X + lineWidthAdjust), area.Y);
                            path.AddLineToPoint((nfloat)(area.X + lineWidthAdjust), area.Y + area.Height);
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Right != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Right;
                            var lineWidthAdjust = borderThickness.Right / 2;
                            path.MoveToPoint((nfloat)(area.X + area.Width - lineWidthAdjust), area.Y);
                            path.AddLineToPoint((nfloat)(area.X + area.Width - lineWidthAdjust), area.Y + area.Height);
                            path.CloseSubpath();
                        });
                    }
                }
            }

            disposables.Add(() =>
            {
                foreach (var sl in sublayers)
                {
                    sl.RemoveFromSuperLayer();
                    sl.Dispose();
                }
            }
                            );
            return(disposables);
        }
Ejemplo n.º 43
0
 public void Setup(CompositeDisposable cd, IEngine engine, State state)
 {
     this.engine = engine;
     this.state  = state;
     cd.Add(this);
 }
Ejemplo n.º 44
0
        public void WatchTables(IList <PinballXSystem> systems)
        {
            const string pattern  = @"^\.vp[tx]$";
            var          trottle  = TimeSpan.FromMilliseconds(100);   // file changes are triggered multiple times
            var          oldPaths = new HashSet <string>(_tableWatches.Keys);
            var          newPaths = systems
                                    .Where(s => s.Enabled)
                                    .Select(s => PathHelper.NormalizePath(s.TablePath) + @"\")
                                    .Distinct()
                                    .Where(Directory.Exists);

            foreach (var newPath in newPaths)
            {
                var disposables = new CompositeDisposable();
                var fsw         = new System.IO.FileSystemWatcher(newPath);
                disposables.Add(fsw);

                // start watching new paths
                if (!oldPaths.Contains(newPath))
                {
                    // file changed
                    disposables.Add(Observable
                                    .FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(x => fsw.Changed += x, x => fsw.Changed -= x)
                                    .Throttle(trottle, RxApp.TaskpoolScheduler)
                                    .Where(x => x.EventArgs.FullPath != null && Regex.IsMatch(Path.GetExtension(x.EventArgs.FullPath), pattern, RegexOptions.IgnoreCase))
                                    .Subscribe(x => _tableFileChanged.OnNext(x.EventArgs.FullPath)));

                    // file created
                    disposables.Add(Observable
                                    .FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(x => fsw.Created += x, x => fsw.Created -= x)
                                    .Where(x => x.EventArgs.FullPath != null && Regex.IsMatch(Path.GetExtension(x.EventArgs.FullPath), pattern, RegexOptions.IgnoreCase))
                                    .Subscribe(x => _tableFileCreated.OnNext(x.EventArgs.FullPath)));

                    // file deleted
                    disposables.Add(Observable
                                    .FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(x => fsw.Deleted += x, x => fsw.Deleted -= x)
                                    .Where(x => x.EventArgs.FullPath != null && Regex.IsMatch(Path.GetExtension(x.EventArgs.FullPath), pattern, RegexOptions.IgnoreCase))
                                    .Subscribe(x => _tableFileDeleted.OnNext(x.EventArgs.FullPath)));

                    // file renamed
                    disposables.Add(Observable
                                    .FromEventPattern <RenamedEventHandler, FileSystemEventArgs>(x => fsw.Renamed += x, x => fsw.Renamed -= x)
                                    .Throttle(trottle, RxApp.TaskpoolScheduler)
                                    .Where(x => x.EventArgs.FullPath != null && Regex.IsMatch(Path.GetExtension(x.EventArgs.FullPath), pattern, RegexOptions.IgnoreCase))
                                    .Subscribe(x => _tableFileRenamed.OnNext(new Tuple <string, string>(((RenamedEventArgs)x.EventArgs).OldFullPath, x.EventArgs.FullPath))));

                    fsw.EnableRaisingEvents = true;

                    _tableWatches.Add(newPath, disposables);
                    _tableFolderAdded.OnNext(newPath);
                    _logger.Info("Started watching table folder {0}", newPath);

                    // ignore already watching paths
                }
                else
                {
                    oldPaths.Remove(newPath);
                }
            }

            // stop watching non-provided paths
            foreach (var oldPath in oldPaths)
            {
                _tableWatches[oldPath].Dispose();
                _tableWatches.Remove(oldPath);
                _tableFolderRemoved.OnNext(oldPath);
                _logger.Info("Stopped watching table folder {0}", oldPath);
            }
        }
Ejemplo n.º 45
0
        public async Task <TResult> ShowFlyoutView <TResult>(Func <ILifetimeScope, IView> viewFactory,
                                                             ViewRequest viewRequest = null, UiShowFlyoutOptions options = null)
        {
            if (!string.IsNullOrEmpty(viewRequest?.ViewId))
            {
                var viewOld = FlyoutsControl.Items
                              .Cast <Flyout>()
                              .Select(x => (IView)x.Content)
                              .FirstOrDefault(x => (x.ViewModel as ViewModelBase)?.ViewId == viewRequest.ViewId);

                if (viewOld != null)
                {
                    (viewOld.ViewModel as Ui.Wpf.Common.ViewModels.IActivatableViewModel)?.Activate(viewRequest);
                    return(default(TResult));
                }
            }

            var view = viewFactory(Container);

            if (options != null)
            {
                view.Configure(options);
            }

            options = options ?? new UiShowFlyoutOptions();

            var flyout = new Flyout
            {
                IsModal               = options.IsModal,
                Position              = options.Position,
                Theme                 = options.Theme,
                ExternalCloseButton   = options.ExternalCloseButton,
                IsPinned              = options.IsPinned,
                CloseButtonIsCancel   = options.CloseByEscape,
                CloseCommand          = options.CloseCommand,
                CloseCommandParameter = options.CloseCommandParameter,
                AnimateOpacity        = options.AnimateOpacity,
                AreAnimationsEnabled  = options.AreAnimationsEnabled,
                IsAutoCloseEnabled    = options.IsAutoCloseEnabled,
                AutoCloseInterval     = options.AutoCloseInterval,
                Width                 = options.Width ?? double.NaN,
                Height                = options.Height ?? double.NaN,
                Content               = view,
                IsOpen                = true
            };

            var vm = view.ViewModel as ViewModelBase;

            if (vm != null)
            {
                Observable
                .FromEventPattern <ViewModelCloseQueryArgs>(
                    x => vm.CloseQuery       += x,
                    x => vm.CloseQuery       -= x)
                .Subscribe(x => flyout.IsOpen = false)
                .DisposeWith(vm.Disposables);
            }

            var disposables = new CompositeDisposable();

            view.ViewModel
            .WhenAnyValue(x => x.Title)
            .Subscribe(x =>
            {
                flyout.Header          = x;
                flyout.TitleVisibility =
                    !string.IsNullOrEmpty(x)
                            ? Visibility.Visible
                            : Visibility.Collapsed;
            })
            .DisposeWith(disposables);
            view.ViewModel
            .WhenAnyValue(x => x.CanClose)
            .Subscribe(x => flyout.CloseButtonVisibility = x ? Visibility.Visible : Visibility.Collapsed)
            .DisposeWith(disposables);

            var closedObservable = Observable
                                   .FromEventPattern <RoutedEventHandler, RoutedEventArgs>(
                x => flyout.ClosingFinished += x,
                x => flyout.ClosingFinished -= x);

            FlyoutsControl.Items.Add(flyout);
            InitializeView(view, viewRequest);
            (view.ViewModel as Ui.Wpf.Common.ViewModels.IActivatableViewModel)?.Activate(viewRequest);

            await closedObservable.FirstAsync();

            disposables.Dispose();
            vm?.Closed(new ViewModelCloseQueryArgs());
            flyout.Content = null;
            FlyoutsControl.Items.Remove(flyout);

            if (vm is IResultableViewModel <TResult> model)
            {
                return(model.ViewResult);
            }

            return(default(TResult));
        }
Ejemplo n.º 46
0
        public Task <TResult> ShowChildWindowView <TResult>(Func <ILifetimeScope, IView> viewFactory,
                                                            ViewRequest viewRequest          = null,
                                                            UiShowChildWindowOptions options = null)
        {
            if (!string.IsNullOrEmpty(viewRequest?.ViewId))
            {
                var metroDialogContainer = Window.Template.FindName("PART_MetroActiveDialogContainer", Window) as Grid;
                metroDialogContainer = metroDialogContainer ??
                                       Window.Template.FindName("PART_MetroInactiveDialogsContainer", Window) as Grid;

                if (metroDialogContainer == null)
                {
                    throw new InvalidOperationException(
                              "The provided child window can not add, there is no container defined.");
                }

                var viewOld = metroDialogContainer.Children
                              .Cast <ChildWindowView>()
                              .Select(x => (IView)x.Content)
                              .FirstOrDefault(x => (x.ViewModel as ViewModelBase)?.ViewId == viewRequest.ViewId);

                if (viewOld != null)
                {
                    (viewOld.ViewModel as Ui.Wpf.Common.ViewModels.IActivatableViewModel)?.Activate(viewRequest);
                    return(Task.FromResult(default(TResult)));
                }
            }

            var view = viewFactory(Container);

            if (options != null)
            {
                view.Configure(options);
            }

            InitializeView(view, viewRequest);
            (view.ViewModel as Ui.Wpf.Common.ViewModels.IActivatableViewModel)?.Activate(viewRequest);

            options = options ?? new UiShowChildWindowOptions();

            var childWindow = new ChildWindowView(options)
            {
                Content = view
            };

            var vm = view.ViewModel as ViewModelBase;

            if (vm != null)
            {
                Observable
                .FromEventPattern <ViewModelCloseQueryArgs>(
                    x => vm.CloseQuery += x,
                    x => vm.CloseQuery -= x)
                .Subscribe(x =>
                {
                    if (vm is IResultableViewModel <TResult> model)
                    {
                        childWindow.Close(model.ViewResult);
                    }
                    else
                    {
                        childWindow.Close();
                    }
                })
                .DisposeWith(vm.Disposables);

                Observable
                .FromEventPattern <CancelEventArgs>(
                    x => childWindow.Closing += x,
                    x => childWindow.Closing -= x)
                .Subscribe(x =>
                {
                    var vcq = new ViewModelCloseQueryArgs {
                        IsCanceled = false
                    };
                    vm.Closing(vcq);

                    if (vcq.IsCanceled)
                    {
                        x.EventArgs.Cancel = true;
                    }
                })
                .DisposeWith(vm.Disposables);
            }

            var disposables = new CompositeDisposable();

            view.ViewModel
            .WhenAnyValue(x => x.Title)
            .Subscribe(x => childWindow.Title = x)
            .DisposeWith(disposables);
            view.ViewModel
            .WhenAnyValue(x => x.CanClose)
            .Subscribe(x => childWindow.ShowCloseButton = x)
            .DisposeWith(disposables);

            Observable
            .FromEventPattern <RoutedEventHandler, RoutedEventArgs>(
                x => childWindow.ClosingFinished += x,
                x => childWindow.ClosingFinished -= x)
            .Select(x => (ChildWindow)x.Sender)
            .Take(1)
            .Subscribe(x =>
            {
                disposables.Dispose();
                vm?.Closed(new ViewModelCloseQueryArgs());
                x.Content = null;
            });

            return(Window.ShowChildWindowAsync <TResult>(
                       childWindow,
                       options.OverlayFillBehavior
                       ));
        }
Ejemplo n.º 47
0
            protected override IDisposable SubscribeCore(IObserver <TSource> observer)
            {
                var outGate = new object();
                var q       = new Queue <IObservable <TSource> >();
                var m       = new SerialDisposable();
                var d       = new CompositeDisposable {
                    m
                };
                var activeCount = 0;
                var isAcquired  = false;

                void ensureActive()
                {
                    var isOwner = false;

                    lock (q)
                    {
                        if (q.Count > 0)
                        {
                            isOwner    = !isAcquired;
                            isAcquired = true;
                        }
                    }

                    if (isOwner)
                    {
                        m.Disposable = _scheduler.Schedule(self =>
                        {
                            var work = default(IObservable <TSource>);

                            lock (q)
                            {
                                if (q.Count > 0)
                                {
                                    work = q.Dequeue();
                                }
                                else
                                {
                                    isAcquired = false;
                                    return;
                                }
                            }

                            var m1 = new SingleAssignmentDisposable();
                            d.Add(m1);
                            m1.Disposable = work.Subscribe(
                                x =>
                            {
                                lock (outGate)
                                {
                                    observer.OnNext(x);
                                }

                                var result = default(IObservable <TSource>);
                                try
                                {
                                    result = _selector(x);
                                }
                                catch (Exception exception)
                                {
                                    lock (outGate)
                                    {
                                        observer.OnError(exception);
                                    }
                                }

                                lock (q)
                                {
                                    q.Enqueue(result);
                                    activeCount++;
                                }

                                ensureActive();
                            },
                                exception =>
                            {
                                lock (outGate)
                                {
                                    observer.OnError(exception);
                                }
                            },
                                () =>
                            {
                                d.Remove(m1);

                                var done = false;
                                lock (q)
                                {
                                    activeCount--;
                                    if (activeCount == 0)
                                    {
                                        done = true;
                                    }
                                }
                                if (done)
                                {
                                    lock (outGate)
                                    {
                                        observer.OnCompleted();
                                    }
                                }
                            });
                            self();
                        });
                    }
                }

                lock (q)
                {
                    q.Enqueue(_source);
                    activeCount++;
                }
                ensureActive();

                return(d);
            }
Ejemplo n.º 48
0
    private void BindCommands(CompositeDisposable disposables)
    {
        this.BindCommand(this.ViewModel !, vm => vm.Save, v => v.SaveButton)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Cancel, v => v.CancelButton)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Close, v => v.CloseButton)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToFranchise, v => v.GoToFranchiseButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToFranchise.CanExecute
        .BindTo(this, v => v.GoToFranchiseButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToFranchise, v => v.GoToFranchiseArrowButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToFranchise.CanExecute
        .BindTo(this, v => v.GoToFranchiseArrowButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToNext, v => v.GoToNextButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToNext.CanExecute
        .BindTo(this, v => v.GoToNextButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToPrevious, v => v.GoToPreviousButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToPrevious.CanExecute
        .BindTo(this, v => v.GoToPreviousButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.CreateFranchise, v => v.CreateFranchiseButton)
        .DisposeWith(disposables);

        this.ViewModel !.CreateFranchise.CanExecute
        .BindTo(this, v => v.CreateFranchiseButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Delete, v => v.DeleteButton)
        .DisposeWith(disposables);

        this.ViewModel !.Delete.CanExecute
        .BindTo(this, v => v.DeleteButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.AddTitle, v => v.AddTitleButton)
        .DisposeWith(disposables);

        this.ViewModel !.AddTitle.CanExecute
        .BindTo(this, v => v.AddTitleButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.AddOriginalTitle, v => v.AddOriginalTitleButton)
        .DisposeWith(disposables);

        this.ViewModel !.AddOriginalTitle.CanExecute
        .BindTo(this, v => v.AddOriginalTitleButton.IsVisible)
        .DisposeWith(disposables);

        Observable.CombineLatest(this.ViewModel !.Save.CanExecute, this.ViewModel !.Cancel.CanExecute)
        .AnyTrue()
        .BindTo(this, v => v.ActionPanel.IsVisible)
        .DisposeWith(disposables);

        this.ViewModel !.Save
        .Subscribe(_ => this.LoadPoster())
        .DisposeWith(disposables);
    }
Ejemplo n.º 49
0
 protected void HandleViewModelBound(CompositeDisposable d)
 {
     this.Bind(ViewModel, vm => vm.ApplicationTitle, v => v.Title).DisposeWith(d);
 }
Ejemplo n.º 50
0
 public static void Add(this CompositeDisposable c, Action action)
 {
     c.Add(Disposable.Create(action));
 }
Ejemplo n.º 51
0
        public static TDisposable DisposeWith <TDisposable>(this TDisposable observable, CompositeDisposable disposables)
            where TDisposable : class, IDisposable
        {
            if (observable != null)
            {
                disposables.Add(observable);
            }

            return(observable);
        }
Ejemplo n.º 52
0
        private void SubscribeToSectionInfoChanges(int sectionInfoId, IReadOnlyList <TSectionInfo> sectionInfo, IObservable <Unit> sectionChanging, IObservable <Unit> sectionChanged, CompositeDisposable disposables)
        {
            // holds a single disposable representing the monitoring of sectionInfo.
            // once disposed, any changes to sectionInfo will no longer trigger any of the logic below
            var sectionInfoDisposable = new SerialDisposable();

            disposables.Add(sectionInfoDisposable);

            disposables.Add(
                sectionChanging.Subscribe(_ =>
            {
                this.VerifyOnMainThread();

                this.Log().Debug("[#{0}] SectionInfo is changing.", sectionInfoId);
                sectionInfoDisposable.Disposable = Disposable.Empty;
            }));

            disposables.Add(
                sectionChanged.Subscribe(x =>
            {
                this.VerifyOnMainThread();

                this.Log().Debug("[#{0}] Calling ReloadData()", sectionInfoId);
                this.adapter.ReloadData();

                // holds all the disposables created to monitor stuff inside the section
                var sectionDisposables           = new CompositeDisposable();
                sectionInfoDisposable.Disposable = sectionDisposables;

                // holds a single disposable for any outstanding request to apply pending changes
                var applyPendingChangesDisposable = new SerialDisposable();
                sectionDisposables.Add(applyPendingChangesDisposable);

                var isReloading = adapter
                                  .IsReloadingData
                                  .DistinctUntilChanged()
                                  .Do(y => this.Log().Debug("[#{0}] IsReloadingData = {1}", sectionInfoId, y))
                                  .Publish();

                var anySectionChanged = Observable
                                        .Merge(
                    sectionInfo
                    .Select((y, index) => y.Collection.Changed.Select(z => new { Section = index, Change = z })))
                                        .Publish();

                // since reloads are applied asynchronously, it is possible for data to change whilst the reload is occuring
                // thus, we need to ensure any such changes result in another reload
                sectionDisposables.Add(
                    isReloading
                    .Where(y => y)
                    .Join(
                        anySectionChanged,
                        _ => isReloading,
                        _ => Observable <Unit> .Empty,
                        (_, __) => Unit.Default)
                    .Subscribe(_ =>
                {
                    this.VerifyOnMainThread();
                    this.Log().Debug("[#{0}] A section changed whilst a reload is in progress - forcing another reload.", sectionInfoId);

                    adapter.ReloadData();
                    this.pendingChanges.Clear();
                    isCollectingChanges = false;
                }));

                sectionDisposables.Add(
                    isReloading
                    .Where(y => !y)
                    .Join(
                        anySectionChanged,
                        _ => isReloading,
                        _ => Observable <Unit> .Empty,
                        (reloading, changeDetails) => new { Change = changeDetails.Change, Section = changeDetails.Section })
                    .Subscribe(y =>
                {
                    this.VerifyOnMainThread();

                    if (this.IsDebugEnabled)
                    {
                        this.Log().Debug(
                            "[#{0}] Change detected in section {1} : Action = {2}, OldStartingIndex = {3}, NewStartingIndex = {4}, OldItems.Count = {5}, NewItems.Count = {6}",
                            sectionInfoId,
                            y.Section,
                            y.Change.Action,
                            y.Change.OldStartingIndex,
                            y.Change.NewStartingIndex,
                            y.Change.OldItems == null ? "null" : y.Change.OldItems.Count.ToString(),
                            y.Change.NewItems == null ? "null" : y.Change.NewItems.Count.ToString());
                    }

                    if (!this.isCollectingChanges)
                    {
                        this.Log().Debug("[#{0}] A section changed whilst no reload is in progress - instigating collection of updates for later application.", sectionInfoId);
                        this.isCollectingChanges = true;

                        // immediately indicate to the view that there are changes underway, even though we don't apply them immediately
                        // this ensures that if application code itself calls BeginUpdates/EndUpdates on the view before the changes have been applied, those inconsistencies
                        // between what's in the data source versus what the view believes is in the data source won't trigger any errors because of the outstanding
                        // BeginUpdates call (calls to BeginUpdates/EndUpdates can be nested)
                        this.Log().Debug("[#{0}] BeginUpdates", sectionInfoId);
                        adapter.BeginUpdates();

                        applyPendingChangesDisposable.Disposable = RxApp.MainThreadScheduler.Schedule(
                            () =>
                        {
                            this.ApplyPendingChanges(sectionInfoId);
                            this.Log().Debug("[#{0}] EndUpdates", sectionInfoId);
                            adapter.EndUpdates();
                            isCollectingChanges = false;
                            applyPendingChangesDisposable.Disposable = null;
                        });
                    }

                    this.pendingChanges.Add(Tuple.Create(y.Section, new PendingChange(y.Change)));
                },
                               ex => this.Log().Error("[#{0}] Error while watching section collection: {1}", sectionInfoId, ex)));

                sectionDisposables.Add(isReloading.Connect());
                sectionDisposables.Add(anySectionChanged.Connect());
            }));
        }
Ejemplo n.º 53
0
        public PrimaryWindowCoreLayout(PrimaryWindowCoreLayoutViewModel viewModel)
        {
            DataContext = _viewModel = viewModel;
            this.InitializeComponent();

            _dispatcher = Dispatcher;

            ContentFrame.NavigationFailed += (_, e) =>
            {
                Debug.WriteLine("Page navigation failed!!");
                Debug.WriteLine(e.SourcePageType.AssemblyQualifiedName);
                Debug.WriteLine(e.Exception.ToString());

                _ = (App.Current as App).OutputErrorFile(e.Exception, e.SourcePageType?.AssemblyQualifiedName);
            };

            // Resolve Page Title
            ContentFrame.Navigated += (_, e) =>
            {
                OptionalPageTitle = string.Empty;
                Action <Page, NavigationEventArgs> UpdateOptionalTitleAction = (page, args) =>
                {
                    if (page.DataContext is ITitleUpdatablePage pageVM)
                    {
                        pageVM.GetTitleObservable()
                        .Subscribe(title =>
                        {
                            OptionalPageTitle = title;
                        })
                        .AddTo(_navigationDisposable);
                    }
                };

                var page = e.Content as Page;
                if (page.DataContext == null)
                {
                    page.ObserveDependencyProperty(DataContextProperty)
                    .Subscribe(_ =>
                    {
                        UpdateOptionalTitleAction(page, e);
                    })
                    .AddTo(_navigationDisposable);
                }
                else
                {
                    UpdateOptionalTitleAction(page, e);
                }

                var pageNameRaw = e.SourcePageType.FullName.Split('.').LastOrDefault();
                var pageName    = pageNameRaw.Split('_').FirstOrDefault();
                if (Enum.TryParse(pageName.Substring(0, pageName.Length - 4), out HohoemaPageType pageType))
                {
                    PageTitle = pageType.Translate();
                }
            };

            ContentFrame.Navigating += ContentFrame_Navigating;

            _viewModel.EventAggregator.GetEvent <PageNavigationEvent>()
            .Subscribe(args =>
            {
                _navigationDisposable?.Dispose();
                _navigationDisposable = new CompositeDisposable();

                _ = ContentFrameNavigation(args);
            });

            // Back Navigation Handling
            SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
            Window.Current.CoreWindow.KeyDown        += CoreWindow_KeyDown;
            Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;


            if (Services.Helpers.DeviceTypeHelper.IsDesktop)
            {
                Window.Current.SetTitleBar(DraggableContent as UIElement);
            }

            ContentFrame.Navigated      += TVModeContentFrame_Navigated;
            UINavigationManager.Pressed += UINavigationManager_Pressed;
            this.GettingFocus           += PrimaryWindowCoreLayout_GettingFocus;


            _viewModel.AppearanceSettings.ObserveProperty(x => x.Theme)
            .Subscribe(theme =>
            {
                if (theme == ElementTheme.Default)
                {
                    var appTheme = Helpers.SystemThemeHelper.GetSystemTheme();
                    if (appTheme == ApplicationTheme.Dark)
                    {
                        theme = ElementTheme.Dark;
                    }
                    else
                    {
                        theme = ElementTheme.Light;
                    }
                }

                this.RequestedTheme = theme;
            });
        }
Ejemplo n.º 54
0
 public void Stop()
 {
     syncingDisposeBag?.Dispose();
     syncingDisposeBag = new CompositeDisposable();
 }
Ejemplo n.º 55
0
        public NewCachingDialog(IServiceProvider serviceProvider, CachingItem existing, CachingFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            Text     = existing == null ? "Add Cache Rule" : "Edit Cache Rule";
            _feature = feature;
            Item     = existing ?? new CachingItem(null);
            if (existing == null)
            {
                return;
            }

            txtExtension.Text  = Item.Extension;
            cbUser.Checked     = Item.Policy != 0L;
            rbUserFile.Checked = Item.Policy == 1L;
            rbUserTime.Checked = Item.Policy == 2L;
            rbUserNo.Checked   = Item.Policy == 3L;

            cbKernel.Checked     = Item.KernelCachePolicy != 0L;
            rbKernelFile.Checked = Item.KernelCachePolicy == 1L;
            rbKernelTime.Checked = Item.KernelCachePolicy == 2L;
            rbKernelNo.Checked   = Item.KernelCachePolicy == 3L;

            txtKernelTime.Text = txtUserTime.Text = Item.Duration.ToString();

            var container = new CompositeDisposable();

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

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                Item.Extension = txtExtension.Text;
                Item.Duration  = TimeSpan.Parse(txtKernelTime.Text);
                if (!cbUser.Checked)
                {
                    Item.Policy = 0L;
                }
                else if (rbUserFile.Checked)
                {
                    Item.Policy = 1L;
                }
                else if (rbUserTime.Checked)
                {
                    Item.Policy = 2L;
                }
                else if (rbUserNo.Checked)
                {
                    Item.Policy = 3L;
                }

                if (!cbKernel.Checked)
                {
                    Item.KernelCachePolicy = 0L;
                }
                else if (rbKernelFile.Checked)
                {
                    Item.KernelCachePolicy = 1L;
                }
                else if (rbKernelTime.Checked)
                {
                    Item.KernelCachePolicy = 2L;
                }
                else if (rbKernelNo.Checked)
                {
                    Item.KernelCachePolicy = 3L;
                }

                if (_feature.Items.Any(item => item.Match(Item)))
                {
                    ShowMessage(
                        "This rule already exists.",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnAdvanced, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var dialog = new CachingAdvancedDialog(ServiceProvider, Item);
                dialog.ShowDialog();
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtExtension, "TextChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtExtension.Text);
            }));
        }
Ejemplo n.º 56
0
        public CoinViewModel(Wallet wallet, CoinListViewModel owner, SmartCoin model)
        {
            Global = Locator.Current.GetService <Global>();

            Model  = model;
            Wallet = wallet;
            Owner  = owner;

            RefreshSmartCoinStatus();

            Disposables = new CompositeDisposable();

            _coinJoinInProgress = Model
                                  .WhenAnyValue(x => x.CoinJoinInProgress)
                                  .ToProperty(this, x => x.CoinJoinInProgress, scheduler: RxApp.MainThreadScheduler)
                                  .DisposeWith(Disposables);

            _confirmed = Model
                         .WhenAnyValue(x => x.Confirmed)
                         .ToProperty(this, x => x.Confirmed, scheduler: RxApp.MainThreadScheduler)
                         .DisposeWith(Disposables);

            _anonymitySet = Model
                            .WhenAnyValue(x => x.HdPubKey.AnonymitySet)
                            .ToProperty(this, x => x.AnonymitySet, scheduler: RxApp.MainThreadScheduler)
                            .DisposeWith(Disposables);

            _cluster = Model
                       .WhenAnyValue(x => x.HdPubKey.Cluster, x => x.HdPubKey.Cluster.Labels)
                       .Select(x => x.Item2.ToString())
                       .ToProperty(this, x => x.Cluster, scheduler: RxApp.MainThreadScheduler)
                       .DisposeWith(Disposables);

            this.WhenAnyValue(x => x.Status)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => this.RaisePropertyChanged(nameof(ToolTip)));

            Observable
            .Merge(Model.WhenAnyValue(x => x.IsBanned, x => x.SpentAccordingToBackend, x => x.Confirmed, x => x.CoinJoinInProgress).Select(_ => Unit.Default))
            .Merge(Observable.FromEventPattern(Wallet.ChaumianClient, nameof(Wallet.ChaumianClient.StateUpdated)).Select(_ => Unit.Default))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => RefreshSmartCoinStatus())
            .DisposeWith(Disposables);

            Global.BitcoinStore.SmartHeaderChain
            .WhenAnyValue(x => x.TipHeight).Select(_ => Unit.Default)
            .Merge(Model.WhenAnyValue(x => x.Height).Select(_ => Unit.Default))
            .Throttle(TimeSpan.FromSeconds(0.1))                     // DO NOT TAKE THIS THROTTLE OUT, OTHERWISE SYNCING WITH COINS IN THE WALLET WILL STACKOVERFLOW!
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => this.RaisePropertyChanged(nameof(Confirmations)))
            .DisposeWith(Disposables);

            Global.UiConfig
            .WhenAnyValue(x => x.PrivacyMode)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                this.RaisePropertyChanged(nameof(AmountBtc));
                this.RaisePropertyChanged(nameof(Cluster));
            }).DisposeWith(Disposables);

            DequeueCoin = ReactiveCommand.Create(() => Owner.PressDequeue(Model), this.WhenAnyValue(x => x.CoinJoinInProgress));

            OpenCoinInfo = ReactiveCommand.Create(() =>
            {
                var shell = IoC.Get <IShell>();

                var coinInfo = shell.Documents?.OfType <CoinInfoTabViewModel>()?.FirstOrDefault(x => x.Coin?.Model == Model);

                if (coinInfo is null)
                {
                    coinInfo = new CoinInfoTabViewModel(this);
                    shell.AddDocument(coinInfo);
                }

                shell.Select(coinInfo);
            });

            CopyCluster = ReactiveCommand.CreateFromTask(async() => await Application.Current.Clipboard.SetTextAsync(Cluster));

            Observable
            .Merge(DequeueCoin.ThrownExceptions)                     // Don't notify about it. Dequeue failure (and success) is notified by other mechanism.
            .Merge(OpenCoinInfo.ThrownExceptions)
            .Merge(CopyCluster.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
Ejemplo n.º 57
0
        public async Task <IActionResult> ConnectWebSocket(
            string cryptoCode,
            bool includeTransaction        = true,
            CancellationToken cancellation = default)
        {
            if (!HttpContext.WebSockets.IsWebSocketRequest)
            {
                return(NotFound());
            }

            GetNetwork(cryptoCode, false);             // Internally check if cryptoCode is correct

            string listenAllDerivationSchemes = null;
            string listenAllTrackedSource     = null;
            var    listenedBlocks             = new ConcurrentDictionary <string, string>();
            var    listenedDerivations        = new ConcurrentDictionary <(Network, DerivationStrategyBase), DerivationStrategyBase>();
            var    listenedTrackedSource      = new ConcurrentDictionary <(Network, TrackedSource), TrackedSource>();

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

            subscriptions.Add(_EventAggregator.Subscribe <Models.NewBlockEvent>(async o =>
            {
                if (listenedBlocks.ContainsKey(o.CryptoCode))
                {
                    await server.Send(o);
                }
            }));
            subscriptions.Add(_EventAggregator.Subscribe <Models.NewTransactionEvent>(async o =>
            {
                var network = Waiters.GetWaiter(o.CryptoCode);
                if (network == null)
                {
                    return;
                }

                bool forward         = false;
                var derivationScheme = (o.TrackedSource as DerivationSchemeTrackedSource)?.DerivationStrategy;
                if (derivationScheme != null)
                {
                    forward |= listenAllDerivationSchemes == "*" ||
                               listenAllDerivationSchemes == o.CryptoCode ||
                               listenedDerivations.ContainsKey((network.Network.NBitcoinNetwork, derivationScheme));
                }

                forward |= listenAllTrackedSource == "*" || listenAllTrackedSource == o.CryptoCode ||
                           listenedTrackedSource.ContainsKey((network.Network.NBitcoinNetwork, o.TrackedSource));

                if (forward)
                {
                    var derivation = (o.TrackedSource as DerivationSchemeTrackedSource)?.DerivationStrategy;
                    await server.Send(o);
                }
            }));
            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:
                        var network = Waiters.GetWaiter(r.CryptoCode)?.Network;
                        if (r.DerivationSchemes != null)
                        {
                            r.CryptoCode = r.CryptoCode ?? cryptoCode;
                            if (network != null)
                            {
                                foreach (var derivation in r.DerivationSchemes)
                                {
                                    var parsed = new DerivationStrategyFactory(network.NBitcoinNetwork).Parse(derivation);
                                    listenedDerivations.TryAdd((network.NBitcoinNetwork, parsed), parsed);
                                }
                            }
                        }
                        else if (
                            // Back compat: If no derivation scheme precised and ListenAllDerivationSchemes not set, we listen all
                            (r.TrackedSources == null && r.ListenAllDerivationSchemes == null) ||
                            (r.ListenAllDerivationSchemes != null && r.ListenAllDerivationSchemes.Value))
                        {
                            listenAllDerivationSchemes = r.CryptoCode;
                        }

                        if (r.ListenAllTrackedSource != null && r.ListenAllTrackedSource.Value)
                        {
                            listenAllTrackedSource = r.CryptoCode;
                        }
                        else if (r.TrackedSources != null)
                        {
                            r.CryptoCode = r.CryptoCode ?? cryptoCode;
                            if (network != null)
                            {
                                foreach (var trackedSource in r.TrackedSources)
                                {
                                    if (TrackedSource.TryParse(trackedSource, out var parsed, network.NBitcoinNetwork))
                                    {
                                        listenedTrackedSource.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());
        }
Ejemplo n.º 58
0
        protected override void HandleActivation(CompositeDisposable disposables)
        {
            IsLoading = true;

            Task.Run(() =>
            {
                var suppliers = new List <Supplier>();
                if (saftValidator?.SaftFileV4?.MasterFiles?.Supplier != null)
                {
                    var saft_suppliers = saftValidator.SaftFileV4.MasterFiles.Supplier;

                    foreach (var c in saft_suppliers)
                    {
                        suppliers.Add(new Supplier
                        {
                            AccountID      = c.AccountID,
                            BillingAddress = new SupplierAddressStructure
                            {
                                AddressDetail  = c.BillingAddress?.AddressDetail,
                                BuildingNumber = c.BillingAddress?.BuildingNumber,
                                City           = c.BillingAddress?.City,
                                Country        = c.BillingAddress?.Country,
                                PostalCode     = c.BillingAddress?.PostalCode,
                                Region         = c.BillingAddress?.Region,
                                StreetName     = c.BillingAddress?.StreetName
                            },
                            CompanyName          = c.CompanyName,
                            Contact              = c.Contact,
                            SupplierID           = c.SupplierID,
                            SupplierTaxID        = c.SupplierTaxID,
                            Email                = c.Email,
                            Fax                  = c.Fax,
                            SelfBillingIndicator = c.SelfBillingIndicator,
                            Telephone            = c.Telephone,
                            Website              = c.Website,
                            ShipFromAddress      = c.ShipFromAddress?.Select(s => new SupplierAddressStructure
                            {
                                AddressDetail  = s.AddressDetail,
                                BuildingNumber = s.BuildingNumber,
                                City           = s.City,
                                Country        = s.Country,
                                PostalCode     = s.PostalCode,
                                Region         = s.Region,
                                StreetName     = s.StreetName
                            }).ToArray(),
                            TooltipAccountID      = c.TooltipAccountID,
                            TooltipBillingAddress = c.TooltipBillingAddress,
                            TooltipBillingAddressAddressDetail  = c.TooltipBillingAddressAddressDetail,
                            TooltipBillingAddressBuildingNumber = c.TooltipBillingAddressBuildingNumber,
                            TooltipBillingAddressCity           = c.TooltipBillingAddressCity,
                            TooltipBillingAddressCountry        = c.TooltipBillingAddressCountry,
                            TooltipBillingAddressPostalCode     = c.TooltipBillingAddressPostalCode,
                            TooltipBillingAddressRegion         = c.TooltipBillingAddressRegion,
                            TooltipBillingAddressStreetName     = c.TooltipBillingAddressStreetName,
                            TooltipCompanyName                   = c.TooltipCompanyName,
                            TooltipContact                       = c.TooltipContact,
                            TooltipEmail                         = c.TooltipEmail,
                            TooltipFax                           = c.TooltipFax,
                            TooltipSelfBillingIndicator          = c.TooltipSelfBillingIndicator,
                            TooltipShipFromAddress               = c.TooltipShipFromAddress,
                            TooltipShipFromAddressAddressDetail  = c.TooltipShipFromAddressAddressDetail,
                            TooltipShipFromAddressBuildingNumber = c.TooltipShipFromAddressBuildingNumber,
                            TooltipShipFromAddressCity           = c.TooltipShipFromAddressCity,
                            TooltipShipFromAddressCountry        = c.TooltipShipFromAddressCountry,
                            TooltipShipFromAddressPostalCode     = c.TooltipShipFromAddressPostalCode,
                            TooltipShipFromAddressRegion         = c.TooltipShipFromAddressRegion,
                            TooltipShipFromAddressStreetName     = c.TooltipShipFromAddressStreetName,
                            TooltipSupplierID                    = c.TooltipSupplierID,
                            TooltipSupplierTaxID                 = c.TooltipSupplierTaxID,
                            TooltipTelephone                     = c.TooltipTelephone,
                            TooltipWebsite                       = c.TooltipWebsite
                        });
                    }
                }
                else if (saftValidator?.SaftFileV3?.MasterFiles?.Supplier != null)
                {
                    var saft_suppliers = saftValidator.SaftFileV4.MasterFiles.Supplier;

                    foreach (var c in saft_suppliers)
                    {
                        suppliers.Add(new Supplier
                        {
                            AccountID      = c.AccountID,
                            BillingAddress = new SupplierAddressStructure
                            {
                                AddressDetail  = c.BillingAddress?.AddressDetail,
                                BuildingNumber = c.BillingAddress?.BuildingNumber,
                                City           = c.BillingAddress?.City,
                                Country        = c.BillingAddress?.Country,
                                PostalCode     = c.BillingAddress?.PostalCode,
                                Region         = c.BillingAddress?.Region,
                                StreetName     = c.BillingAddress?.StreetName
                            },
                            CompanyName          = c.CompanyName,
                            Contact              = c.Contact,
                            SupplierID           = c.SupplierID,
                            SupplierTaxID        = c.SupplierTaxID,
                            Email                = c.Email,
                            Fax                  = c.Fax,
                            SelfBillingIndicator = c.SelfBillingIndicator,
                            Telephone            = c.Telephone,
                            Website              = c.Website,
                            ShipFromAddress      = c.ShipFromAddress?.Select(s => new SupplierAddressStructure
                            {
                                AddressDetail  = s.AddressDetail,
                                BuildingNumber = s.BuildingNumber,
                                City           = s.City,
                                Country        = s.Country,
                                PostalCode     = s.PostalCode,
                                Region         = s.Region,
                                StreetName     = s.StreetName
                            }).ToArray(),
                            TooltipAccountID      = c.TooltipAccountID,
                            TooltipBillingAddress = c.TooltipBillingAddress,
                            TooltipBillingAddressAddressDetail  = c.TooltipBillingAddressAddressDetail,
                            TooltipBillingAddressBuildingNumber = c.TooltipBillingAddressBuildingNumber,
                            TooltipBillingAddressCity           = c.TooltipBillingAddressCity,
                            TooltipBillingAddressCountry        = c.TooltipBillingAddressCountry,
                            TooltipBillingAddressPostalCode     = c.TooltipBillingAddressPostalCode,
                            TooltipBillingAddressRegion         = c.TooltipBillingAddressRegion,
                            TooltipBillingAddressStreetName     = c.TooltipBillingAddressStreetName,
                            TooltipCompanyName                   = c.TooltipCompanyName,
                            TooltipContact                       = c.TooltipContact,
                            TooltipEmail                         = c.TooltipEmail,
                            TooltipFax                           = c.TooltipFax,
                            TooltipSelfBillingIndicator          = c.TooltipSelfBillingIndicator,
                            TooltipShipFromAddress               = c.TooltipShipFromAddress,
                            TooltipShipFromAddressAddressDetail  = c.TooltipShipFromAddressAddressDetail,
                            TooltipShipFromAddressBuildingNumber = c.TooltipShipFromAddressBuildingNumber,
                            TooltipShipFromAddressCity           = c.TooltipShipFromAddressCity,
                            TooltipShipFromAddressCountry        = c.TooltipShipFromAddressCountry,
                            TooltipShipFromAddressPostalCode     = c.TooltipShipFromAddressPostalCode,
                            TooltipShipFromAddressRegion         = c.TooltipShipFromAddressRegion,
                            TooltipShipFromAddressStreetName     = c.TooltipShipFromAddressStreetName,
                            TooltipSupplierID                    = c.TooltipSupplierID,
                            TooltipSupplierTaxID                 = c.TooltipSupplierTaxID,
                            TooltipTelephone                     = c.TooltipTelephone,
                            TooltipWebsite                       = c.TooltipWebsite
                        });
                    }
                }

                return(suppliers);
            }).ContinueWith(async c =>
            {
                var suppliers = await c;

                CollectionView = new DataGridCollectionView(suppliers)
                {
                    Filter = o =>
                    {
                        if (string.IsNullOrWhiteSpace(Filter))
                        {
                            return(true);
                        }

                        if (o is Supplier supplier)
                        {
                            if (supplier.AccountID != null && supplier.AccountID.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.CompanyName != null && supplier.CompanyName.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.Contact != null && supplier.Contact.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.SupplierID != null && supplier.SupplierID.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.SupplierTaxID != null && supplier.SupplierTaxID.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.Email != null && supplier.Email.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.Fax != null && supplier.Fax.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.Telephone != null && supplier.Telephone.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                            if (supplier.Website != null && supplier.Website.Contains(Filter, StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                        }

                        return(false);
                    }
                };

                CollectionView.GroupDescriptions.Add(new DataGridPathGroupDescription("AccountID"));

                this.WhenAnyValue(x => x.Filter)
                .Throttle(TimeSpan.FromSeconds(1))
                .ObserveOn(RxApp.MainThreadScheduler)
                .InvokeCommand(SearchCommand)
                .DisposeWith(disposables);

                IsLoading = false;
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Initialize instance
 /// </summary>
 public virtual void Initialize()
 {
     Disposer = new CompositeDisposable();
 }
Ejemplo n.º 60
0
 protected virtual void HandleActivation(CompositeDisposable disposables)
 {
 }