コード例 #1
0
        public void should_receive_errors_using_a_coruoutine()
        {
            IEnumerable <string> returnWords()
            {
                yield return("Mario");

                yield return("Cioni");

                throw new Exception("This should be caught in onError()");
                yield return("Gaspare");

                yield return("Fu");

                yield return("Giulia");
            }

            var messages = new List <string>();
            var observer = new AnonymousObserver <string>(
                onNext: w => messages.Add(w),
                onError: (e) => messages.Add("*** I got an error! ***"),
                onCompleted: () => messages.Add("Done")
                );

            using (returnWords().Select(w => w.ToLower()).Subscribe(observer))
            {
            }

            messages[0].Should().Be("mario");
            messages[1].Should().Be("cioni");
            messages[2].Should().Be("*** I got an error! ***");
//            messages[3].Should().Be("gaspare");
//            messages[4].Should().Be("fu");
//            messages[5].Should().Be("giulia");
//            messages[6].Should().Be("done");
        }
コード例 #2
0
        /// <summary>
        ///  The CancellationToken passed to the asynchronous Subscribe method is tied to the returned disposable subscription, allowing best-effort cancellation.
        ///   Pay attention that the the result of the parameter function is Task<IDisposable>.
        /// </summary>
        public virtual IObservable <TResult> Create <TResult>(Func <IObserver <TResult>, CancellationToken, Task <Action> > subscribeAsync)
        {
            return(new AnonymousObservable <TResult>(observer =>
            {
                var subscription = new SingleAssignmentDisposable();
                var cancellable = new CancellationDisposable();

                var taskObservable = subscribeAsync(observer, cancellable.Token).ToObservable();
                ///The logic of the first parameter (a stands for an action)
                /// if a is not null
                ///     subscription.Disposable= Disposable.Create(a);
                ///  else
                ///     subscription.Disposable=Disposable.Empty
                var taskCompletionObserver = new AnonymousObserver <Action>(
                    a => subscription.Disposable = a != null ? Disposable.Create(a) : Disposable.Empty, observer.OnError, Stubs.Nop);

                //
                // We don't cancel the subscription below *ever* and want to make sure the returned resource eventually gets disposed.
                // Notice because we're using the AnonymousObservable<T> type, we get auto-detach behavior for free.
                //
                taskObservable.Subscribe(taskCompletionObserver);

                return new CompositeDisposable(cancellable, subscription);
            }));
        }
コード例 #3
0
        /// <summary>
        /// The function of the code below is:
        ///     Creates an observable sequence from a specified cancellable asynchronous[异步的] Subscribe method.
        /// </summary>
        /// <typeparam name="TResult"> The type of the element in the return sequence.</typeparam>
        /// <param name="subscribeAsync"> A functions delegate takes 2 parameters and 1 output result.
        ///   The first parameter is an object that implements interface IObserver.
        ///   The second parameter is a structure named CancellationToken which propagates notification that operations should be canceled.
        ///   The result is an instance of Task that represents an asynchronous operation.
        /// </param>
        public virtual IObservable <TResult> Create <TResult>(Func <IObserver <TResult>, CancellationToken, Task> subscribeAsync)
        {
            //call constructor AnonymousObservable(Func<IObserver<T>, IDisposable> subscribe)
            // The parameter passed into the constructor is a lambda expression.
            // observer is input and the codes in {} is a procedure that can produce an IDisposable output result.
            return(new AnonymousObservable <TResult>(observer =>
            {
                // Initializes the System.Threading.CancellationTokenSource.
                var cancellable = new CancellationDisposable();

                //  There we see a new function ToObservable() which returns an observable sequence that signals when the task completes.
                // The second parameter means getting the <see cref="T:System.Threading.CancellationToken"/> used by this CancellationDisposable.
                var taskObservable = subscribeAsync(observer, cancellable.Token).ToObservable();

                //  constructor AnonymousObserver : Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
                //  new structure Unit
                //      Determines whether the specified Unit values is equal to the current Unit.
                var taskCompletionObserver = new AnonymousObserver <Unit>(Stubs <Unit> .Ignore, observer.OnError, observer.OnCompleted);

                //  Subscribe:  Notifies the provider taskObservable that an observer taskCompletionObserver is to receive notifications.
                var subscription = taskObservable.Subscribe(taskCompletionObserver);

                //   Represents a group of disposable resources that are disposed together.
                return new CompositeDisposable(cancellable, subscription);
            }));
        }
コード例 #4
0
        public void should_receive_errors()
        {
            var words = new List <string> {
                "Mario", "Cioni", "Di", "Gaspare", "Fu", "Giulia"
            }
            .Select(w =>
            {
                if (w == "Di")
                {
                    throw new Exception("This should be caught in onError()");
                }
                return(w);
            });

            var messages = new List <string>();
            var observer = new AnonymousObserver <string>(
                onNext: w => messages.Add(w),
                onError: (e) => messages.Add("*** I got an error! ***"),
                onCompleted: () => messages.Add("Done")
                );

            using (words.ToObservable().Select(w => w.ToLower()).Subscribe(observer))
            {
            }

            messages[0].Should().Be("mario");
            messages[1].Should().Be("cioni");
            messages[2].Should().Be("*** I got an error! ***");
//            messages[3].Should().Be("gaspare");
//            messages[4].Should().Be("fu");
//            messages[5].Should().Be("giulia");
//            messages[6].Should().Be("done");
        }
コード例 #5
0
    /// <summary>
    /// Subscribes to changes in the observable.
    /// </summary>
    /// <param name="observer">The subscriber.</param>
    /// <returns>A disposable object. When disposed, the observer will stop receiving events.</returns>
    public IDisposable Subscribe(IObserver <T> observer)
    {
        var disposableObserver = new AnonymousObserver(observer);

        this.observers.Add(disposableObserver);
        return(disposableObserver);
    }
コード例 #6
0
ファイル: Oscillator.cs プロジェクト: JohnStov/Theremin
        public Oscillator(int sampleRate, Func<double, double> generator)
        {
            this.sampleRate = sampleRate;
            Data = Samples(generator);

            Frequency = new AnonymousObserver<double>(SetFrequency);
        }
コード例 #7
0
        public void TestServiceBusWithEmbeddedBroker()
        {
            // use the embedded broker
            var brokerUri = _broker.FailoverUri;

            // set up ServiceBus using fluent interfaces and all current endpoints and pointing at test AMQ broker
            IServiceBus serviceBus = ServiceBus.Configure()
                .WithActiveMQEndpoints<ITestMessage1>()
                    .Named("Obvs.TestService")
                    .UsingQueueFor<TestCommand>().ClientAcknowledge()
                    .UsingQueueFor<TestCommand2>().ClientAcknowledge()
                    .UsingQueueFor<IRequest>().AutoAcknowledge()
                    .ConnectToBroker(brokerUri)
                    .SerializedAsJson()
                    .AsClientAndServer()
                .PublishLocally()
                    .OnlyMessagesWithNoEndpoints()
                .UsingConsoleLogging()
                .Create();

            // create threadsafe collection to hold received messages in
            ConcurrentBag<IMessage> messages = new ConcurrentBag<IMessage>();

            // create some actions that will act as a fake services acting on incoming commands and requests
            Action<TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent {Id = command.Id});
            Action<TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse {Id = request.Id});
            AnonymousObserver<IMessage> observer = new AnonymousObserver<IMessage>(messages.Add, Console.WriteLine, () => Console.WriteLine("OnCompleted"));

            // subscribe to all messages on the ServiceBus
            CompositeDisposable subscriptions = new CompositeDisposable
            {
                serviceBus.Events.Subscribe(observer),
                serviceBus.Commands.Subscribe(observer),
                serviceBus.Requests.Subscribe(observer),
                serviceBus.Commands.OfType<TestCommand>().Subscribe(fakeService1),
                serviceBus.Requests.OfType<TestRequest>().Subscribe(fakeService2)
            };
            
            // send some messages
            serviceBus.SendAsync(new TestCommand { Id = 123 });
            serviceBus.SendAsync(new TestCommand2 { Id = 123 });
            serviceBus.SendAsync(new TestCommand3 { Id = 123 });
            serviceBus.GetResponses(new TestRequest { Id = 456 }).Subscribe(observer);

            // wait some time until we think all messages have been sent and received over AMQ
            Thread.Sleep(TimeSpan.FromSeconds(1));

            // test we got everything we expected
            Assert.That(messages.OfType<TestCommand>().Count() == 1, "TestCommand not received");
            Assert.That(messages.OfType<TestCommand2>().Count() == 1, "TestCommand2 not received");
            Assert.That(messages.OfType<TestCommand3>().Count() == 1, "TestCommand3 not received");
            Assert.That(messages.OfType<TestEvent>().Count() == 1, "TestEvent not received");
            Assert.That(messages.OfType<TestRequest>().Count() == 1, "TestRequest not received");
            Assert.That(messages.OfType<TestResponse>().Count() == 1, "TestResponse not received");

            subscriptions.Dispose();
            ((IDisposable)serviceBus).Dispose();
            // win!
        }
コード例 #8
0
        public async Task ShouldSendAndReceiveMessagesOverServiceBus()
        {
            IServiceBus serviceBus = ServiceBus.Configure()
                                     .WithRabbitMQEndpoints <ITestMessage>()
                                     .Named("Obvs.TestService")
                                     .ConnectToBroker("amqp://192.168.99.100:32769") // edit to correspond with 5672 port on local RabbitMQ from DockerHub
                                     .SerializedAsJson()
                                     .AsClientAndServer()
                                     .PublishLocally().AnyMessagesWithNoEndpointClients()
                                     .UsingConsoleLogging()
                                     .Create();

            // create threadsafe collection to hold received messages in
            var messages = new ConcurrentBag <IMessage>();

            // create some actions that will act as a fake services acting on incoming commands and requests
            Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent {
                Id = command.Id
            });
            Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse {
                Id = request.Id
            });
            var observer = new AnonymousObserver <IMessage>(msg => { messages.Add(msg); Console.WriteLine(msg); }, exception => Console.WriteLine(exception));

            // subscribe to all messages on the ServiceBus
            var sub1 = serviceBus.Events.Subscribe(observer);
            var sub2 = serviceBus.Commands.Subscribe(observer);
            var sub3 = serviceBus.Requests.Subscribe(observer);
            var sub4 = serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1);
            var sub5 = serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2);

            // send some messages
            await serviceBus.SendAsync(new TestCommand { Id = 123 });

            var sub6 = serviceBus.GetResponses(new TestRequest {
                Id = 456
            }).Subscribe(observer);

            // wait some time until we think all messages have been sent and received from RabbitMQ
            await Task.Delay(TimeSpan.FromSeconds(1));

            // test we got everything we expected
            Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received");
            Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received");
            Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received");
            Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received");

            // dispose subscriptions
            sub1.Dispose();
            sub2.Dispose();
            sub3.Dispose();
            sub4.Dispose();
            sub5.Dispose();
            sub6.Dispose();

            // always call Dispose on serviceBus when exiting process
            ((IDisposable)serviceBus).Dispose();
        }
コード例 #9
0
        public MainWindowViewModel()
        {
            IObserver <string> observer = new AnonymousObserver <string>(s =>
            {
                Debug.WriteLine("xx" + s);
                ReactiveTracer.Add(s);
            });

            LoggerAdapter.TracerSubject.Subscribe(observer);
        }
コード例 #10
0
        public async void TestServiceEndpointsOverLocalHostSockets()
        {
            // set up ServiceBus using fluent interfaces and all current endpoints and pointing at localhost
            var serviceBus = ServiceBus.Configure()
                             .WithNetMqEndpoints <ITestMessage>()
                             .Named("Obvs.TestNetMqService")
                             .BindToAddress("tcp://localhost")
                             .OnPort(5555)
                             .SerializedAsJson()
                             .AsClientAndServer()
                             .UsingConsoleLogging()
                             .Create();

            // create threadsafe collection to hold received messages in
            var messages = new ConcurrentBag <IMessage>();

            // create some actions that will act as a fake services acting on incoming commands and requests
            Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent {
                Id = command.Id
            });
            Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse {
                Id = request.Id
            });
            var observer = new AnonymousObserver <IMessage>(msg =>
            {
                messages.Add(msg);
                Console.WriteLine(msg);
            }, exception => Console.WriteLine(exception));

            // subscribe to all messages on the ServiceBus
            serviceBus.Events.Subscribe(observer);
            serviceBus.Commands.Subscribe(observer);
            serviceBus.Requests.Subscribe(observer);
            serviceBus.Commands.OfType <TestCommand>().SubscribeOn(TaskPoolScheduler.Default).Subscribe(fakeService1);
            serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2);

            // send some messages
            await serviceBus.SendAsync(new TestCommand { Id = 123 });

            serviceBus.GetResponses(new TestRequest {
                Id = 456
            }).Subscribe(observer);

            // wait some time until we think all messages have been sent and received over AMQ
            await Task.Delay(TimeSpan.FromSeconds(2));

            // test we got everything we expected
            Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received");
            Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received");
            Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received");
            Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received");

            // win!
        }
コード例 #11
0
        public async void TestServiceBusWithLocalEventStore()
        {
            var serviceBus = ServiceBus.Configure()
                .WithEventStoreSharedConnectionScope("ConnectTo=tcp://admin:[email protected]:1113", config => config
                    .WithEventStoreEndpoints<ITestMessage1>()
                        .Named("Obvs.EventStore.Test")
                        .AppendMessageProperties(message => null)
                        .FilterReceivedMessages(properties => true)
                        .UseSharedConnection()
                        .SerializedAsJson()
                        .AsClientAndServer())
                .UsingConsoleLogging()
                .Create();

            var fakeService = new AnonymousObserver<ITestMessage1>(msg =>
            {
                var command = msg as TestCommand;
                if (command != null)
                {
                    serviceBus.PublishAsync(new TestEvent {Id = command.Id});
                    return;
                }

                var request = msg as TestRequest;
                if (request != null)
                {
                    serviceBus.ReplyAsync(request, new TestResponse {Id = request.Id});
                }
            });

            var sub = serviceBus.Commands.OfType<ITestMessage1>()
                .Merge(serviceBus.Requests.OfType<ITestMessage1>())
                .ObserveOn(Scheduler.Default)
                .Subscribe(fakeService);

            var receivedEvent = await Observable.Create<TestEvent>(observer =>
            {
                var disposable = serviceBus.Events
                    .OfType<TestEvent>()
                    .ObserveOn(Scheduler.Default)
                    .Subscribe(observer);

                serviceBus.SendAsync(new TestCommand {Id = 123});

                return disposable;
            }).Take(1);

            var receivedResponse = await serviceBus.GetResponse<TestResponse>(new TestRequest {Id = 456});

            sub.Dispose();

            Assert.That(receivedEvent.Id, Is.EqualTo(123));
            Assert.That(receivedResponse.Id, Is.EqualTo(456));
        }
コード例 #12
0
        private async Task ShouldSendAndReceiveMessagesOverServiceBus(IServiceBus serviceBus)
        {
            // create threadsafe collection to hold received messages in
            var messages = new ConcurrentBag <IMessage>();

            // create some actions that will act as a fake services acting on incoming commands and requests
            Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent {
                Id = command.Id
            });
            Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse {
                Id = request.Id
            });
            var observer = new AnonymousObserver <IMessage>(msg =>
            {
                messages.Add(msg);
                _output.WriteLine(JsonConvert.SerializeObject(msg));
            }, exception => _output.WriteLine(exception.ToString()));

            // subscribe to all messages on the ServiceBus
            var sub1 = serviceBus.Events.Subscribe(observer);
            var sub2 = serviceBus.Commands.Subscribe(observer);
            var sub3 = serviceBus.Requests.Subscribe(observer);
            var sub4 = serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1);
            var sub5 = serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2);

            // send some messages
            await serviceBus.SendAsync(new TestCommand { Id = 123 });

            var sub6 = serviceBus.GetResponses(new TestRequest {
                Id = 456
            }).Subscribe(observer);

            // wait some time until we think all messages have been sent and received from RabbitMQ
            await Task.Delay(TimeSpan.FromSeconds(1));

            // test we got everything we expected
            Assert.True(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received");
            Assert.True(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received");
            Assert.True(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received");
            Assert.True(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received");

            // dispose subscriptions
            sub1.Dispose();
            sub2.Dispose();
            sub3.Dispose();
            sub4.Dispose();
            sub5.Dispose();
            sub6.Dispose();

            // always call Dispose on serviceBus when exiting process
            ((IDisposable)serviceBus).Dispose();
        }
コード例 #13
0
        public virtual IObservable <TResult> Create <TResult>(Func <IObserver <TResult>, CancellationToken, Task> subscribeAsync)
        {
            return(new AnonymousObservable <TResult>(observer =>
            {
                var cancellable = new CancellationDisposable();

                var taskObservable = subscribeAsync(observer, cancellable.Token).ToObservable();
                var taskCompletionObserver = new AnonymousObserver <Unit>(Stubs <Unit> .Ignore, observer.OnError, observer.OnCompleted);
                var subscription = taskObservable.Subscribe(taskCompletionObserver);

                return StableCompositeDisposable.Create(cancellable, subscription);
            }));
        }
コード例 #14
0
        public async Task TestSendingAndReceivingBytesOverLocalHost()
        {
            const string topic = "TestTopic";

            var messages = new ConcurrentBag <IMessage>();

            var observer = new AnonymousObserver <IMessage>(msg =>
            {
                Console.WriteLine("Received: " + msg);
                messages.Add(msg);
            }, err => Console.WriteLine("Error: " + err));

            IMessageSource <IMessage> source = new MessageSource <IMessage>("tcp://localhost:5556",
                                                                            new IMessageDeserializer <IMessage>[]
            {
                new ProtoBufMessageDeserializer <TestMessage1>(),
                new ProtoBufMessageDeserializer <TestMessage2>()
            },
                                                                            topic);

            var sub = source.Messages.Subscribe(observer);

            IMessagePublisher <IMessage> publisher = new MessagePublisher <IMessage>("tcp://localhost:5556",
                                                                                     new ProtoBufMessageSerializer(), topic);

            await publisher.PublishAsync(new TestMessage1 { Id = 1 });

            await publisher.PublishAsync(new TestMessage1 { Id = 2 });

            await publisher.PublishAsync(new TestMessage2 { Id = 1 });

            await publisher.PublishAsync(new TestMessage2 { Id = 2 });

            await publisher.PublishAsync(new TestMessage1 { Id = 3 });

            await publisher.PublishAsync(new TestMessage2 { Id = 3 });

            await Task.Delay(TimeSpan.FromSeconds(2));

            Assert.True(messages.OfType <TestMessage1>().Any(msg => msg.Id == 1), "TestMessage1 1 not received");
            Assert.True(messages.OfType <TestMessage1>().Any(msg => msg.Id == 2), "TestMessage1 2 not received");
            Assert.True(messages.OfType <TestMessage1>().Any(msg => msg.Id == 3), "TestMessage1 3 not received");

            Assert.True(messages.OfType <TestMessage2>().Any(msg => msg.Id == 1), "TestMessage2 1 not received");
            Assert.True(messages.OfType <TestMessage2>().Any(msg => msg.Id == 2), "TestMessage2 2 not received");
            Assert.True(messages.OfType <TestMessage2>().Any(msg => msg.Id == 3), "TestMessage2 3 not received");

            sub.Dispose();
            source.Dispose();
        }
コード例 #15
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // string name = req.Query["name"];

            // string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            // dynamic data = JsonConvert.DeserializeObject(requestBody);

            var eventNames = new List <string>();

            Action <KeyValuePair <string, object> > callback = (KeyValuePair <string, object> evnt) =>
            {
                eventNames.Add(evnt.Key);
                Console.WriteLine($"{evnt.Key} {evnt.Value}");
                Console.WriteLine($"Activity.Current.Id: {Activity.Current?.Id}");
                Console.WriteLine($"Activity.Current.ParentId: {Activity.Current?.ParentId}");
                Console.WriteLine($"Activity.Current.OperationName: {Activity.Current?.OperationName}");
                Console.WriteLine("=========================================================================");
            };

            // Turn it into an observer (using System.Reactive.Core's AnonymousObserver)
            IObserver <KeyValuePair <string, object> > observer = new AnonymousObserver <KeyValuePair <string, object> >(callback);

            // Create a predicate (asks only for one kind of event)
            Func <string, object, object, bool> predicate = (string eventName, object request, object arg3) =>
            {
                return(true);
            };

            DiagnosticListener.AllListeners.Subscribe(delegate(DiagnosticListener listener)
            {
                // We get a callback of every Diagnostics Listener that is active in the system (past present or future)
                if (listener.Name == "HttpHandlerDiagnosticListener")
                {
                    Console.WriteLine("Subscribed to HttpHandlerDiagnosticListener");
                    listener.Subscribe(observer, predicate);
                }
            });

            var httpClient = new HttpClient();
            var res        = await httpClient.GetStringAsync("http://google.com");

            return(new OkObjectResult(eventNames));
        }
コード例 #16
0
        public void ShouldSendAndReceiveMessagesOverServiceBus()
        {
            IServiceBus serviceBus = ServiceBus.Configure()
                                     .WithRabbitMQEndpoints <ITestMessage>()
                                     .Named("Obvs.TestService")
                                     .ConnectToBroker("amqp://localhost")
                                     .SerializedAsJson()
                                     .AsClientAndServer()
                                     .UsingConsoleLogging()
                                     .Create();

            // create threadsafe collection to hold received messages in
            ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>();

            // create some actions that will act as a fake services acting on incoming commands and requests
            Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent {
                Id = command.Id
            });
            Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse {
                Id = request.Id
            });
            AnonymousObserver <IMessage> observer = new AnonymousObserver <IMessage>(msg => { messages.Add(msg); Console.WriteLine(msg); }, exception => Console.WriteLine(exception));

            // subscribe to all messages on the ServiceBus
            serviceBus.Events.Subscribe(observer);
            serviceBus.Commands.Subscribe(observer);
            serviceBus.Requests.Subscribe(observer);
            serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1);
            serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2);

            // send some messages
            serviceBus.SendAsync(new TestCommand {
                Id = 123
            });
            serviceBus.GetResponses(new TestRequest {
                Id = 456
            }).Subscribe(observer);

            // wait some time until we think all messages have been sent and received from RabbitMQ
            Thread.Sleep(TimeSpan.FromSeconds(1));

            // test we got everything we expected
            Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received");
            Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received");
            Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received");
            Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received");
        }
コード例 #17
0
        private Task SearchAsync()
        {
            Device.BeginInvokeOnMainThread(() => { ViewModel.Device = "Searching"; });

            var tcs = new TaskCompletionSource <bool>();

            Task.Run(async() =>
            {
                using (var discoveryService = new DiscoveryService())
                    using (var observer = new AnonymousObserver <DeviceAvailableEventArgs>(async e =>
                    {
                        State.PreviousDevice = await TargetDevice.FromDiscoveredDeviceAsync(e.DiscoveredDevice);
                        tcs.SetResult(true);
                    }))
                    {
                        var pipeline = Observable
                                       .FromEventPattern <DeviceAvailableEventArgs>(
                            handler => discoveryService.OnDevice += handler,
                            handler => discoveryService.OnDevice -= handler
                            )
                                       .Select(x => x.EventArgs);

                        if (State.PreviousDevice == null)
                        {
                            pipeline = pipeline
                                       .Take(1);
                        }

                        if (State?.PreviousDevice?.Usn != null)
                        {
                            pipeline = pipeline
                                       .Where(x => x.DiscoveredDevice.Usn == State.PreviousDevice.Usn)
                                       .Take(1);
                        }

                        pipeline.Subscribe(observer);

                        await discoveryService.SearchAsync();
                        tcs.SetResult(true);
                    }
            });

            return(tcs.Task);
        }
コード例 #18
0
        public virtual IObservable <TResult> Create <TResult>(Func <IObserver <TResult>, CancellationToken, Task <IDisposable> > subscribeAsync)
        {
            return(new AnonymousObservable <TResult>(observer =>
            {
                var subscription = new SingleAssignmentDisposable();
                var cancellable = new CancellationDisposable();

                var taskObservable = subscribeAsync(observer, cancellable.Token).ToObservable();
                var taskCompletionObserver = new AnonymousObserver <IDisposable>(d => subscription.Disposable = d ?? Disposable.Empty, observer.OnError, Stubs.Nop);

                //
                // We don't cancel the subscription below *ever* and want to make sure the returned resource gets disposed eventually.
                // Notice because we're using the AnonymousObservable<T> type, we get auto-detach behavior for free.
                //
                taskObservable.Subscribe(taskCompletionObserver);

                return StableCompositeDisposable.Create(cancellable, subscription);
            }));
        }
コード例 #19
0
        private Task <CommandResult <TResponse> > Execute <TResponse>(IObservable <TResponse> observable, BaseCommand <TResponse> command, CommandResult <TResponse> commandResult)
        {
            TaskCompletionSource <CommandResult <TResponse> > tcs = new TaskCompletionSource <CommandResult <TResponse> >();

            try
            {
                AnonymousObserver <TResponse> observer =
                    new AnonymousObserver <TResponse>(
                        _ => { },
                        _ => tcs.TrySetResult(commandResult),
                        () => tcs.TrySetResult(commandResult));

                observable.Subscribe(observer);
            }
            catch (Exception ex)
            {
                this.OnExecutionException(command, commandResult, ex);
                tcs.TrySetResult(commandResult);
            }

            return(tcs.Task);
        }
コード例 #20
0
ファイル: Kafka4NetTests.cs プロジェクト: dicko2/Obvs.Kafka
        public void TestServiceBusWithRemoteKafka()
        {
            IServiceBus serviceBus = ServiceBus.Configure()
                                     .WithKafkaEndpoints <ITestMessage1>()
                                     .Named("Obvs.TestService")
                                     .AppendMessageProperties(message => new Dictionary <string, string> {
                { "TestProperty", "123" }
            })
                                     .FilterReceivedMessages(properties => true)
                                     .ConnectToKafka(_seed2Addresses)
                                     .SerializedAsJson()
                                     .AsClientAndServer()
                                     .PublishLocally()
                                     .OnlyMessagesWithNoEndpoints()
                                     .UsingConsoleLogging()
                                     .Create();

            ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>();

            // create some actions that will act as a fake services acting on incoming commands and requests
            Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent {
                Id = command.Id
            });
            Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse {
                Id = request.Id
            });
            AnonymousObserver <IMessage> observer = new AnonymousObserver <IMessage>(x =>
            {
                Console.WriteLine("********* " + x);
                messages.Add(x);
            }, Console.WriteLine, () => Console.WriteLine("OnCompleted"));

            // subscribe to all messages on the ServiceBus
            CompositeDisposable subscriptions = new CompositeDisposable
            {
                serviceBus.Events.Subscribe(observer),
                serviceBus.Commands.Subscribe(observer),
                serviceBus.Requests.Subscribe(observer),
                serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1),
                serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2)
            };

            // send some messages
            serviceBus.SendAsync(new TestCommand {
                Id = 123
            });
            serviceBus.SendAsync(new TestCommand2 {
                Id = 123
            });
            serviceBus.SendAsync(new TestCommand3 {
                Id = 123
            });
            serviceBus.GetResponses(new TestRequest {
                Id = 456
            }).Subscribe(observer);

            // wait some time until we think all messages have been sent and received over AMQ
            Thread.Sleep(TimeSpan.FromSeconds(10));

            // test we got everything we expected
            Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received");
            Assert.That(messages.OfType <TestCommand2>().Count() == 1, "TestCommand2 not received");
            Assert.That(messages.OfType <TestCommand3>().Count() == 1, "TestCommand3 not received");
            Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received");
            Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received");
            Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received");

            subscriptions.Dispose();
            ((IDisposable)serviceBus).Dispose();
            // win!
        }
コード例 #21
0
        private static Task ForEachAsync_ <TSource>(IObservable <TSource> source, Action <TSource> onNext, CancellationToken cancellationToken)
        {
            var tcs          = new TaskCompletionSource <object>();
            var subscription = new SingleAssignmentDisposable();

            var ctr = default(CancellationTokenRegistration);

            if (cancellationToken.CanBeCanceled)
            {
                ctr = cancellationToken.Register(() =>
                {
                    tcs.TrySetCanceled(cancellationToken);
                    subscription.Dispose();
                });
            }

            if (!cancellationToken.IsCancellationRequested)
            {
                // Making sure we always complete, even if disposing throws.
                var dispose = new Action <Action>(action =>
                {
                    try
                    {
                        ctr.Dispose(); // no null-check needed (struct)
                        subscription.Dispose();
                    }
                    catch (Exception ex)
                    {
                        tcs.TrySetException(ex);
                        return;
                    }

                    action();
                });

                var taskCompletionObserver = new AnonymousObserver <TSource>(
                    x =>
                {
                    if (!subscription.IsDisposed)
                    {
                        try
                        {
                            onNext(x);
                        }
                        catch (Exception exception)
                        {
                            dispose(() => tcs.TrySetException(exception));
                        }
                    }
                },
                    exception =>
                {
                    dispose(() => tcs.TrySetException(exception));
                },
                    () =>
                {
                    dispose(() => tcs.TrySetResult(null));
                }
                    );

                //
                // Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
                // will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
                // spot, which may throw an exception. (See TFS 487142)
                //
                try
                {
                    //
                    // [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
                    //
                    // Notice we could use a safe subscription to route errors through OnError, but we still need the
                    // exception handling logic here for the reason explained above. We cannot afford to throw here
                    // and as a result never set the TaskCompletionSource, so we tunnel everything through here.
                    //
                    subscription.Disposable = source.Subscribe/*Unsafe*/ (taskCompletionObserver);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            }

            return(tcs.Task);
        }
コード例 #22
0
ファイル: DckSubject.cs プロジェクト: ODck/DckSubject
        public IDisposable Subscribe(Action <T> callback)
        {
            var observer = new AnonymousObserver <T>(callback);

            return(Subscribe(observer));
        }
コード例 #23
0
        public async Task TestServiceBusWithLocalEventStore()
        {
            // run EventStore on Docker and then edit below for local address:port that maps to 1113
            var serviceBus = ServiceBus.Configure()
                             .WithEventStoreSharedConnectionScope("ConnectTo=tcp://admin:[email protected]:32777", config => config
                                                                  .WithEventStoreEndpoints <ITestMessage1>()
                                                                  .Named("Obvs.EventStore.Test")
                                                                  .AppendMessageProperties(message => null)
                                                                  .FilterReceivedMessages(properties => true)
                                                                  .UseSharedConnection()
                                                                  .SerializedAsJson()
                                                                  .AsClientAndServer())
                             .UsingConsoleLogging()
                             .Create();

            var fakeService = new AnonymousObserver <ITestMessage1>(msg =>
            {
                var command = msg as TestCommand;
                if (command != null)
                {
                    serviceBus.PublishAsync(new TestEvent {
                        Id = command.Id
                    });
                    return;
                }

                var request = msg as TestRequest;
                if (request != null)
                {
                    serviceBus.ReplyAsync(request, new TestResponse {
                        Id = request.Id
                    });
                }
            });

            var sub = serviceBus.Commands.OfType <ITestMessage1>()
                      .Merge(serviceBus.Requests.OfType <ITestMessage1>())
                      .ObserveOn(Scheduler.Default)
                      .Subscribe(fakeService);

            var receivedEvent = await Observable.Create <TestEvent>(observer =>
            {
                var disposable = serviceBus.Events
                                 .OfType <TestEvent>()
                                 .ObserveOn(Scheduler.Default)
                                 .Subscribe(observer);

                serviceBus.SendAsync(new TestCommand {
                    Id = 123
                });

                return(disposable);
            }).Take(1);

            var receivedResponse = await serviceBus.GetResponse <TestResponse>(new TestRequest { Id = 456 });

            sub.Dispose();

            Assert.That(receivedEvent.Id, Is.EqualTo(123));
            Assert.That(receivedResponse.Id, Is.EqualTo(456));
        }
コード例 #24
0
ファイル: DckSubject.cs プロジェクト: ODck/DckSubject
        public IDisposable Subscribe(Action <T> callback, Action <Exception> error, Action finish)
        {
            var observer = new AnonymousObserver <T>(callback, error, finish);

            return(Subscribe(observer));
        }
コード例 #25
0
 public void AnonymousObserver_Error_Null()
 {
     var observer = new AnonymousObserver<int>(_ => { }, e => { }, () => { });
     ReactiveAssert.Throws<ArgumentNullException>(() => observer.OnError(null));
 }
コード例 #26
0
ファイル: AnonymousTest.cs プロジェクト: ctaggart/Rx.NET
        public void AnonymousObserver_Error_Null()
        {
            var observer = new AnonymousObserver <int>(_ => { }, e => { }, () => { });

            ReactiveAssert.Throws <ArgumentNullException>(() => observer.OnError(null));
        }
コード例 #27
0
            public IDisposable Subscribe(IExcelObserver excelObserver)
            {
                var observer = new AnonymousObserver <T>(value => excelObserver.OnNext(value), excelObserver.OnError, excelObserver.OnCompleted);

                return(_observable.Subscribe(observer));
            }
コード例 #28
0
        /// <summary>
        /// Returns a task that will receive the last value or the exception produced by the observable sequence.
        /// </summary>
        /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
        /// <param name="observable">Observable sequence to convert to a task.</param>
        /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
        /// <param name="state">The state to use as the underlying task's AsyncState.</param>
        /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
        public static Task <TResult> ToTask <TResult>(this IObservable <TResult> observable, CancellationToken cancellationToken, object state)
        {
            if (observable == null)
            {
                throw new ArgumentNullException("observable");
            }

            var hasValue  = false;
            var lastValue = default(TResult);

            var tcs = new TaskCompletionSource <TResult>(state);

            var disposable = new SingleAssignmentDisposable();

            var ctr = default(CancellationTokenRegistration);

            if (cancellationToken.CanBeCanceled)
            {
                ctr = cancellationToken.Register(() =>
                {
                    disposable.Dispose();
                    tcs.TrySetCanceled();
                });
            }

            var taskCompletionObserver = new AnonymousObserver <TResult>(
                value =>
            {
                hasValue  = true;
                lastValue = value;
            },
                ex =>
            {
                tcs.TrySetException(ex);

                ctr.Dispose();     // no null-check needed (struct)
                disposable.Dispose();
            },
                () =>
            {
                if (hasValue)
                {
                    tcs.TrySetResult(lastValue);
                }
                else
                {
                    tcs.TrySetException(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
                }

                ctr.Dispose();     // no null-check needed (struct)
                disposable.Dispose();
            }
                );

            //
            // Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
            // will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
            // spot, which may throw an exception. (Similar to TFS 487142)
            //
            try
            {
                //
                // [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
                //
                // Notice we could use a safe subscription to route errors through OnError, but we still need the
                // exception handling logic here for the reason explained above. We cannot afford to throw here
                // and as a result never set the TaskCompletionSource, so we tunnel everything through here.
                //
                disposable.Disposable = observable.Subscribe/*Unsafe*/ (taskCompletionObserver);
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            return(tcs.Task);
        }