Beispiel #1
0
        public Future <char> Read(bool advance = true)
        {
            var f = new Future <char>();

            SetPendingOperation(f);

            char result;

            if (!GetCurrentCharacter(out result))
            {
                var decodeMoreChars = DecodeMoreData();
                decodeMoreChars.RegisterOnComplete((_) => {
                    if (IsDisposed)
                    {
                        f.Dispose();
                        return;
                    }

                    var error = _.Error;
                    if (error != null)
                    {
                        ClearPendingOperation(f);
                        f.Fail(error);
                    }
                    else
                    {
                        char ch;
                        if (GetCurrentCharacter(out ch))
                        {
                            if (advance)
                            {
                                ReadNextCharacter();
                            }
                            ClearPendingOperation(f);
                            f.Complete(ch);
                        }
                        else
                        {
                            ClearPendingOperation(f);
                            f.Complete(null);
                        }
                    }
                });
            }
            else
            {
                if (advance)
                {
                    ReadNextCharacter();
                }
                ClearPendingOperation(f);
                f.Complete(result);
            }

            return(f);
        }
Beispiel #2
0
        public void An_exception_is_thrown()
        {
            var future = new Future<object>();

            var obj1 = new object();
            var obj2 = new object();

            future.Complete(obj1);
            Assert.That(() => future.Complete(obj2), Throws.TypeOf<InvalidOperationException>());
        }
Beispiel #3
0
        public void An_exception_is_thrown()
        {
            var future = new Future <object>();

            var obj1 = new object();
            var obj2 = new object();

            future.Complete(obj1);
            Assert.That(() => future.Complete(obj2), Throws.TypeOf <InvalidOperationException>());
        }
Beispiel #4
0
		public void Should_properly_arrive_at_the_destination()
		{
			var serviceUri = new Uri("net.pipe://localhost/pipe");
			string pipeName = "test";

			var future = new Future<TestMessage>();
			var message = new TestMessage
				{
					Id = Guid.NewGuid(),
					Name = "Alpha",
				};

			UntypedChannel adapter = new ChannelAdapter();
			using (var remote = new WcfChannelHost(new SynchronousFiber(), adapter, serviceUri, pipeName))
			{
				using (adapter.Connect(x =>
					{
						x.AddConsumerOf<TestMessage>()
							.UsingConsumer(m => future.Complete(m));
					}))
				{
					var client = new WcfChannelProxy(new SynchronousFiber(), serviceUri, pipeName);

					client.Send(message);

					future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue();
				}
			}

			future.Value.ShouldNotBeNull();
			future.Value.ShouldEqual(message);
			future.Value.ShouldNotBeTheSameAs(message);
		}
Beispiel #5
0
        public void Newly_created_account_should_have_correct_balence_and_credit()
        {
            ActorRef      account = ActorFactory.Create(inbox => new AccountActor(inbox, 100.0m)).GetActor();
            Future <bool> result  = new Future <bool>();

            decimal balance         = 0xDEADBEEF;
            decimal availableCredit = 0xDEADBEEF;
            decimal creditLimit     = 0xDEADBEEF;

            AnonymousActor.New(inbox =>
            {
                account.Request(new QueryAccountBalance(), inbox)
                .Receive <AccountBalance>(message =>
                {
                    balance         = message.Balance;
                    availableCredit = message.AvailableCredit;
                    creditLimit     = message.CreditLimit;

                    Console.WriteLine("Balance={0}, Credit={1}, Limit={2}",
                                      balance, availableCredit, creditLimit);
                    result.Complete(true);
                });
            });

            result.WaitUntilCompleted(5.Seconds());
            Assert.True(balance == 0 && availableCredit == 100.0m && creditLimit == 100.0m);
        }
Beispiel #6
0
        public void Should_support_the_username_password_for_a_host()
        {
            var inputAddress = new Uri("rabbitmq://localhost/mt/test_queue");
            var future = new Future<IConsumeContext<A>>();

            using (IServiceBus bus = ServiceBusFactory.New(c =>
                {
                    c.ReceiveFrom(inputAddress);
                    c.UseRabbitMq(r =>
                        {
                            r.ConfigureHost(inputAddress, h =>
                                {
                                    h.SetUsername("testUser");
                                    h.SetPassword("test");
                                });
                        });

                    c.Subscribe(s => s.Handler<A>((context, message) => future.Complete(context)));
                }))
            {
                bus.Publish(new A());

                Assert.IsTrue(future.WaitUntilCompleted(TimeSpan.FromSeconds(8)));
            }

            Assert.AreEqual(inputAddress.ToString(), future.Value.SourceAddress.ToString());
        }
Beispiel #7
0
		public void Adding_operations_to_a_fiber()
		{
			_count = 10000;
			_values = new int[_count];
			Fiber fiber = new PoolFiber();

			int index = 0;
			var completed = new Future<int>();

			var go = new Future<bool>();

			fiber.Add(() => { go.WaitUntilCompleted(10.Seconds()); });

			for (int i = 0; i < _count; i++)
			{
				int offset = i;
				fiber.Add(() =>
					{
						_values[offset] = index++;

						if (offset == _count - 1)
							completed.Complete(offset);
					});
			}

			go.Complete(true);

			completed.WaitUntilCompleted(10.Seconds()).ShouldBeTrue();
		}
 protected static EventHeapState query_internal_state()
 {
     var reply = new Future<EventHeapState>();
     AnonymousActor.New(inbox => eventFilter.Request<QueryInternals>(inbox).Receive<EventHeapState>(msg => reply.Complete(msg)));
     reply.WaitUntilCompleted(-1);
     return reply.Value;
 }
        private void GivenSubscriptionsToAQueueInTwoRegions()
        {
            var primaryHandler = Substitute.For <IHandlerAsync <SimpleMessage> >();

            primaryHandler.Handle(Arg.Any <SimpleMessage>()).Returns(true);
            primaryHandler
            .When(x => x.Handle(Arg.Any <SimpleMessage>()))
            .Do(async x => await _primaryHandler.Complete((SimpleMessage)x.Args()[0]));

            _primaryBus = CreateMeABus
                          .WithLogging(LoggerFactory)
                          .InRegion(PrimaryRegion)
                          .WithSqsTopicSubscriber()
                          .IntoQueue(QueueName)
                          .WithMessageHandler(primaryHandler);

            _primaryBus.StartListening();

            var secondaryHandler = Substitute.For <IHandlerAsync <SimpleMessage> >();

            secondaryHandler.Handle(Arg.Any <SimpleMessage>()).Returns(true);
            secondaryHandler
            .When(x => x.Handle(Arg.Any <SimpleMessage>()))
            .Do(async x => await _secondaryHandler.Complete((SimpleMessage)x.Args()[0]));

            _secondaryBus = CreateMeABus
                            .WithLogging(LoggerFactory)
                            .InRegion(SecondaryRegion)
                            .WithSqsTopicSubscriber()
                            .IntoQueue(QueueName)
                            .WithMessageHandler(secondaryHandler);

            _secondaryBus.StartListening();
        }
        public void a_rat_is_sent_to_a_hungry_cat()
        {
            rat_id       = CombGuid.Generate();
            received_rat = new Future <Rat>();
            cat          = new ConsumerOf <Rat>(a_large_rat_actually =>
            {
                Console.WriteLine("Miaooo!!!");
                Console.WriteLine(a_large_rat_actually.Sound + "!!!");
                Console.WriteLine("Cat: chase! ...");
                Console.WriteLine("*silence*");
                Console.WriteLine("Cat: *Crunch chrunch*");
                received_rat.Complete(a_large_rat_actually);
            });

            cat_nap_unsubscribes = RemoteBus.SubscribeInstance(cat);

            // we need to make sure this bus is up before sending to it
            RemoteBus.Endpoint.InboundTransport.Receive(ctx => c => { }, 4.Seconds());

            LocalBus.GetEndpoint(RemoteUri).Send <Rat>(new
            {
                Sound         = "Eeeek",
                CorrelationId = rat_id
            });
        }
Beispiel #11
0
        public void Should_property_adapt_itself_to_a_channel_network()
        {
            TraceLogger.Configure(LogLevel.Debug);
            ILogger log = Logger.GetLogger<Sending_a_message_through_a_wcf_channel>();
            log.Debug("Starting");

            var serviceUri = new Uri("net.pipe://localhost/Pipe");
            string pipeName = "Test";
            Channel<TestMessage> adapter = new ChannelAdapter<TestMessage>();
            using (var host = new WcfChannelHost<TestMessage>(adapter, serviceUri, pipeName))
            {
                log.Debug("Host started");

                var future = new Future<TestMessage>();

                using (adapter.Connect(x =>
                    {
                        x.AddConsumer(m =>
                            {
                                log.Debug(l => l.Write("Received: {0}", m.Value));
                                future.Complete(m);
                            });
                    }))
                {
                    var client = new WcfChannelProxy<TestMessage>(new SynchronousFiber(), serviceUri, pipeName);
                    log.Debug("Client started");

                    client.Send(new TestMessage("Hello!"));

                    future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue();

                    log.Debug("Complete");
                }
            }
        }
Beispiel #12
0
        public void Should_properly_arrive_at_the_destination()
        {
            var    serviceUri = new Uri("net.pipe://localhost/pipe");
            string pipeName   = "test";

            var future  = new Future <TestMessage>();
            var message = new TestMessage
            {
                Id   = Guid.NewGuid(),
                Name = "Alpha",
            };

            UntypedChannel adapter = new ChannelAdapter();

            using (var remote = new WcfChannelHost(new SynchronousFiber(), adapter, serviceUri, pipeName))
            {
                using (adapter.Connect(x =>
                {
                    x.AddConsumerOf <TestMessage>()
                    .UsingConsumer(m => future.Complete(m));
                }))
                {
                    var client = new WcfChannelProxy(new SynchronousFiber(), serviceUri, pipeName);

                    client.Send(message);

                    future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue();
                }
            }

            future.Value.ShouldNotBeNull();
            future.Value.ShouldEqual(message);
            future.Value.ShouldNotBeTheSameAs(message);
        }
Beispiel #13
0
		public void A_loopback_registry()
		{
			Address = new Uri("loopback://localhost/");
			ReceivedA = new Future<A>();

			Registry = ActorRegistryFactory.New(x =>
			{
				x.Remote(r =>
				{
					r.ListenTo(Address);
				});
			});

			ActorId = Guid.NewGuid();
			Actor = AnonymousActor.New(inbox =>
			{
				inbox.Loop(loop =>
				{
					loop.Receive<Message<A>>(message =>
					{
						ReceivedA.Complete(message.Body);

						loop.Continue();
					});
				});
			});

			Registry.Register(ActorId, Actor);
		}
        protected override void ConfigureServiceBus(Uri uri, IServiceBusConfigurator configurator)
        {
            base.ConfigureServiceBus(uri, configurator);
            _received = new Future <TestMessage>();

            configurator.Subscribe(s => s.Handler <TestMessage>(message => _received.Complete(message)));
        }
        public void Should_run_the_action_until_disabled()
        {
            Fiber     fiber     = new PoolFiber();
            Scheduler scheduler = new TimerScheduler(new PoolFiber());

            Stopwatch elapsed = Stopwatch.StartNew();

            int count  = 0;
            var called = new Future <int>();
            var failed = new Future <bool>();

            ScheduledOperation scheduledAction = null;

            scheduledAction = scheduler.Schedule(TimeSpan.Zero, 100.Milliseconds(), fiber, () =>
            {
                count++;
                if (count == 10)
                {
                    called.Complete(count);
                    scheduledAction.Cancel();
                }
                else if (count > 10)
                {
                    failed.Complete(true);
                }
            });

            called.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();

            elapsed.Stop();

            failed.WaitUntilCompleted(200.Milliseconds()).ShouldBeFalse();

            Trace.WriteLine("Time Period: " + elapsed.ElapsedMilliseconds);
        }
Beispiel #16
0
        public void Adding_operations_to_a_fiber()
        {
            _count  = 10000;
            _values = new int[_count];
            Fiber fiber = new PoolFiber();

            int index     = 0;
            var completed = new Future <int>();

            var go = new Future <bool>();

            fiber.Add(() => { go.WaitUntilCompleted(10.Seconds()); });

            for (int i = 0; i < _count; i++)
            {
                int offset = i;
                fiber.Add(() =>
                {
                    _values[offset] = index++;

                    if (offset == _count - 1)
                    {
                        completed.Complete(offset);
                    }
                });
            }

            go.Complete(true);

            completed.WaitUntilCompleted(10.Seconds()).ShouldBeTrue();
        }
        public void Should_invoke_the_continuation()
        {
            var transport = MockRepository.GenerateStub <IMsmqTransport>();

            transport.Stub(x => x.Receive(null))
            .Callback(new Func <Func <Message, Action <Message> >, bool>(Forwarder));

            var address = MockRepository.GenerateMock <IMsmqEndpointAddress>();

            IEndpoint endpoint = new MsmqEndpoint(address, new XmlMessageSerializer(), transport, MockRepository.GenerateMock <IMsmqTransport>());

            var future = new Future <object>();

            endpoint.Receive(m =>
                             message =>
            {
                Assert.IsInstanceOf <SimpleMessage>(message);

                Assert.AreEqual(((SimpleMessage)message).Name, "Chris");

                future.Complete(message);
            });

            Assert.IsTrue(future.IsAvailable(), "Receive was not called");
        }
Beispiel #18
0
		public void Should_have_the_bits_without_the_message_first()
		{
			var engine = new DynamicRoutingEngine(new PoolFiber());
			var visualizer = new TraceRoutingEngineVisualizer();

			var received = new Future<A>();
			engine.Configure(x => x.Receive<A>(received.Complete));

			var block = new Future<int>();
			engine.Add(0, () =>
				{
					visualizer.Show(engine);
					block.Complete(0);
				});
			block.WaitUntilCompleted(2.Seconds());

			engine.Send(new A());
			received.WaitUntilCompleted(2.Seconds());

			engine.Send(new B());

			var receivedB = new Future<B>();
			engine.Configure(x => x.Receive<B>(receivedB.Complete));

			received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();
			receivedB.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();

			//engine.Receive<A, B>(x => { });

			visualizer.Show(engine);
		}
Beispiel #19
0
            protected override void OnExecute(Tangle <T> tangle, out NoneType result)
            {
                ThunkSignal.Complete();
                OpenSignal.Wait();

                result = NoneType.None;
            }
Beispiel #20
0
        public static Future <int> AsyncRead(this Stream stream, byte[] buffer, int offset, int count)
        {
#if XBOX
            return(Future.RunInThread(() => stream.Read(buffer, offset, count)));
#else
            var f = new Future <int>();
            try {
                stream.BeginRead(buffer, offset, count, (ar) => {
                    try {
                        int bytesRead;
                        lock (stream)
                            bytesRead = stream.EndRead(ar);
                        f.Complete(bytesRead);
                    } catch (FutureHandlerException) {
                        throw;
                    } catch (Exception ex) {
                        f.Fail(ex);
                    }
                }, stream);
            } catch (Exception ex) {
                f.Fail(ex);
            }
            return(f);
#endif
        }
Beispiel #21
0
        public void A_loopback_registry()
        {
            Address   = new Uri("loopback://localhost/");
            ReceivedA = new Future <A>();

            Registry = ActorRegistryFactory.New(x =>
            {
                x.Remote(r =>
                {
                    r.ListenTo(Address);
                });
            });

            ActorId = Guid.NewGuid();
            Actor   = AnonymousActor.New(inbox =>
            {
                inbox.Loop(loop =>
                {
                    loop.Receive <Message <A> >(message =>
                    {
                        ReceivedA.Complete(message.Body);

                        loop.Continue();
                    });
                });
            });

            Registry.Register(ActorId, Actor);
        }
        private void GivenSubscriptionsToAQueueInTwoRegions()
        {
            var primaryHandler = Substitute.For <IHandler <GenericMessage> >();

            primaryHandler.Handle(Arg.Any <GenericMessage>()).Returns(true);
            primaryHandler
            .When(x => x.Handle(Arg.Any <GenericMessage>()))
            .Do(x => _primaryHandler.Complete((GenericMessage)x.Args()[0]));

            _primaryBus = CreateMeABus
                          .InRegion(PrimaryRegion)
                          .WithSqsTopicSubscriber()
                          .IntoQueue("queuename")
                          .WithMessageHandler(primaryHandler);
            _primaryBus.StartListening();

            var secondaryHandler = Substitute.For <IHandler <GenericMessage> >();

            secondaryHandler.Handle(Arg.Any <GenericMessage>()).Returns(true);
            secondaryHandler
            .When(x => x.Handle(Arg.Any <GenericMessage>()))
            .Do(x => _secondaryHandler.Complete((GenericMessage)x.Args()[0]));

            _secondaryBus = CreateMeABus
                            .InRegion(SecondaryRegion)
                            .WithSqsTopicSubscriber()
                            .IntoQueue("queuename")
                            .WithMessageHandler(secondaryHandler);
            _secondaryBus.StartListening();
        }
Beispiel #23
0
 public Future<int> Read (byte[] buffer, int offset, int count) {
     var f = new Future<int>();
     if (!_Socket.Connected) {
         if (ThrowOnDisconnect)
             f.Fail(new SocketDisconnectedException());
         else
             f.Complete(0);
     } else {
         SocketError errorCode;
         if (_Socket.Available >= count) {
             try {
                 int bytesRead = _Socket.Receive(buffer, offset, count, SocketFlags.None, out errorCode);
                 if (ThrowOnDisconnect && (bytesRead == 0)) {
                     f.Fail(new SocketDisconnectedException());
                 } else {
                     f.Complete(bytesRead);
                 }
             } catch (Exception ex) {
                 f.Fail(ex);
             }
         } else {
             _Socket.BeginReceive(buffer, offset, count, SocketFlags.None, out errorCode, _ReadCallback, f);
         }
     }
     return f;
 }
        private void GivenSubscriptionsToAQueueInTwoRegions()
        {
            var primaryHandler = Substitute.For <IHandlerAsync <GenericMessage> >();

            primaryHandler.Handle(Arg.Any <GenericMessage>()).Returns(true);
            primaryHandler
            .When(x => x.Handle(Arg.Any <GenericMessage>()))
            .Do(async x => await _primaryHandler.Complete((GenericMessage)x.Args()[0]));

            _primaryBus = CreateMeABus
                          .InRegion(PrimaryRegion)
                          .WithSqsPointToPointSubscriber()
                          .IntoQueue(string.Empty)
                          .WithMessageHandler(primaryHandler);
            _primaryBus.StartListening();

            var secondaryHandler = Substitute.For <IHandlerAsync <GenericMessage> >();

            secondaryHandler.Handle(Arg.Any <GenericMessage>()).Returns(true);
            secondaryHandler
            .When(x => x.Handle(Arg.Any <GenericMessage>()))
            .Do(async x => await _secondaryHandler.Complete((GenericMessage)x.Args()[0]));

            _secondaryBus = CreateMeABus
                            .InRegion(SecondaryRegion)
                            .WithSqsPointToPointSubscriber()
                            .IntoQueue(string.Empty)
                            .WithMessageHandler(secondaryHandler);
            _secondaryBus.StartListening();
        }
Beispiel #25
0
        public void Should_support_the_username_password_for_a_host()
        {
            var inputAddress = new Uri("rabbitmq://localhost/mt/test_queue");
            var future       = new Future <IConsumeContext <A> >();

            using (IServiceBus bus = ServiceBusFactory.New(c =>
            {
                c.ReceiveFrom(inputAddress);
                c.UseRabbitMq(r =>
                {
                    r.ConfigureHost(inputAddress, h =>
                    {
                        h.SetUsername("testUser");
                        h.SetPassword("test");
                    });
                });

                c.Subscribe(s => s.Handler <A>((context, message) => future.Complete(context)));
            }))
            {
                bus.Publish(new A());

                Assert.IsTrue(future.WaitUntilCompleted(TimeSpan.FromSeconds(8)));
            }

            Assert.AreEqual(inputAddress.ToString(), future.Value.SourceAddress.ToString());
        }
Beispiel #26
0
        public void Setup()
        {
            _addCalled    = new Future <bool>();
            _removeCalled = new Future <bool>();

            _input = PipeSegment.Input(PipeSegment.End());

            _subscriberScope = _input.NewSubscriptionScope();
            _subscriberScope.Subscribe <SubscriberAdded>(x =>
            {
                if (x.MessageType == typeof(ClaimModified))
                {
                    _addCalled.Complete(true);
                }
            });
            _subscriberScope.Subscribe <SubscriberRemoved>(x =>
            {
                if (x.MessageType == typeof(ClaimModified))
                {
                    _removeCalled.Complete(true);
                }
            });

            using (ISubscriptionScope scope = _input.NewSubscriptionScope())
            {
                scope.Subscribe <ClaimModified>(x => { });
            }
        }
Beispiel #27
0
        public void FillingSendBufferCausesWriteToBlock()
        {
            byte[] buf = new byte[102400];

            StreamA.Write(buf, 0, buf.Length);

            var f = new Future <object>();

            ThreadPool.QueueUserWorkItem((_) => {
                try {
                    StreamA.Write(buf, 0, buf.Length);
                    f.Complete();
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            }, null);

            Thread.Sleep(3000);

            Assert.IsFalse(f.Completed, "Expected a full send buffer to make write operation block");

            A.Close();
            B.Close();
            StreamA.Dispose();
            StreamB.Dispose();

            GC.Collect();

            Thread.Sleep(1000);

            Assert.IsTrue(f.Completed);
            Assert.IsTrue(f.Failed);
        }
Beispiel #28
0
        public void Should_have_the_bits_without_the_message_first()
        {
            var engine     = new DynamicRoutingEngine(new PoolFiber());
            var visualizer = new TraceRoutingEngineVisualizer();

            var received = new Future <A>();

            engine.Configure(x => x.Receive <A>(received.Complete));

            var block = new Future <int>();

            engine.Add(0, () =>
            {
                visualizer.Show(engine);
                block.Complete(0);
            });
            block.WaitUntilCompleted(2.Seconds());

            engine.Send(new A());
            received.WaitUntilCompleted(2.Seconds());

            engine.Send(new B());

            var receivedB = new Future <B>();

            engine.Configure(x => x.Receive <B>(receivedB.Complete));

            received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();
            receivedB.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();

            //engine.Receive<A, B>(x => { });

            visualizer.Show(engine);
        }
Beispiel #29
0
            void _OnDecodeComplete(IFuture f)
            {
                if (Parent.IsDisposed)
                {
                    Result.Dispose();
                    return;
                }

                var e = f.Error;

                if (e != null)
                {
                    Buffer.Dispose();
                    Result.Fail(e);
                }
                else
                {
                    int numChars = (int)f.Result;

                    if (numChars > 0)
                    {
                        ProcessDecodedChars();
                    }
                    else
                    {
                        string resultString = Buffer.DisposeAndGetContents();
                        if (resultString.Length == 0)
                        {
                            resultString = null;
                        }

                        Result.Complete(resultString);
                    }
                }
            }
Beispiel #30
0
        private Future <int> DecodeMoreData()
        {
            var f        = new Future <int>();
            var readData = ReadMoreData();

            readData.RegisterOnComplete((_) => {
                if (IsDisposed)
                {
                    f.Dispose();
                    return;
                }

                var error = _.Error;
                if (error != null)
                {
                    f.Fail(error);
                    return;
                }

                var bytesRead = (int)_.Result;

                try {
                    DecodeBuffer(bytesRead);

                    f.Complete(_DecodedCharacterCount);
                } catch (FutureHandlerException) {
                    throw;
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            });
            return(f);
        }
        public void Should_be_fast()
        {
            Fiber fiber = new ThreadPoolFiber();

            const int limit = 5000000;

            var complete = new Future<int>();

            Channel<MsgStruct> channel = new ConsumerChannel<MsgStruct>(fiber, message =>
                {
                    if (message.Count == limit)
                        complete.Complete(limit);
                });

            using (var timer = new FunctionTimer("Throughput", x =>
                {
                    Trace.WriteLine("Time to execute: " + (int) x.ElapsedMilliseconds + "ms");

                    Trace.WriteLine("Per second throughput: " + (int) (limit/(x.ElapsedMilliseconds/1000)));
                }))
            {
                for (int i = 1; i <= limit; i++)
                {
                    channel.Send(new MsgStruct
                        {
                            Count = i,
                            Other = i*8,
                        });
                }

                timer.Mark();

                complete.WaitUntilCompleted(30.Seconds()).ShouldBeTrue();
            }
        }
        public void A_file_is_created()
        {
            _baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            _filename = "test2.dat";
            _path = Path.Combine(_baseDirectory, _filename);

            System.IO.File.Delete(_path);

            _listener = new Future<FileCreated>();

            _channel = new ChannelAdapter();
            FiberFactory fiberFactory = () => new SynchronousFiber();
            _scheduler = new TimerScheduler(fiberFactory());
            _producer = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, fiberFactory(),
                                                           20.Seconds());

            Thread.Sleep(5.Seconds());

            using (_channel.Connect(x => x.AddConsumerOf<FileCreated>().UsingConsumer(m => _listener.Complete(m))))
            {
                System.IO.File.Create(_path);

                _listener.WaitUntilCompleted(25.Seconds());
            }

            _producer.Dispose();
        }
Beispiel #33
0
        public void Complete_is_called_twice_with_the_same_object()
        {
            var obj1 = new object();

            Future.Complete(obj1);
            Future.Complete(obj1);
        }
Beispiel #34
0
 public void InvokesOnCompletesWhenCompleted () {
     var f = new Future<object>();
     object completeResult = null;
     f.RegisterOnComplete((_) => { completeResult = _.Error ?? _.Result; });
     f.Complete(5);
     Assert.AreEqual(5, completeResult);
 }
Beispiel #35
0
        public void Should_throw_an_exception()
        {
            var obj1 = new object();
            var obj2 = new object();

            Future.Complete(obj1);
            Assert.That(() => Future.Complete(obj2), Throws.TypeOf <InvalidOperationException>());
        }
Beispiel #36
0
        protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
        {
            base.ConfigureServiceBus(uri, configurator);

            _received = new Future<A>();

            configurator.Subscribe(x => { x.Handler<A>(msg => _received.Complete(msg)); });
        }
Beispiel #37
0
        protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
        {
            base.ConfigureServiceBus(uri, configurator);

            _received = new Future <A>();

            configurator.Subscribe(x => { x.Handler <A>(msg => _received.Complete(msg)); });
        }
Beispiel #38
0
        public Future <int> Read(byte[] buffer, int offset, int count)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException("SocketDataAdapter");
            }

            var f = new Future <int>();

            if (!_Socket.Connected)
            {
                if (ThrowOnDisconnect)
                {
                    f.Fail(new SocketDisconnectedException());
                }
                else
                {
                    f.Complete(0);
                }
            }
            else
            {
                SocketError errorCode;
                if (_Socket.Available >= count)
                {
                    try {
                        int bytesRead = _Socket.Receive(buffer, offset, count, SocketFlags.None, out errorCode);
                        if (ThrowOnDisconnect && (bytesRead == 0))
                        {
                            f.Fail(new SocketDisconnectedException());
                        }
                        else
                        {
                            f.Complete(bytesRead);
                        }
                    } catch (Exception ex) {
                        f.Fail(ex);
                    }
                }
                else
                {
                    _Socket.BeginReceive(buffer, offset, count, SocketFlags.None, out errorCode, _ReadCallback, f);
                }
            }
            return(f);
        }
		protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
		{
			base.ConfigureServiceBus(uri, configurator);

			_receivedB = new Future<B>();

			configurator.Subscribe(s => s.Handler<B>(message => _receivedB.Complete(message)));
		}
        protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
        {
            _received = new Future<A>();

            configurator.Subscribe(s => s.Handler<A>(message => _received.Complete(message)));
            configurator.UseControlBus();
            configurator.UseStomp();
        }
        protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
        {
            _received = new Future <A>();

            configurator.Subscribe(s => s.Handler <A>(message => _received.Complete(message)));
            configurator.UseControlBus();
            configurator.UseStomp();
        }
Beispiel #42
0
		public SomeActorInstance()
		{
			_fiber = new PoolFiber();
			_future = new Future<MyMessage>();

			MessageChannel = new ConsumerChannel<MyMessage>(_fiber, Consume);
			LambdaMessageChannel = new ConsumerChannel<MyMessage>(_fiber, message => _future.Complete(message));
		}
		public void Should_properly_wrap_the_channel_as_synchronized()
		{
			Assert.IsNull(SynchronizationContext.Current);

			var fiber = new PoolFiber();

			var input = new ChannelAdapter();

			var context = new TestSynchronizationContext();

			var future = new Future<TestMessage>();

			SynchronizationContext.SetSynchronizationContext(context);

			Assert.IsNotNull(SynchronizationContext.Current);

			using (input.Connect(x =>
				{
					x.AddConsumerOf<TestMessage>()
						.OnCurrentSynchronizationContext()
						.UsingConsumer(message =>
							{
								Trace.WriteLine("Received on Thread: " + Thread.CurrentThread.ManagedThreadId);

								Assert.IsNotNull(SynchronizationContext.Current);
								Assert.AreEqual(context, SynchronizationContext.Current);

								future.Complete(message);
							});
				}))
			{
				Trace.WriteLine("Subscribed on Thread: " + Thread.CurrentThread.ManagedThreadId);

				SynchronizationContext.SetSynchronizationContext(null);

				input.Flatten().Select(c => c.GetType()).ShouldEqual(new[]
					{
						typeof(ChannelAdapter),
						typeof(BroadcastChannel),
						typeof(TypedChannelAdapter<TestMessage>),
						typeof(SynchronizedChannel<TestMessage>),
						typeof(ConsumerChannel<TestMessage>),
					});

				fiber.Add(() =>
					{
						Trace.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId);
						Assert.IsNull(SynchronizationContext.Current);

						input.Send(new TestMessage());
					});

				Assert.IsNull(SynchronizationContext.Current);

				future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue();
			}
		}
Beispiel #44
0
        protected override void ConfigureLocalBus(ServiceBusConfigurator configurator)
        {
            base.ConfigureLocalBus(configurator);


            _received = new Future <A>();

            configurator.Subscribe(s => s.Handler <A>(message => _received.Complete(message)));
        }
        public void Should_properly_wrap_the_channel_as_synchronized()
        {
            Assert.IsNull(SynchronizationContext.Current);

            var fiber = new ThreadPoolFiber();

            var input = new ChannelAdapter();

            var context = new TestSynchronizationContext();

            var future = new Future <TestMessage>();

            SynchronizationContext.SetSynchronizationContext(context);

            Assert.IsNotNull(SynchronizationContext.Current);

            using (input.Connect(x =>
            {
                x.AddConsumerOf <TestMessage>()
                .OnCurrentSynchronizationContext()
                .UsingConsumer(message =>
                {
                    Trace.WriteLine("Received on Thread: " + Thread.CurrentThread.ManagedThreadId);

                    Assert.IsNotNull(SynchronizationContext.Current);
                    Assert.AreEqual(context, SynchronizationContext.Current);

                    future.Complete(message);
                });
            }))
            {
                Trace.WriteLine("Subscribed on Thread: " + Thread.CurrentThread.ManagedThreadId);

                SynchronizationContext.SetSynchronizationContext(null);

                input.Flatten().Select(c => c.GetType()).ShouldEqual(new[]
                {
                    typeof(ChannelAdapter),
                    typeof(BroadcastChannel),
                    typeof(TypedChannelAdapter <TestMessage>),
                    typeof(SynchronizedChannel <TestMessage>),
                    typeof(ConsumerChannel <TestMessage>),
                });

                fiber.Add(() =>
                {
                    Trace.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId);
                    Assert.IsNull(SynchronizationContext.Current);

                    input.Send(new TestMessage());
                });

                Assert.IsNull(SynchronizationContext.Current);

                future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue();
            }
        }
        protected override void ConfigureLocalBus(ServiceBusConfigurator configurator)
        {
            base.ConfigureLocalBus(configurator);


            _received = new Future<A>();

            configurator.Subscribe(s => s.Handler<A>(message => _received.Complete(message)));
        }
Beispiel #47
0
		public void A_reactive_query_is_observing_a_bus_message()
		{
			_observable = LocalBus.AsObservable<PingMessage>();

			_thatJustHappened = new Future<PingMessage>();
			_subscription = _observable.Subscribe(m => _thatJustHappened.Complete(m));

			LocalBus.Publish(new PingMessage());
		}
Beispiel #48
0
        public void A_reactive_query_is_observing_a_bus_message()
        {
            _observable = LocalBus.AsObservable <PingMessage>();

            _thatJustHappened = new Future <PingMessage>();
            _subscription     = _observable.Subscribe(m => _thatJustHappened.Complete(m));

            LocalBus.Publish(new PingMessage());
        }
Beispiel #49
0
 public void Wait()
 {
     lock (SyncObject)
     {
         foreach (TP.Future Future in Futures)
         {
             Future.Complete();
         }
     }
 }
        public void A_message_is_published()
        {
            _received = new Future<A>();
            LocalBus.SubscribeHandler<A>(message => _received.Complete(message));

            LocalBus.Publish(new A
                                 {
                                     StringA = "ValueA",
                                 });
        }
Beispiel #51
0
        public void Should_not_pass_unwanted_types_through_the_filter()
        {
            var received = new Future<bool>();

            Pipe consumer = PipeSegment.Consumer<SubClass>(x => received.Complete(true));
            Pipe filter = PipeSegment.Filter<object>(consumer);

            filter.Send(new BaseClass());

            received.WaitUntilCompleted(TimeSpan.Zero).ShouldBeFalse();
        }
Beispiel #52
0
        public void Should_pass_derived_types_through_the_filter()
        {
            var received = new Future<bool>();

            Pipe consumer = PipeSegment.Consumer<BaseClass>(x => received.Complete(true));
            Pipe filter = PipeSegment.Filter<object>(consumer);

            filter.Send(new SubClass());

            received.IsAvailable(TimeSpan.Zero).ShouldBeTrue();
        }
        public void Should_not_stall_the_scheduler()
        {
            Fiber fiber = new ThreadPoolFiber();
            Scheduler scheduler = new TimerScheduler(new ThreadPoolFiber());

            var called = new Future<bool>();

            scheduler.Schedule(200.Milliseconds(), fiber, () => { throw new InvalidOperationException("Bugger!"); });
            scheduler.Schedule(400.Milliseconds(), fiber, () => called.Complete(true));

            called.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
        }
Beispiel #54
0
        public void Should_not_stall_the_scheduler()
        {
            ActionQueue queue = new ThreadPoolActionQueue();
            ActionScheduler scheduler = new TimerActionScheduler(new ThreadPoolActionQueue());

            var called = new Future<bool>();

            scheduler.Schedule(200.Milliseconds(), queue, () => { throw new InvalidOperationException("Bugger!"); });
            scheduler.Schedule(400.Milliseconds(), queue, () => called.Complete(true));

            called.IsAvailable(1.Seconds()).ShouldBeTrue();
        }
Beispiel #55
0
        public void An_exit_is_sent_to_an_actor()
        {
            _receivedA = new Future<A>();

            _actor = AnonymousActor.New(inbox =>
            {
                inbox.Receive<A>(message =>
                {
                    _receivedA.Complete(message);
                });
            });
        }
        public void A_message_is_published_one_the_local_bus()
        {
            _received = new Future<A>();
            RemoteBus.SubscribeHandler<A>(message => _received.Complete(message));

            Thread.Sleep(3.Seconds());

            LocalBus.Publish(new A
                                 {
                                     StringA = "ValueA",
                                 });
        }
        public void Should_wait_until_the_appropriate_time_for_the_action_to_execute()
        {
            Fiber fiber = new ThreadPoolFiber();
            Scheduler scheduler = new TimerScheduler(new SynchronousFiber());

            var called = new Future<bool>();

            scheduler.Schedule(100.Milliseconds(), fiber, () => called.Complete(true));

            called.IsCompleted.ShouldBeFalse();

            called.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
        }
        public void Should_not_run_any_pending_actions()
        {
            Fiber fiber = new ThreadPoolFiber();
            Scheduler scheduler = new TimerScheduler(new ThreadPoolFiber());

            var called = new Future<bool>();

            scheduler.Schedule(1.Seconds(), fiber, () => called.Complete(true));

            scheduler.Stop();

            called.WaitUntilCompleted(2.Seconds()).ShouldBeFalse();
        }
		protected override void ConfigureRemoteBus(ServiceBusConfigurator configurator)
		{
			base.ConfigureRemoteBus(configurator);

			_baseMessage = new Future<BaseMessage>();
			_message = new Future<Message>();

			configurator.Subscribe(cf =>
				{
					cf.Handler<BaseMessage>(message => _baseMessage.Complete(message));
					cf.Handler<Message>(message => _message.Complete(message));
				});
		}
Beispiel #60
-1
		public void Should_run_the_action_immediately()
		{
			Fiber fiber = new PoolFiber();
			Scheduler scheduler = new TimerScheduler(new SynchronousFiber());

			var called = new Future<bool>();

			scheduler.Schedule(TimeSpan.Zero, fiber, () => called.Complete(true));

			called.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
		}