Example #1
0
        public static IStage <T0, T1> To <T0, T, T1>(this IStage <T0, T> stage1, IStage <T, T1> stage2)
        {
            Disposables stages = new Disposables();

            stages.Add(stage1);
            stages.Add(stage2);
            stages.Add(stage1.Connect(stage2));
            return(new CompositeStage <T0, T1>(stage1, stage2, stages));
        }
Example #2
0
        public void DisposeInReverseOrder()
        {
            var test = "";

            using (var disposables = new Disposables())
            {
                disposables.Add(Scope.Create(() => test += "a"));
                disposables.Add(Scope.Create(() => test += "b"));
                disposables.Add(Scope.Create(() => test += "c"));
            }
            Assert.AreEqual("cba", test);
        }
Example #3
0
        public void IgnoreNull()
        {
            var test = "";

            using (var disposables = new Disposables())
            {
                disposables.Add(Scope.Create(() => test += "a"));
                disposables.Add(null);
                disposables.Add(Scope.Create(() => test += "c"));
            }
            Assert.AreEqual("ca", test);
        }
Example #4
0
        public Computed(IObservable <T> valueStream)
        {
            valueChanged = new Subject <Unit>();
            Stream       = valueStream;

            disposables.Add(Stream.Subscribe(value =>
            {
                Value = value;
                valueChanged.OnNext(Unit.Default);
            }));

            disposables.Add(new Disposable(() => valueChanged.OnCompleted()));
        }
 public override void Init(IMessageBus messageBus)
 {
     Disposables.Add(
         messageBus.Listen <AddedEntityMessage <PlanReceiptOrder> >().Subscribe(this.HandlingAddedMessage));
     Disposables.Add(
         messageBus.Listen <UpdatedEntityMessage <PlanReceiptOrder> >().Subscribe(this.HandlingUpdatedMessage));
 }
Example #6
0
        public void MapLights(DDJSB2.PioneerDDJSB2 ddjsb2)
        {
            var channels = new Voicemeeter.Levels.Channel[] {
                new Voicemeeter.Levels.Channel { // Check if Spotify is outputting audio
                    LevelType     = Voicemeeter.LevelType.PreFaderInput,
                    ChannelNumber = 4            // Strip #3 - Left Audio
                },
                new Voicemeeter.Levels.Channel { // Spotify Audio Level
                    LevelType     = Voicemeeter.LevelType.PostFaderInput,
                    ChannelNumber = 4            // Strip #3 - Left Audio
                },
                new Voicemeeter.Levels.Channel { // VoiceAttack Audio Level
                    LevelType     = Voicemeeter.LevelType.PostFaderInput,
                    ChannelNumber = 2            // Strip #2 - Left Audio
                }
            };

            // Subscribe to the levels from Voicemeeter
            var levels = new Voicemeeter.Levels(channels, 20);  // Update every 20 miliseconds

            Disposables.Add(levels.Subscribe(x => LevelsUpdate(ddjsb2, x)));

            // Watch for changes
            var parameters = new Voicemeeter.Parameters();

            Disposables.Add(parameters.Subscribe(x => ParametersUpdate(ddjsb2, x)));

            Disposables.Add(GameService.GameStatusObservable.Subscribe(x => Process(ddjsb2, x)));

            // Init
            //ddjsb2.LedControl(Leds.Deck.Deck1, Leds.PlayLed, false, GameService.GameStatusObservable.EliteAPI.Status.IsRunning);
        }
Example #7
0
        public FilterViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog, IFilterService service)
            : base(log, scheduler, standardDialog)
        {
            _service = service;

            Disposables.Add(service);
        }
Example #8
0
 internal Gate(ILoggerFactory loggerFactory, GateConfig config)
 {
     _loggerFactory = loggerFactory;
     _logger        = loggerFactory.CreateLogger <Gate>();
     _config        = config;
     Disposables.Add(config);
 }
Example #9
0
        public Property(T?initialValue, Func <T?, T?, T?>?coerceValue = null, IEqualityComparer <T>?comparer = null)
        {
            this.Value = initialValue;

            this.coerceValue = coerceValue;

            stream = new BehaviorSubject <T>(CoerceValue(initialValue) !);

            ValueChanged = stream
                           .DistinctUntilChanged(comparer.OrDefault())
                           .Select(_ => Unit.Default);

            disposables.Add(stream.Subscribe(value => Value = value));

            disposables.Add(new Disposable(() => stream.OnCompleted()));
        }
 protected void Manage(IDisposable disposable)
 {
     if (disposable != null)
     {
         Disposables.Add(disposable);
     }
 }
        public void Remove()
        {
            TestDisposable[] o = new TestDisposable[4];
            for (int i = 0; i < o.Length; i++)
            {
                o[i] = new TestDisposable();
            }

            using (var disposer = new Disposables())
            {
                foreach (IDisposable d in o)
                {
                    disposer.Add(d);
                }
                disposer.RemoveAt(2);
            }
            for (int i = 0; i < o.Length; i++)
            {
                if (i == 2)
                {
                    Assert.IsFalse(o[i].IsDisposed);
                }
                else
                {
                    Assert.IsTrue(o[i].IsDisposed);
                }
            }
        }
Example #12
0
        public WindowActivationViewModel(CoreDispatcher dispatcher) : base(dispatcher)
        {
            CoreWindow.GetForCurrentThread().Activated += CoreWindowActivated;
            XamlWindow.Current.Activated          += WindowActivated;
            XamlWindow.Current.VisibilityChanged  += WindowVisibilityChanged;
            Application.Current.EnteredBackground += AppEnteredBackground;
            Application.Current.LeavingBackground += AppLeavingBackground;
            CoreApplication.EnteredBackground     += CoreApplicationEnteredBackground;
            CoreApplication.LeavingBackground     += CoreApplicationLeavingBackground;
            Application.Current.Suspending        += ApplicationSuspending;
            Application.Current.Resuming          += ApplicationResuming;
            CoreApplication.Suspending            += CoreApplicationResuming;
            CoreApplication.Resuming += CoreApplicationResuming;

            Disposables.Add(() =>
            {
                CoreWindow.GetForCurrentThread().Activated -= CoreWindowActivated;
                XamlWindow.Current.Activated          -= WindowActivated;
                XamlWindow.Current.VisibilityChanged  -= WindowVisibilityChanged;
                Application.Current.EnteredBackground -= AppEnteredBackground;
                Application.Current.LeavingBackground -= AppLeavingBackground;
                CoreApplication.EnteredBackground     -= CoreApplicationEnteredBackground;
                CoreApplication.LeavingBackground     -= CoreApplicationLeavingBackground;
                Application.Current.Suspending        -= ApplicationSuspending;
                Application.Current.Resuming          -= ApplicationResuming;
                CoreApplication.Suspending            -= CoreApplicationResuming;
                CoreApplication.Resuming -= CoreApplicationResuming;
            });
        }
Example #13
0
 private bool Storage_Find(ExecutionEngine engine)
 {
     if (engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface)
     {
         StorageContext context = _interface.GetInterface <StorageContext>();
         if (!CheckStorageContext(context))
         {
             return(false);
         }
         byte[] prefix = engine.CurrentContext.EvaluationStack.Pop().GetByteArray();
         byte[] prefix_key;
         using (MemoryStream ms = new MemoryStream())
         {
             int index  = 0;
             int remain = prefix.Length;
             while (remain >= 16)
             {
                 ms.Write(prefix, index, 16);
                 ms.WriteByte(0);
                 index  += 16;
                 remain -= 16;
             }
             if (remain > 0)
             {
                 ms.Write(prefix, index, remain);
             }
             prefix_key = context.ScriptHash.ToArray().Concat(ms.ToArray()).ToArray();
         }
         StorageIterator iterator = new StorageIterator(Snapshot.Storages.Find(prefix_key).Where(p => p.Key.Key.Take(prefix.Length).SequenceEqual(prefix)).GetEnumerator());
         engine.CurrentContext.EvaluationStack.Push(StackItem.FromInterface(iterator));
         Disposables.Add(iterator);
         return(true);
     }
     return(false);
 }
Example #14
0
        public DynamicColumnEditViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog, IDynamicColumnEditService service)
            : base(log, scheduler, standardDialog)
        {
            _service = service;

            Disposables.Add(service);
        }
Example #15
0
 protected internal StackItem Convert(object value)
 {
     if (value is IDisposable disposable)
     {
         Disposables.Add(disposable);
     }
     return(value switch
     {
         null => StackItem.Null,
         bool b => b,
         sbyte i => i,
         byte i => (BigInteger)i,
         short i => i,
         ushort i => (BigInteger)i,
         int i => i,
         uint i => i,
         long i => i,
         ulong i => i,
         Enum e => Convert(System.Convert.ChangeType(e, e.GetTypeCode())),
         byte[] data => data,
         string s => s,
         BigInteger i => i,
         JObject o => o.ToByteArray(false),
         IInteroperable interoperable => interoperable.ToStackItem(ReferenceCounter),
         ISerializable i => i.ToArray(),
         StackItem item => item,
         (object a, object b) => new Struct(ReferenceCounter)
         {
             Convert(a), Convert(b)
         },
         Array array => new VMArray(ReferenceCounter, array.OfType <object>().Select(p => Convert(p))),
         _ => StackItem.FromInterface(value)
     });
Example #16
0
        /// <summary>
        /// Customize the store configuration for one off tests.
        /// The return value is the database schema
        /// </summary>
        /// <param name="configure"></param>
        /// <returns></returns>
        protected string StoreOptions(Action <StoreOptions> configure)
        {
            overrideSession = true;

            if (session != null)
            {
                session.Dispose();
                Disposables.Remove(session);
                session = null;
            }


            var options = new StoreOptions();

            options.Connection(ConnectionSource.ConnectionString);

            // Can be overridden
            options.AutoCreateSchemaObjects = AutoCreate.All;
            options.NameDataLength          = 100;
            options.DatabaseSchemaName      = "special";

            configure(options);

            store = new DocumentStore(options);
            Disposables.Add(store);

            store.Advanced.Clean.CompletelyRemoveAll();

            return(options.DatabaseSchemaName);
        }
 public ControlManager()
     : base(UPDATE_FREQUENCY)
 {
     Disposables.Add(new MessageListener((s) => BroadcastData(null, s.Select(x => new MessagePackage(x)))));
     Disposables.Add(new CommandListener((s) => BroadcastData(null, s.Select(x => new CommandPackage(x)))));
     Disposables.Add(new SimulationListener((s) => BroadcastData(null, s.Select(x => new SimulationPackage(x)))));
 }
        public DynamicColumnManagementViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog, IDynamicColumnManagementService service,
                                                BindableCollection <DynamicColumn> columnsCollection,
                                                BindableCollection <IToolBarItem> toolBarItemsCollection,
                                                Func <DynamicColumnEditViewModel> editViewModelFactory,
                                                IToolBarService toolBarService)
            : base(log, scheduler, standardDialog)
        {
            _service = service;
            _editViewModelFactory = editViewModelFactory;

            Disposables.Add(service);

            Columns = columnsCollection;

            ToolBarItems = toolBarItemsCollection;

            var saveToolBarItem = toolBarService.CreateToolBarButtonItem();

            saveToolBarItem.DisplayName = "Save";
            _saveCommand = new DelegateCommand(() =>
            {
                ClosingStrategy.Close();
            });
            saveToolBarItem.Command = _saveCommand;
            ToolBarItems.Add(saveToolBarItem);

            var cancelToolBarItem = toolBarService.CreateToolBarButtonItem();

            cancelToolBarItem.DisplayName = "Cancel";
            cancelToolBarItem.Command     = ClosingStrategy.CloseCommand;
            ToolBarItems.Add(cancelToolBarItem);
        }
Example #19
0
        public void NoAddAfterDispose()
        {
            var disposables = new Disposables();

            disposables.Dispose();
            Assert.Throws <ObjectDisposedException>(() => disposables.Add(Scope.Create(() => { })));
        }
Example #20
0
        public void MultiConsumer()
        {
            using (var queues = new Disposables())
            {
                IChannel <string> channel = new QueueChannel <string>();

                //Init executing Fibers
                for (int i = 0; i < 5; i++)
                {
                    char OnReceive(string message)
                    {
                        return(message[0]);
                    }

                    IFiber threadFiber = new ThreadFiber(new Executor(), new TimerScheduler(), new SleepingQueue(), i.ToString());
                    threadFiber.Start();
                    queues.Add(threadFiber);
                    channel.Subscribe(threadFiber, x => OnReceive(x));
                }
                Stopwatch sw = new Stopwatch();
                sw.Start();

                //Push messages
                for (int i = 0; i < 1000000; i++)
                {
                    string msg = "[" + i + "] Push";
                    channel.Publish(msg);
                }
                sw.Stop();
                Console.WriteLine("End : " + sw.ElapsedMilliseconds);
            }
        }
Example #21
0
        public void DragNDrop_ExtensionApi_IsExecuted()
        {
            Navigate("/E2ETestDragnDrop");
            try
            {
                // Given
                var tempFile = Path.GetTempFileName();
                File.WriteAllText(tempFile, "Hello world");
                Disposables.Add(() => File.Delete(tempFile));

                // When
                Browser.FindElement(By.Id("testDropEvents")).Click();
                var dropZone = Browser.FindElement(By.Id("drop-zone"));
                DropFile(Browser, new FileInfo(tempFile), dropZone, 0, 0);

                // Then
                var value = Browser.FindElement(By.Id("testDropEventsValues")).GetAttribute("value");
                var nl    = Environment.NewLine;
                Assert.Equal(@$ "{nl}OnDragOverMethod{nl}OnDragOverScript{nl}OnDropMethod{nl}OnDropScript", value);
            }
            finally
            {
                Disposables?.ForEach(d => d?.Invoke());
            }
        }
Example #22
0
        public void DragNDropHotPath_ReadsFile()
        {
            Navigate("/E2ETestDragnDrop");
            try
            {
                var dropZone       = Browser.FindElement(By.Id("drop-zone"));
                var tempFile       = Path.GetTempFileName();
                var expectedOutput = $@"IFileInfo.Name: {Path.GetFileName(tempFile)}
Read 11 bytes. 11 / 11
--DONE";
                File.WriteAllText(tempFile, "Hello world");
                Disposables.Add(() => File.Delete(tempFile));
                DropFile(Browser, new FileInfo(tempFile), dropZone, 0, 0);
                var gobutton = Browser.FindElement(By.Id("read-file"));
                gobutton.Click();
                try
                {
                    new WebDriverWait(Browser, TimeSpan.FromSeconds(5)).Until(
                        driver => driver.FindElement(By.Id("debug-output")).Text.Contains("--DONE"));
                }
                catch (OpenQA.Selenium.WebDriverTimeoutException)
                {
                    Assert.Equal(expectedOutput, Browser.FindElement(By.Id("debug-output")).Text);
                }
                var finalOutput = Browser.FindElement(By.Id("debug-output")).Text;
                Assert.Equal(expectedOutput, Browser.FindElement(By.Id("debug-output")).Text);
            }
            finally
            {
                Disposables?.ForEach(d => d?.Invoke());
            }
        }
Example #23
0
        private void Subskrybuj()
        {
            var potok = Trener.Pokemon.Atakuje.Merge(Rywal.Pokemon.Atakuje).Subscribe(data => ZaatakowaƂ(data));

            Disposables.Add(potok);
            //Disposables.Add(potok2);
        }
Example #24
0
        public void OnlyOneConsumer()
        {
            using (var queues = new Disposables())
            {
                IChannel <int>      channel = new QueueChannel <int>();
                ConcurrentBag <int> results = new ConcurrentBag <int>();

                void OnReceive(int message)
                {
                    results.Add(message);
                }

                //Init executing Fibers
                for (int i = 0; i < 10; i++)
                {
                    IFiber threadFiber = ThreadFiber.StartNew();
                    queues.Add(threadFiber);
                    channel.Subscribe(threadFiber, OnReceive);
                }
                //Push messages
                for (int i = 0; i < 1000000; i++)
                {
                    channel.Publish(i);
                }
                Thread.Sleep(100);
                Assert.AreEqual(1000000, results.Count);
                var r1 = results.OrderBy(x => x).ToArray();
                for (int i = 0; i < 1000000; i++)
                {
                    Assert.AreEqual(i, r1[i]);
                }
            }
        }
Example #25
0
        protected internal IIterator Find(StorageContext context, byte[] prefix)
        {
            byte[]          prefix_key = StorageKey.CreateSearchPrefix(context.Id, prefix);
            StorageIterator iterator   = new StorageIterator(Snapshot.Storages.Find(prefix_key).Where(p => p.Key.Key.AsSpan().StartsWith(prefix)).GetEnumerator());

            Disposables.Add(iterator);
            return(iterator);
        }
Example #26
0
 internal GateConfig(
     SchemaGenerationOptions schemaGenerationOptions,
     TransportConfig transportConfig)
 {
     _schemaGenerationOptions = schemaGenerationOptions;
     _transportConfig         = transportConfig;
     Disposables.Add(transportConfig);
 }
        protected CancellationTokenSource CreateCancellationTokenSource()
        {
            var cts = new CancellationTokenSource();

            lock (Disposables)
                Disposables.Add(cts);
            return(cts);
        }
Example #28
0
 public GamepadReadingTestViewModel(CoreDispatcher dispatcher) : base(dispatcher)
 {
     _checkTimer.Tick += CheckTimer_Tick;
     Disposables.Add(Disposable.Create(() =>
     {
         _checkTimer.Stop();
     }));
 }
Example #29
0
        protected Channel(EventMessage eventMessage, EventSocket eventSocket) : base(eventMessage, eventSocket)
        {
            eventSocket.SubscribeEvents(EventName.ChannelCreate).Wait();

            Disposables.Add(
                eventSocket.Events.Where(x => x.UUID == UUID && x.EventName == EventName.ChannelBridge).Subscribe(
                    x =>
            {
                Log.Trace(() => "Channel [{0}] Bridged to [{1}]".Fmt(UUID, x.GetHeader(HeaderNames.OtherLegUniqueId)));

                if (Bridge.Channel != null && x.GetHeader(HeaderNames.OtherLegUniqueId) != Bridge.Channel.UUID)
                {
                    //possibly changed bridge partner as part of att_xfer
                    Log.Warn(() => "Channel [{0}] was Bridged to [{1}] but now changed to [{2}]".Fmt(UUID, Bridge.Channel.UUID, x.UUID));

                    Bridge.Channel.Dispose();
                    Bridge = new BridgeStatus(true, "TRANSFERRED", new BridgedChannel(x, eventSocket));
                }
            }));

            Disposables.Add(
                eventSocket.Events.Where(x => x.UUID == UUID && x.EventName == EventName.ChannelUnbridge).Subscribe(
                    x => Log.Trace(() => "Channel [{0}] Unbridged from [{1}] {2}".Fmt(UUID, Bridge.Channel.UUID, x.GetVariable("bridge_hangup_cause")))));

            Disposables.Add(
                eventSocket.Events.Where(x => x.EventName == EventName.ChannelBridge &&
                                         x.UUID != UUID &&
                                         x.GetHeader(HeaderNames.OtherLegUniqueId) == UUID &&
                                         (Bridge.Channel != null && x.UUID != Bridge.Channel.UUID))
                .Subscribe(x =>
            {
                //there is another channel out there that has bridged to us but we didn't get the CHANNEL_BRIDGE event on this channel
                //possibly an attended transfer. We'll swap our bridge partner so we can get its events

                Log.Warn(() => "Channel [{0}] was Bridged to [{1}] but now changed to [{2}]".Fmt(UUID, Bridge.Channel.UUID, x.UUID));

                Bridge.Channel.Dispose();
                Bridge = new BridgeStatus(true, "TRANSFERRED", new BridgedChannel(x, eventSocket));
            }));

            if (this.eventSocket is OutboundSocket)
            {
                Disposables.Add(
                    eventSocket.Events.Where(x => x.UUID == UUID && x.EventName == EventName.ChannelHangup)
                    .Subscribe(async e =>
                {
                    if (ExitOnHangup)
                    {
                        await eventSocket.Exit();
                        Log.Info(() => "Channel [{0}] exited".Fmt(UUID));
                    }
                }));
            }

            //populate empty bridge status
            Bridge       = new BridgeStatus(false, null);
            ExitOnHangup = true;
        }
Example #30
0
        public FileOpenPickerTestsViewModel(CoreDispatcher dispatcher) : base(dispatcher)
        {
            Disposables.Add(Disposable.Create(() =>
            {
#if __WASM__
                WinRTFeatureConfiguration.Storage.Pickers.AllowWasmNativePickers = true;
#endif
            }));
        }