public void HandlerThrowsExceptionPublishSubscribeWithExecutor()
        {
            services.AddSingleton <IDestinationResolver <IMessageChannel>, DefaultMessageChannelDestinationResolver>();
            services.AddSingleton <IMessageBuilderFactory, DefaultMessageBuilderFactory>();
            services.AddSingleton <IMessageChannel>((p) => new DirectChannel(p.GetService <IApplicationContext>(), "errorChannel"));
            var provider = services.BuildServiceProvider();

            var defaultErrorChannel = provider.GetService <IMessageChannel>() as DirectChannel;
            var channel             = new PublishSubscribeChannel(provider.GetService <IApplicationContext>(), TaskScheduler.Default);
            var resultHandler       = new ResultHandler(latch);
            var throwingHandler     = new ThrowMessageExceptionHandler();

            channel.Subscribe(throwingHandler);
            defaultErrorChannel.Subscribe(resultHandler);
            var message = IntegrationMessageBuilder.WithPayload("test").Build();

            channel.Send(message);
            Assert.True(latch.Wait(10000));
            var errorMessage = resultHandler.LastMessage;

            Assert.IsType <MessagingException>(errorMessage.Payload);
            var exceptionPayload = (MessagingException)errorMessage.Payload;

            Assert.IsType <NotSupportedException>(exceptionPayload.InnerException);
            Assert.Same(message, exceptionPayload.FailedMessage);
            Assert.NotEqual(Thread.CurrentThread.ManagedThreadId, resultHandler.LastThread.ManagedThreadId);
        }
示例#2
0
        public void CreatePublishSubscriberChannel(PublishSubscribeChannel publishSubscribeChannel, IChannelManager channelmanager)
        {
            if (publishSubscribeChannel.ConnectionStringExtractorType != null)
            {
                var extractorconnectionstring = _factory.Create <IValueSettingFinder>(publishSubscribeChannel.ConnectionStringExtractorType);

                var toconnectionextractor = publishSubscribeChannel.ToConnectionStringExtractor as Func <IValueSettingFinder, string>;

                if (toconnectionextractor != null)
                {
                    try
                    {
                        var connectionstring = toconnectionextractor(extractorconnectionstring);

                        var created = channelmanager.CreateIfNotExistPublishSubscribeChannel(connectionstring, publishSubscribeChannel.Path);

                        if (created)
                        {
                            Console.WriteLine($"Created {publishSubscribeChannel.Path} publish subscriber channel");
                        }
                        else
                        {
                            Console.WriteLine($"Publish subscriber channel {publishSubscribeChannel.Path} already exists");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {publishSubscribeChannel.Path} publish subscriber channel: {ex}");
                    }
                }
            }
        }
示例#3
0
        public async Task ValidateSuccessfulErrorFlowDoesNotThrowErrors()
        {
            var provider   = services.BuildServiceProvider();
            var outChannel = new DirectChannel(provider);
            var handler    = new ExceptionHandler();

            outChannel.Subscribe(handler);
            var errorChannel = new PublishSubscribeChannel(provider);
            var errorService = new SuccessfulErrorService();
            var errorHandler = new ServiceActivatingHandler(provider, errorService);

            errorChannel.Subscribe(errorHandler);

            var mps = new TestMessageProducerSupportEndpoint(provider);

            mps.OutputChannel = outChannel;
            mps.ErrorChannel  = errorChannel;

            await mps.Start();

            var message = new GenericMessage("hello");

            mps.SendMessage(message);
            Assert.IsType <ErrorMessage>(errorService.LastMessage);
            Assert.IsType <MessageDeliveryException>(errorService.LastMessage.Payload);
            var exception = (MessageDeliveryException)errorService.LastMessage.Payload;

            Assert.Equal(message, exception.FailedMessage);
        }
示例#4
0
文件: Program.cs 项目: winhu/Steeltoe
    public void PublishSubscribeChannel_Send_10_000_000_TwoHandlers()
    {
        var services = new ServiceCollection();

        services.AddSingleton <IIntegrationServices, IntegrationServices>();
        var provider = services.BuildServiceProvider();
        var channel  = new PublishSubscribeChannel(provider);
        var handler1 = new CounterHandler();
        var handler2 = new CounterHandler();

        channel.Subscribe(handler1);
        channel.Subscribe(handler2);
        var message = new GenericMessage("test");

        for (var i = 0; i < 10_000_000; i++)
        {
            channel.Send(message);
        }
        if (handler1.Count != 10_000_000)
        {
            throw new InvalidOperationException("Handler count1 invalid");
        }
        if (handler2.Count != 10_000_000)
        {
            throw new InvalidOperationException("Handler count2 invalid");
        }
    }
 private static void SimpleMessageHandlerEventing()
 {
     PublishSubscribeChannel channel = new PublishSubscribeChannel();
     channel.Subscribe(new SimpleMessageHandler("one"));
     channel.Subscribe(new SimpleMessageHandler("two"));
     IMessage message = MessageBuilder.WithPayload("foo").Build();
     channel.Send(message);
 }
        public void AddSubscriberType_Without_WithTimeToExpire_WithFakeProvider()
        {
            var subscriberInfo = new PublishSubscribeChannel<User>(new StubIStoreProvider<User>())
                .AddSubscriberType(typeof(TestSubscriberZZZ<User>));
            var pubsub = subscriberInfo.WithTimeToExpire(new TimeSpan(0, 1, 0));
            Assert.IsInstanceOfType(pubsub, typeof(PublishSubscribeChannel<User>));

            Assert.IsInstanceOfType(pubsub.GetSubscriptions()[0], typeof(ISubscriber<User>));
        }
示例#7
0
        public void applySequenceEnabled()
        {
            IApplicationContext     ctx     = TestUtils.GetContext(@"Config\PublishSubscribeChannelParserTests.xml");
            PublishSubscribeChannel channel = (PublishSubscribeChannel)ctx.GetObject("channelWithApplySequenceEnabled");

            BroadcastingDispatcher dispatcher = TestUtils.GetPropertyValue <BroadcastingDispatcher>(channel, "Dispatcher");

            Assert.IsTrue(TestUtils.GetFieldValue <bool>(dispatcher, "_applySequence"));
        }
示例#8
0
        public void channelWithErrorHandler()
        {
            IApplicationContext     ctx     = TestUtils.GetContext(@"Config\PublishSubscribeChannelParserTests.xml");
            PublishSubscribeChannel channel = (PublishSubscribeChannel)ctx.GetObject("channelWithErrorHandler");

            IErrorHandler errorHandler = TestUtils.GetFieldValue <IErrorHandler>(channel, "_errorHandler");

            Assert.IsNotNull(errorHandler);
            Assert.That(errorHandler, Is.EqualTo(ctx.GetObject("testErrorHandler")));
        }
示例#9
0
        private static void SimpleMessageHandlerEventing()
        {
            PublishSubscribeChannel channel = new PublishSubscribeChannel();

            channel.Subscribe(new SimpleMessageHandler("one"));
            channel.Subscribe(new SimpleMessageHandler("two"));
            IMessage message = MessageBuilder.WithPayload("foo").Build();

            channel.Send(message);
        }
 public void Get_1_Subscribers_WithFakeProvider()
 {
     var pubsub = new PublishSubscribeChannel<User>(new StubIStoreProvider<User>())
      .AddSubscriberType(typeof(TestSubscriberZZZ<User>)).WithTimeToExpire(new TimeSpan(0, 1, 0));
     var Subscribers = pubsub.GetSubscriptions();
     Assert.IsInstanceOfType(Subscribers[0], typeof(TestSubscriberZZZ<User>));
     Assert.AreEqual(Subscribers[0].Name, "TestSubscriberZZZ`1");
     Assert.AreEqual(Subscribers[0].TimeToExpire, new TimeSpan(0, 1, 0));
     Assert.IsTrue(Subscribers.Count == 1);
 }
示例#11
0
        public void CreatePublishSubscriberChannel(PublishSubscribeChannel channel, IChannelManager manager, StringBuilder errors)
        {
            if (channel.ConnectionStringExtractorType != null)
            {
                var finder = _factory.Create <IValueSettingFinder>(channel.ConnectionStringExtractorType);

                var extractor = channel.ConnectionStringExtractor as Func <IValueSettingFinder, string>;

                channel.ConnectionString = extractor?.Invoke(finder);

                if (string.IsNullOrWhiteSpace(channel.ConnectionString))
                {
                    var error = $"Empty connection string, publish subscriber channel {channel.Path}";

                    errors.AppendLine(error);

                    _logger.Log(error);

                    return;
                }

                if (string.IsNullOrWhiteSpace(channel.Path))
                {
                    var error = $"Empty path, publish subscriber channel {channel.Path}";

                    errors.AppendLine(error);

                    _logger.Log(error);

                    return;
                }

                try
                {
                    var created = manager.CreateIfNotExistPublishSubscribeChannel(channel.ConnectionString, channel.Path);

                    if (created)
                    {
                        _logger.Log($"Created {channel.Path} publish subscriber channel");
                    }
                    else
                    {
                        _logger.Log($"Publish subscriber channel {channel.Path} already exists");
                    }
                }
                catch (Exception ex)
                {
                    var error = $"Exception {channel.Path} publish subscriber channel: {ex}";

                    errors.AppendLine(error);

                    _logger.Log(error);
                }
            }
        }
示例#12
0
        public void DefaultChannel()
        {
            IApplicationContext     ctx     = TestUtils.GetContext(@"Config\PublishSubscribeChannelParserTests.xml");
            PublishSubscribeChannel channel = (PublishSubscribeChannel)ctx.GetObject("defaultChannel");

            BroadcastingDispatcher dispatcher = TestUtils.GetPropertyValue <BroadcastingDispatcher>(channel, "Dispatcher");
            IExecutor taskExecutor            = TestUtils.GetPropertyValue <IExecutor>(dispatcher, "TaskExecutor");

            Assert.IsNull(taskExecutor);
            Assert.IsFalse(TestUtils.GetFieldValue <bool>(dispatcher, "_applySequence"));
        }
        public void HandlerThrowsExceptionPublishSubscribeWithoutScheduler()
        {
            var provider = services.BuildServiceProvider();
            var channel  = new PublishSubscribeChannel(provider.GetService <IApplicationContext>());
            var handler  = new ThrowingHandler();

            channel.Subscribe(handler);
            var message = IntegrationMessageBuilder.WithPayload("test").Build();

            Assert.Throws <MessageDeliveryException>(() => channel.Send(message));
        }
示例#14
0
        public void Should_return_false_if_there_are_no_subscribers()
        {
            Fiber fiber = new SynchronousFiber();

            Channel<UserUpdate> channel = new PublishSubscribeChannel<UserUpdate>(fiber, new Channel<UserUpdate>[] {});

            var update = new UserUpdate();

            channel.Send(update);

            // exception here? or just ignore
        }
示例#15
0
        public void channelWithTaskExecutor()
        {
            IApplicationContext     ctx     = TestUtils.GetContext(@"Config\PublishSubscribeChannelParserTests.xml");
            PublishSubscribeChannel channel = (PublishSubscribeChannel)ctx.GetObject("channelWithTaskExecutor");

            IExecutor executor = TestUtils.GetPropertyValue <IExecutor>(channel, "Dispatcher.TaskExecutor");

            Assert.IsNotNull(executor);
            Assert.That(executor.GetType(), Is.EqualTo(typeof(ErrorHandlingTaskExecutor)));
            IExecutor innerExecutor = TestUtils.GetFieldValue <IExecutor>(executor, "_taskExecutor");

            Assert.That(innerExecutor, Is.EqualTo(ctx.GetObject("pool")));
        }
        public void HandlerThrowsExceptionPublishSubscribeWithoutScheduler()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IIntegrationServices, IntegrationServices>();
            var provider = services.BuildServiceProvider();
            var channel  = new PublishSubscribeChannel(provider);
            var handler  = new ThrowingHandler();

            channel.Subscribe(handler);
            var message = MessageBuilder.WithPayload("test").Build();

            Assert.Throws <MessageDeliveryException>(() => channel.Send(message));
        }
        public void CreateUserUsingConstructorParametersTest()
        {
            TestHelper.SetUpCleanTestQueue();

            var queueProvider = new MsmqStoreProvider<User>() as IStoreProvider<User>;
            var PubSubChannel = new PublishSubscribeChannel<User>(queueProvider) as IPublishSubscribeChannel<User>;
            UserManagerServiceAdaptor target = new UserManagerServiceAdaptor(queueProvider, PubSubChannel);
            User umToUpdate = new User();
            umToUpdate.FirstName = "X";
            umToUpdate.LastName = "LastName";
            umToUpdate.UserName = "******";
            umToUpdate.UserName = "******";
            target.Create(umToUpdate);
        }
示例#18
0
        public void UsingPublishSubscribeChannels()
        {
            PublishSubscribeChannel channel = new PublishSubscribeChannel();

            channel.Subscribe(new SimpleMessageHandler("Handler-1"));
            channel.Subscribe(new SimpleMessageHandler("Handler-2"));

            IMessage diningMessage =
                MessageBuilder.WithPayload("Hello World").Build();

            channel.Send(diningMessage);
            channel.Send(diningMessage);
            channel.Send(diningMessage);
        }
        public async ValueTask TestSendAsync()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IIntegrationServices, IntegrationServices>();
            var provider = services.BuildServiceProvider();
            var handler  = new CounterHandler();
            var channel  = new PublishSubscribeChannel(provider);

            channel.Subscribe(handler);
            var message = new GenericMessage("test");

            Assert.True(await channel.SendAsync(message));
            Assert.Equal(1, handler.Count);
        }
        public void TestSend()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IIntegrationServices, IntegrationServices>();
            var provider = services.BuildServiceProvider();
            var handler  = new CounterHandler();
            var channel  = new PublishSubscribeChannel(provider.GetService <IApplicationContext>());

            channel.Subscribe(handler);
            var message = Message.Create("test");

            Assert.True(channel.Send(message));
            Assert.Equal(1, handler.Count);
        }
        public void CreateUserUsingDependencyInjectionTest()
        {
            TestHelper.SetUpCleanTestQueue();

            var queueProvider = new MsmqStoreProvider<User>() as IStoreProvider<User>;
            var PubSubChannel = new PublishSubscribeChannel<User>(queueProvider) as IPublishSubscribeChannel<User>;
            PubSubChannel.AddSubscriberType(typeof(TestSubscriberZZZ<User>));
            UserManagerServiceAdaptor target = new UserManagerServiceAdaptor(queueProvider, PubSubChannel);
            User umToUpdate = new User();
            umToUpdate.FirstName = "X";
            umToUpdate.LastName = "LastName";
            umToUpdate.UserName = "******";

            target.Create(umToUpdate);
            //need to assert something
        }
示例#22
0
        public void Should_filter_out_unwanted_messages()
        {
            var update = new UserUpdate {LastActivity = DateTime.Now - 5.Minutes()};

            Fiber fiber = new SynchronousFiber();

            var future = new Future<UserUpdate>();

            var filter = new FilterChannel<UserUpdate>(fiber, future, x => x.LastActivity > DateTime.Now);

            Channel<UserUpdate> channel = new PublishSubscribeChannel<UserUpdate>(fiber, new[] {filter});

            channel.Send(update);

            Assert.IsFalse(future.WaitUntilCompleted(1.Seconds()));
        }
示例#23
0
        public void RegisterPublishSubscriberChannel <TExtractorConectionString>(string path, Func <IValueSettingFinder, string> connectionstringextractor)
            where TExtractorConectionString : IValueSettingFinder
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (connectionstringextractor == null)
            {
                throw new ArgumentNullException(nameof(connectionstringextractor));
            }
            var channel = new PublishSubscribeChannel(path)
            {
                ConnectionStringExtractorType = typeof(TExtractorConectionString),
                ToConnectionStringExtractor   = connectionstringextractor
            };

            _publishsubscriberchannels.Add(channel);
        }
示例#24
0
        public void Should_schedule_events()
        {
            var update = new UserUpdate {LastActivity = DateTime.Now - 5.Minutes()};

            Fiber fiber = new SynchronousFiber();

            var future = new Future<UserUpdate>();

            Channel<UserUpdate> channel = new PublishSubscribeChannel<UserUpdate>(fiber, new Channel<UserUpdate>[] {future});

            var scheduler = new TimerFiberScheduler(fiber);

            scheduler.Schedule(1000, fiber, () => channel.Send(update));

            Thread.Sleep(500);

            Assert.IsFalse(future.WaitUntilCompleted(0.Seconds()));

            Assert.IsTrue(future.WaitUntilCompleted(1.Seconds()));
        }
        public async ValueTask TestSendAsyncOneHandler_10_000_000()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IIntegrationServices, IntegrationServices>();
            var provider = services.BuildServiceProvider();
            var handler  = new CounterHandler();
            var channel  = new PublishSubscribeChannel(provider.GetService <IApplicationContext>());

            channel.Subscribe(handler);
            var message = Message.Create("test");

            Assert.True(await channel.SendAsync(message));
            for (var i = 0; i < 10000000; i++)
            {
                await channel.SendAsync(message);
            }

            Assert.Equal(10000001, handler.Count);
        }
示例#26
0
        public async Task ValidateExceptionIfSendToErrorChannelFails()
        {
            var provider   = services.BuildServiceProvider();
            var outChannel = new DirectChannel(provider);
            var handler    = new ExceptionHandler();

            outChannel.Subscribe(handler);
            var errorChannel = new PublishSubscribeChannel(provider);

            errorChannel.Subscribe(handler);

            var mps = new TestMessageProducerSupportEndpoint(provider);

            mps.OutputChannel = outChannel;
            mps.ErrorChannel  = errorChannel;

            await mps.Start();

            Assert.Throws <MessageDeliveryException>(() => mps.SendMessage(new GenericMessage("hello")));
        }
        public void TestSendOneHandler_10_000_000()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IIntegrationServices, IntegrationServices>();
            var provider = services.BuildServiceProvider();
            var handler  = new CounterHandler();
            var channel  = new PublishSubscribeChannel(provider);

            channel.Subscribe(handler);
            var message = new GenericMessage("test");

            Assert.True(channel.Send(message));
            for (var i = 0; i < 10000000; i++)
            {
                channel.Send(message);
            }

            Assert.Equal(10000001, handler.Count);
        }
示例#28
0
        public void RegisterPublishSubscriberChannel(string path, string connectionstring)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (string.IsNullOrWhiteSpace(connectionstring))
            {
                throw new ArgumentNullException(nameof(connectionstring));
            }

            Func <IValueSettingFinder, string> extractor = x => connectionstring;

            var channel = new PublishSubscribeChannel(path)
            {
                ConnectionStringExtractorType = typeof(NullValueSettingFinder),
                ConnectionStringExtractor     = extractor
            };

            _publishsubscriberchannels.Add(channel);
        }
示例#29
0
    public void PublishSubscribeChannel_Send_10_000_000_SingleHandler()
    {
        var services = new ServiceCollection();

        services.AddSingleton <IIntegrationServices, IntegrationServices>();
        var provider = services.BuildServiceProvider();
        var channel  = new PublishSubscribeChannel(provider.GetService <IApplicationContext>());
        var handler  = new CounterHandler();

        channel.Subscribe(handler);
        var message = Message.Create("test");

        channel.Send(message);
        for (var i = 0; i < 10_000_000; i++)
        {
            channel.Send(message);
        }
        if (handler.Count != 10_000_000 + 1)
        {
            throw new InvalidOperationException("Handler count invalid");
        }
    }
示例#30
0
        private ISubscribableChannel ProvisionDestination(string name, bool pubSub)
        {
            var destinationName = name + ".destination";

            _provisionedDestinations.TryGetValue(destinationName, out var destination);
            if (destination == null)
            {
                if (pubSub)
                {
                    destination = new PublishSubscribeChannel(_context);
                }
                else
                {
                    destination = new DirectChannel(_context);
                }

                ((AbstractMessageChannel)destination).ServiceName = destinationName;
                _provisionedDestinations.Add(destinationName, destination);
            }

            return(destination);
        }
        public async ValueTask TestSendAsyncTwoHandler_10_000_000()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IIntegrationServices, IntegrationServices>();
            var provider = services.BuildServiceProvider();
            var handler1 = new CounterHandler();
            var handler2 = new CounterHandler();
            var channel  = new PublishSubscribeChannel(provider);

            channel.Subscribe(handler1);
            channel.Subscribe(handler2);
            var message = new GenericMessage("test");

            for (var i = 0; i < 10000000; i++)
            {
                await channel.SendAsync(message);
            }

            Assert.Equal(10000000, handler1.Count);
            Assert.Equal(10000000, handler2.Count);
        }
        private ISubscribableChannel RegisterErrorInfrastructure(IProducerDestination destination)
        {
            var errorChannelName = GetErrorsBaseName(destination);
            ISubscribableChannel errorChannel;
            var errorChannelObject = _destinationRegistry.Lookup(errorChannelName);

            if (errorChannelObject != null)
            {
                if (!(errorChannelObject is ISubscribableChannel))
                {
                    throw new InvalidOperationException("Error channel '" + errorChannelName + "' must be a ISubscribableChannel");
                }

                errorChannel = (ISubscribableChannel)errorChannelObject;
            }
            else
            {
                errorChannel = new PublishSubscribeChannel(ServiceProvider);
                _destinationRegistry.Register(errorChannelName, errorChannel);
            }

            var defaultErrorChannel = (IMessageChannel)_destinationRegistry.Lookup(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);

            if (defaultErrorChannel != null)
            {
                var errorBridge = new BridgeHandler(ServiceProvider)
                {
                    OutputChannel = defaultErrorChannel
                };
                errorChannel.Subscribe(errorBridge);
                var errorBridgeHandlerName = GetErrorBridgeName(destination);
                _destinationRegistry.Register(errorBridgeHandlerName, errorBridge);
            }

            return(errorChannel);
        }
        public void HandleMessageForFirstTime_ExceptionThrownMessageTest_WithFakeStoreProvider()
        {
            TestUtils.TestHelper.Subscriber1Ran = new AutoResetEvent(false);
            TestUtils.TestHelper.Subscriber2Ran = new AutoResetEvent(false);
            TestUtils.TestHelper.Subscriber3Ran = new AutoResetEvent(false);
            TestUtils.TestHelper.UpdateMessageStoreEvent = new AutoResetEvent(false);
            TestUtils.TestHelper.SubscriberGroupCompletedEvent = new AutoResetEvent(false);

            var m = new Message { Name = "MyMessage" };

            var messagePacket = TestUtils.TestHelper.BuildAMessage<Message>(m)
                .WithSubscriberMetadataFor(typeof(TestUtils.SpeedySubscriber<Message>), false, false)
                .WithSubscriberMetadataFor(typeof(TestUtils.SpeedySubscriberGuaranteedExceptions<Message>), false, false).GetMessage();

            List<MessagePacket<Message>> outputPostProcessMP = new List<MessagePacket<Message>>();
            string outputMessageId = string.Empty;
            DateTime timelastupdateCalled = default(DateTime);
            DateTime timeGroupCompletedCalled = default(DateTime);

            var MessagePubSubChannel = new PublishSubscribeChannel<Message>();
            var stubStoreProvider = new StubIStoreProvider<Message>
            {
                UpdateMessageStoreMessagePacketOfT0 = UpdatedMessagepacket =>
                {
                    outputPostProcessMP.Add(UpdatedMessagepacket);
                    timelastupdateCalled = DateTime.Now;
                    TestUtils.TestHelper.UpdateMessageStoreEvent.Set();
                    return;
                },
                SubscriberGroupCompletedForMessageString = messageId =>
                {
                    Assert.IsTrue(messagePacket.MessageId.ToString() == messageId);
                    timeGroupCompletedCalled = DateTime.Now;
                    TestUtils.TestHelper.SubscriberGroupCompletedEvent.Set();
                    return true;
                },
            };

            MessagePubSubChannel.StorageProvider = stubStoreProvider;

            MessagePubSubChannel.AddSubscriberType(typeof(TestUtils.SpeedySubscriberGuaranteedExceptions<Message>)).WithTimeToExpire(new TimeSpan(0, 0, 1, 1))
                .AddSubscriberType(typeof(TestUtils.SpeedySubscriber<Message>)).WithTimeToExpire(new TimeSpan(0, 0, 1, 1));

            MessagePubSubChannel.HandleMessageForFirstTime(messagePacket, messagePacket.MessageId.ToString());

            TestUtils.TestHelper.Subscriber1Ran.WaitOne();
            TestUtils.TestHelper.Subscriber3Ran.WaitOne();
            TestUtils.TestHelper.UpdateMessageStoreEvent.WaitOne();
            TestUtils.TestHelper.SubscriberGroupCompletedEvent.WaitOne();

            foreach (var item in outputPostProcessMP)
            {
                Assert.IsTrue(item.MessageId == messagePacket.MessageId);
                Assert.IsTrue(item.SubscriberMetadataList.Count == 1);
                if (item.SubscriberMetadataList[0].Name.Contains("SpeedySubscriberGuaranteedExceptions"))
                {
                    Assert.IsTrue(item.SubscriberMetadataList[0].FailedOrTimedOut == true);
                }
                else
                {
                    Assert.IsTrue(item.SubscriberMetadataList[0].FailedOrTimedOut == false);
                }
            }
            Trace.WriteLine("timelastupdateCalled: " + timelastupdateCalled.TimeOfDay);
            Trace.WriteLine("timeGroupCompletedCa: " + timeGroupCompletedCalled.TimeOfDay);
            Assert.IsTrue(DateTime.Compare(timelastupdateCalled, timeGroupCompletedCalled) < 0 || DateTime.Compare(timelastupdateCalled, timeGroupCompletedCalled) == 0);
        }
 public void PublishSubscribeChannelConstructor_Add3Subscribers_WithFakeProvider()
 {
     var pubsub = new PublishSubscribeChannel<User>(new StubIStoreProvider<User>())
         .AddSubscriberType(typeof(TestSubscriberZZZ<User>)).WithTimeToExpire(new TimeSpan(0,1,0))
         .AddSubscriberType(typeof(TestSubscriber2<User>)).WithTimeToExpire(new TimeSpan(0, 1, 0))
         .AddSubscriberType(typeof(TestSubscriber3<User>)).WithTimeToExpire(new TimeSpan(0, 1, 0));
     Assert.AreEqual(3, pubsub.GetSubscriptions().Count);
     Assert.IsInstanceOfType(pubsub.GetSubscriptions()[0], typeof(ISubscriber<User>));
     Assert.IsInstanceOfType(pubsub.GetSubscriptions()[1], typeof(ISubscriber<User>));
     Assert.IsInstanceOfType(pubsub.GetSubscriptions()[2], typeof(TestSubscriber3<User>));
 }
        public void HandleMessageForFirstTime_MessageTest_WithFakeStoreProvider()
        {
            TestUtils.TestHelper.Subscriber1Ran = new AutoResetEvent(false);
            TestUtils.TestHelper.Subscriber2Ran = new AutoResetEvent(false);
            TestUtils.TestHelper.Subscriber3Ran = new AutoResetEvent(false);
            TestUtils.TestHelper.UpdateMessageStoreEvent = new AutoResetEvent(false);
            TestUtils.TestHelper.SubscriberGroupCompletedEvent = new AutoResetEvent(false);

            var m = new Message { Name = "MyMessage"};

            var messagePacket = TestUtils.TestHelper.BuildAMessage<Message>(m)
                .WithSubscriberMetadataFor(typeof(TestUtils.SpeedySubscriber<Message>), false, false)
                .WithSubscriberMetadataFor(typeof(TestUtils.SpeedySubscriber2<Message>), false, false).GetMessage();

            MessagePacket<Message> outputPostProcessMP = default(MessagePacket<Message>);
            string outputMessageId = string.Empty;
            DateTime timelastupdateCalled = default(DateTime);
            DateTime timeGroupCompletedCalled = default(DateTime);

            var MessagePubSubChannel = new PublishSubscribeChannel<Message>();
            var stubStoreProvider = new StubIStoreProvider<Message>
            {
                UpdateMessageStoreMessagePacketOfT0 = UpdatedMessagepacket =>
                {
                    outputPostProcessMP = UpdatedMessagepacket;
                    timelastupdateCalled = DateTime.Now;
                    TestUtils.TestHelper.UpdateMessageStoreEvent.Set();
                    return;
                },
                SubscriberGroupCompletedForMessageString = messageId =>
                {
                    Assert.IsTrue(messagePacket.MessageId.ToString() == messageId);
                    timeGroupCompletedCalled = DateTime.Now;
                    TestUtils.TestHelper.SubscriberGroupCompletedEvent.Set();
                    return true;
                }
            };
            MessagePubSubChannel.StorageProvider = stubStoreProvider;

            MessagePubSubChannel.AddSubscriberType(typeof(TestUtils.SpeedySubscriber2<Message>)).WithTimeToExpire(new TimeSpan(0, 0, 1, 1))
                .AddSubscriberType(typeof(TestUtils.SpeedySubscriber<Message>)).WithTimeToExpire(new TimeSpan(0, 0, 1, 1));

            MessagePubSubChannel.HandleMessageForFirstTime(messagePacket, messagePacket.MessageId.ToString());

            TestUtils.TestHelper.Subscriber1Ran.WaitOne();
            TestUtils.TestHelper.Subscriber2Ran.WaitOne();
            TestUtils.TestHelper.UpdateMessageStoreEvent.WaitOne();
            TestUtils.TestHelper.SubscriberGroupCompletedEvent.WaitOne();

            Assert.IsTrue(outputPostProcessMP.MessageId == messagePacket.MessageId);
            Assert.IsTrue(outputPostProcessMP.SubscriberMetadataList.Count == 1);
            Assert.IsTrue(outputPostProcessMP.SubscriberMetadataList[0].FailedOrTimedOut == false);
            Assert.IsTrue(DateTime.Compare(timelastupdateCalled, timeGroupCompletedCalled) < 0 || DateTime.Compare(timelastupdateCalled, timeGroupCompletedCalled) == 0);
        }
        public void UsingPublishSubscribeChannels()
        {
            PublishSubscribeChannel channel = new PublishSubscribeChannel();

            channel.Subscribe(new SimpleMessageHandler("Handler-1"));
            channel.Subscribe(new SimpleMessageHandler("Handler-2"));

            IMessage diningMessage =
                MessageBuilder.WithPayload("Hello World").Build();

            channel.Send(diningMessage);
            channel.Send(diningMessage);
            channel.Send(diningMessage);
        }
        public void ProcessBatch_Subscriberfails_WithFakeStoreProvider()
        {
            TestUtils.TestHelper.autoEvent = new AutoResetEvent(false);

            var m = new Message();

            var messagePacket = TestUtils.TestHelper.BuildAMessage<Message>(m)
                .WithSubscriberMetadataFor(typeof(TestUtils.SpeedySubscriberGuaranteedExceptions<Message>), false, false).GetMessage();
            var beforeRetryCount = messagePacket.SubscriberMetadataList[0].RetryCount;

            MessagePacket<Message> outputPostProcessMP = default(MessagePacket<Message>);
            string outputMessageId = string.Empty;

            var MessagePubSubChannel = new PublishSubscribeChannel<Message>();

            var stubStoreProvider = new StubIStoreProvider<Message>
            {
                ProcessStoreAsBatchFuncOfMessagePacketOfT0StringBoolean = funct => MessagePubSubChannel.HandleMessageForBatchProcessing(messagePacket, messagePacket.MessageId.ToString()),
                UpdateMessageStoreMessagePacketOfT0 = UpdatedMessagepacket =>
                {
                    outputPostProcessMP = UpdatedMessagepacket;
                    TestUtils.TestHelper.autoEvent.Set();
                    return;
                },
                SubscriberGroupCompletedForMessageString = messageId =>
                {
                    Assert.IsTrue(messagePacket.MessageId.ToString() == messageId);

                    return true;
                }
            };
            MessagePubSubChannel.StorageProvider = stubStoreProvider;

            MessagePubSubChannel.AddSubscriberType(typeof(TestUtils.SpeedySubscriberGuaranteedExceptions<Message>)).WithTimeToExpire(new TimeSpan(0, 0, 0, 1));

            MessagePubSubChannel.ProcessBatch();
            TestUtils.TestHelper.autoEvent.WaitOne(); //new TimeSpan(0, 0, 0, 5, 0)
            Assert.IsTrue(outputPostProcessMP.SubscriberMetadataList[0].RetryCount == messagePacket.SubscriberMetadataList[0].RetryCount + 1);
            Assert.IsTrue(outputPostProcessMP.MessageId == messagePacket.MessageId);
            Assert.IsTrue(outputPostProcessMP.SubscriberMetadataList.Count == 1);
            Assert.IsTrue(outputPostProcessMP.SubscriberMetadataList[0].FailedOrTimedOut == true);
        }