public void MethodDispatcher_Publishes_Response_Messages()
        {
            System.Messaging.IMessageFormatter binaryFormatter = new System.Messaging.BinaryMessageFormatter();
            using (ServiceBusRuntime runtime = Create.BinaryMsmqRuntime())
            {
                CEcho echo = new CEcho();

                SubscriptionEndpoint replyEndpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", null, null, typeof(void), new MethodDispatcher(echo, false), new PredicateMessageFilter(m => m.Action == "Echo"));
                runtime.Subscribe(replyEndpoint);
                runtime.Start();
                try
                {
                    string message = "echo this";

                    MessageDelivery[] output = runtime.PublishTwoWay(new PublishRequest(typeof(void), "Echo", message), TimeSpan.FromSeconds(100));

                    Assert.IsNotNull(output);
                    Assert.AreEqual(1, output.Length);
                    Assert.AreEqual(message, (string)output[0].Message);
                }
                finally
                {
                    runtime.Stop();
                }
            }
        }
        public void MethodDispatcher_Publishes_Fault_Messages()
        {
            System.Messaging.IMessageFormatter binaryFormatter = new System.Messaging.BinaryMessageFormatter();
            using (ServiceBusRuntime runtime = Create.BinaryMsmqRuntime())
            {
                CEcho echo = new CEcho();

                SubscriptionEndpoint replyEndpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", null, null, typeof(void), new MethodDispatcher(echo, false), new PredicateMessageFilter(m =>
                {
                    bool result = m.Action == "ThrowInvalidOperationException";
                    return(result);
                }));
                runtime.Subscribe(replyEndpoint);
                runtime.Start();
                try
                {
                    string message = null;

                    MessageDelivery[] output = runtime.PublishTwoWay(new PublishRequest(typeof(void), "ThrowInvalidOperationException", message), TimeSpan.FromSeconds(100));

                    Assert.IsNotNull(output);
                    Assert.AreEqual(1, output.Length);
                    Assert.IsInstanceOfType(typeof(InvalidOperationException), output[0].Message);
                }
                finally
                {
                    runtime.Stop();
                }
            }
        }
        public void WcfDispatcher_Publishes_Response_Messages()
        {
            using (ServiceBusRuntime runtime = Create.MsmqRuntime <IEcho>())
            {
                CEcho echo = new CEcho();

                ServiceHost echoHost = new ServiceHost(typeof(CEcho));

                try
                {
                    echoHost.Open();

                    SubscriptionEndpoint replyEndpoint = new SubscriptionEndpoint(Guid.NewGuid(), "EchoClient", "EchoHostClient", "net.pipe://localhost/echo", typeof(IEcho), new WcfProxyDispatcher(), new PredicateMessageFilter(m => m.Action == "Echo"));
                    runtime.Subscribe(replyEndpoint);
                    runtime.Start();

                    string message = "this is a message";

                    MessageDelivery[] output = runtime.PublishTwoWay(new PublishRequest(typeof(IEcho), "Echo", message), TimeSpan.FromSeconds(10));

                    Assert.IsNotNull(output);
                    Assert.IsInstanceOfType(typeof(string), output[0].Message);
                    Assert.AreEqual(message, output[0].Message);
                    echoHost.Close();
                }
                finally
                {
                    echoHost.Abort();
                }
            }
        }
        public void Can_Dispatch_To_ServiceHost()
        {
            ContractImplementation ci   = new ContractImplementation();
            ServiceHost            host = new ServiceHost(ci);

            host.Open();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore()))
            {
                WcfProxyDispatcher contractDispatcher = new WcfProxyDispatcher();

                SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", "NamedPipeClient", "net.pipe://localhost/remotehello", typeof(IContract), contractDispatcher, null);

                runtime.Subscribe(endpoint);

                runtime.Start();


                string message = "blah blah test test";


                contractDispatcher.Dispatch(new MessageDelivery(endpoint.Id, typeof(IContract), "PublishThis", message, 3, new MessageDeliveryContext()));

                Assert.AreEqual(1, ci.PublishedCount);
                Assert.AreEqual(message, ci.PublishedMessages[0]);

                runtime.Stop();
                host.Close();
            }
        }
        public void Not_Yet_Expired_Subscriptions_Get_Messages()
        {
            using (var serviceBusRuntime = new ServiceBusRuntime())
            {
                ServiceBusTest tester = new ServiceBusTest(serviceBusRuntime);

                string message            = "Publish this message";
                ContractImplementation ci = new ContractImplementation();

                tester.AddTestSubscription(ci, new PassThroughMessageFilter(), DateTime.MaxValue);


                try
                {
                    tester.WaitForDeliveries(2, TimeSpan.FromSeconds(1), () =>
                    {
                        serviceBusRuntime.PublishOneWay(new PublishRequest(typeof(IContract), "PublishThis", message));
                    });
                }
                catch (TimeoutException)
                {
                    Assert.Fail("Message should have been delivered to not yet expired subscription.");
                }
            }
        }
        public void Can_Dispatch_Raw_Messages_To_Pass_Through_Endpoint()
        {
            PassThroughService pts  = new PassThroughService();
            ServiceHost        host = new ServiceHost(pts);

            host.Open();

            WcfProxyDispatcher   contractDispatcher = new WcfProxyDispatcher();
            SubscriptionEndpoint endpoint           = new SubscriptionEndpoint(Guid.NewGuid(), "test", "PassThroughClient", "net.pipe://localhost/passthrough", typeof(IPassThroughServiceContract), contractDispatcher, new PassThroughMessageFilter());

            string action = "http://someaction";
            string body   = "this is a test";

            pts.Validator = (msg) => { Assert.AreEqual(msg.Headers.Action, action); Assert.AreEqual(msg.GetBody <string>(), body); };

            Message message = Message.CreateMessage(MessageVersion.Default, action, body);

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore()))
            {
                runtime.Subscribe(endpoint);

                runtime.Start();

                contractDispatcher.Dispatch(new MessageDelivery(endpoint.Id, typeof(IPassThroughServiceContract), action, message, 3, new MessageDeliveryContext()));

                runtime.Stop();
            }

            Assert.AreEqual(1, pts.PublishedCount);

            host.Close();
        }
        public void Can_Dispatch_Raw_Messages_To_Typed_Endpoint()
        {
            ContractImplementation ci   = new ContractImplementation();
            ServiceHost            host = new ServiceHost(ci);

            host.Open();

            WcfProxyDispatcher contractDispatcher = new WcfProxyDispatcher();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore()))
            {
                SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", "PassThroughClient", "net.pipe://localhost/remotehello", typeof(IPassThroughServiceContract), contractDispatcher, null);

                runtime.Subscribe(endpoint);

                runtime.Start();

                string action = "PublishThis";
                string body   = "blah blah test test";

                XmlDocument document = new XmlDocument();
                document.LoadXml("<PublishThis xmlns='http://tempuri.org/'><message>" + body + "</message></PublishThis>");
                Message message = Message.CreateMessage(MessageVersion.Default, action, new XmlNodeReader(document));
                contractDispatcher.Dispatch(new MessageDelivery(endpoint.Id, typeof(IPassThroughServiceContract), action, message, 3, new MessageDeliveryContext()));

                Assert.AreEqual(1, ci.PublishedCount);
                Assert.AreEqual(body, ci.PublishedMessages[0]);

                runtime.Stop();
            }

            host.Close();
        }
        public void Action_Stops_On_Stop()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();

            timerService.AddEvent(new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(1000)));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(1100);

                long beforeStopCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.GreaterOrEqual(beforeStopCount, 0);

                Thread.Sleep(1100);

                long afterStopCount = Interlocked.Read(ref count);

                Assert.GreaterOrEqual(beforeStopCount, afterStopCount);
            }
        }
        public void Event_Auto_Starts_When_Running()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();
            var evt = new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(100));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(500);

                long curCount = Interlocked.Read(ref count);
                Assert.AreEqual(0, curCount);

                timerService.AddEvent(evt);

                Thread.Sleep(500);

                curCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.GreaterOrEqual(curCount, 3);
            }
        }
        public void Event_Starts_At_Preset_Time()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();

            timerService.AddEvent(new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(100), DateTime.Now.AddSeconds(5)));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(3000);

                long curCount = Interlocked.Read(ref count);
                Assert.AreEqual(0, curCount);


                Thread.Sleep(3000);

                curCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.GreaterOrEqual(curCount, 0);
            }
        }
        public void Action_Stops_On_Stop()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();
            timerService.AddEvent(new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(1000)));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(1100);

                long beforeStopCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.GreaterOrEqual(beforeStopCount, 0);

                Thread.Sleep(1100);

                long afterStopCount = Interlocked.Read(ref count);

                Assert.GreaterOrEqual(beforeStopCount, afterStopCount);
            }
        }
        public void FileSystemDispatcher_Picks_Up_Existing_Messages()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "File System Dispatcher", null, null, typeof(IContract), new FileSystemDispatcher(new ConverterMessageDeliveryWriterFactory(encoder,typeof(IContract)),Config.IncomingFilePath), new PassThroughMessageFilter());
            dispatchRuntime.Subscribe(subscription);

            ServiceBusRuntime listenerRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var listener = new ListenerEndpoint(Guid.NewGuid(), "File System Listener", null, null, typeof(IContract), new FileSystemListener(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)),Config.IncomingFilePath, Config.ProcessedFilePath));
            listenerRuntime.AddListener(listener);
            listenerRuntime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Pass through", null, null, typeof(IContract), new ActionDispatcher((se, md) => { }), new PassThroughMessageFilter()));

            var dispatchTester = new ServiceBusTest(dispatchRuntime);
            var listenerTester = new ServiceBusTest(listenerRuntime);

            string message = "test this thing";

            dispatchTester.StartAndStop(() =>
            {
                dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", message);

                listenerTester.WaitForDeliveries(1, TimeSpan.FromSeconds(10), () =>
                {
                });
            });

            dispatchRuntime.RemoveSubscription(subscription);
        }
        public void FileSystemDispatcher_Picks_Up_Existing_Messages()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "File System Dispatcher", null, null, typeof(IContract), new FileSystemDispatcher(new ConverterMessageDeliveryWriterFactory(encoder, typeof(IContract)), Config.IncomingFilePath), new PassThroughMessageFilter());

            dispatchRuntime.Subscribe(subscription);

            ServiceBusRuntime listenerRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var listener = new ListenerEndpoint(Guid.NewGuid(), "File System Listener", null, null, typeof(IContract), new FileSystemListener(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)), Config.IncomingFilePath, Config.ProcessedFilePath));

            listenerRuntime.AddListener(listener);
            listenerRuntime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Pass through", null, null, typeof(IContract), new ActionDispatcher((se, md) => { }), new PassThroughMessageFilter()));

            var dispatchTester = new ServiceBusTest(dispatchRuntime);
            var listenerTester = new ServiceBusTest(listenerRuntime);


            string message = "test this thing";

            dispatchTester.StartAndStop(() =>
            {
                dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", message);

                listenerTester.WaitForDeliveries(1, TimeSpan.FromSeconds(10), () =>
                {
                });
            });

            dispatchRuntime.RemoveSubscription(subscription);
        }
        public void Can_Dispatch_Raw_Messages_To_Pass_Through_Endpoint()
        {
            PassThroughService pts = new PassThroughService();
            ServiceHost host = new ServiceHost(pts);
            host.Open();

            WcfProxyDispatcher contractDispatcher = new WcfProxyDispatcher();
            SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", "PassThroughClient", "net.pipe://localhost/passthrough", typeof(IPassThroughServiceContract), contractDispatcher, new PassThroughMessageFilter());

            string action = "http://someaction";
            string body = "this is a test";

            pts.Validator = (msg) => { Assert.AreEqual(msg.Headers.Action, action); Assert.AreEqual(msg.GetBody<string>(), body); };

            Message message = Message.CreateMessage(MessageVersion.Default, action, body);

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore()))
            {
                runtime.Subscribe(endpoint);

                runtime.Start();

                contractDispatcher.Dispatch(new MessageDelivery(endpoint.Id, typeof(IPassThroughServiceContract), action, message, 3, new MessageDeliveryContext()));

                runtime.Stop();
            }

            Assert.AreEqual(1, pts.PublishedCount);

            host.Close();
        }
Beispiel #15
0
        // todo: What if I want to publish a single message, but get multiple responses?
        internal void Execute(ServiceBusRuntime runtime)
        {
            lock (_executeLock)
            {
                Event.Reset();

                SubscriptionEndpoint subscription = new SubscriptionEndpoint(Guid.NewGuid(), "Heartbeat " + HeartbeatId, null, null, HearbeatRequest.ContractType, new HeartbeatReplyDispatcher(this), ResponseFilter, true);
                runtime.Subscribe(subscription);
                try
                {
                    runtime.PublishOneWay(HearbeatRequest);
                    if (Event.WaitOne(Timeout))
                    {
                        // Heartbeat success
                        runtime.PublishOneWay(SuccessRequest);
                    }
                    else
                    {
                        // Hearbeat timeout
                        runtime.PublishOneWay(FailureRequest);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    runtime.RemoveSubscription(subscription);
                }
            }
        }
        public void TestPythonTransformation()
        {
            ScriptTransformationDispatcher dispatcher = new ScriptTransformationDispatcher("py",
                                                                                           @"import clr

clr.AddReference(""IServiceOriented.ServiceBus"")
clr.AddReference(""IServiceOriented.ServiceBus.Scripting.UnitTests"")

from IServiceOriented.ServiceBus import PublishRequest
from IServiceOriented.ServiceBus.Scripting.UnitTests import AfterTransformation

def Execute():
    outgoing = AfterTransformation(int(request.Message.Value));
    return PublishRequest(request.ContractType, request.Action, outgoing)
"
                                                                                           , Microsoft.Scripting.SourceCodeKind.Statements);

            dispatcher.Script.Check();

            dispatcher.Script.ExecuteWithVariables(new Dictionary <string, object>()
            {
                { "request", new PublishRequest(null, null, new BeforeTransformation()
                    {
                        Value = "1000"
                    }) }
            });

            AutoResetEvent reset = new AutoResetEvent(false);

            bool success = false;

            ServiceBusRuntime runtime = new ServiceBusRuntime(new QueuedDeliveryCore(new NonTransactionalMemoryQueue(), new NonTransactionalMemoryQueue(), new NonTransactionalMemoryQueue()));

            runtime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Tranformation", null, null, typeof(void), dispatcher, new TypedMessageFilter(typeof(BeforeTransformation))));
            runtime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "AfterTransformation", null, null, typeof(void), new ActionDispatcher((subscription, md) =>
            {
                try
                {
                    success = ((AfterTransformation)md.Message).Value == 1000;
                }
                finally
                {
                    reset.Set();
                }
            }), new TypedMessageFilter(typeof(AfterTransformation))));
            runtime.Start();

            runtime.PublishOneWay(new PublishRequest(null, null, new BeforeTransformation()
            {
                Value = "1000"
            }));

            if (!reset.WaitOne(1000 * 10, true))
            {
                Assert.Fail("Waited too long");
            }

            runtime.Stop();
        }
        /// <summary>
        /// Dynamically generate a service host
        /// </summary>
        public static ServiceHost CreateHost(ServiceBusRuntime runtime, Type contractType, Type implementationType, string configurationName, string address)
        {
            if (configurationName == null)
            {
                throw new InvalidOperationException("The endpoint's ConfigurationName was not set");
            }
            object host = Activator.CreateInstance(implementationType);

            ((WcfListenerServiceImplementationBase)host).Runtime = runtime;
            ServiceHost serviceHost = new WcfListenerServiceHost(host, contractType.FullName, configurationName, address);

            return(serviceHost);
        }
Beispiel #18
0
        public ChatServer()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IChatService)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IChatService)));
            _serviceBus = new ServiceBusRuntime(new DirectDeliveryCore() , new WcfManagementService());
            _serviceBus.AddListener(new ListenerEndpoint(Guid.NewGuid(), "Chat Service", "ChatServer", "http://localhost/chatServer", typeof(IChatService), new WcfServiceHostListener()));
            _serviceBus.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "No subscribers", "ChatClient", "", typeof(IChatService), new MethodDispatcher(new UnhandledReplyHandler(_serviceBus)), new UnhandledMessageFilter(typeof(SendMessageRequest)), true));
            _serviceBus.UnhandledException+= (o, ex) =>
                {
                    Console.WriteLine("Unhandled Exception: "+ex.ExceptionObject);
                };
        }
Beispiel #19
0
        public void Heartbeat_Requires_Timer_Service()
        {
            try
            {
                using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore(), new HeartbeatRuntimeService()))
                {
                    runtime.Start();
                }

                Assert.Fail();
            }
            catch (ValidationException) // should not be able to start service bus without both timer runtime service
            {
            }
        }
        public ChatServer()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IChatService)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IChatService)));

            _serviceBus = new ServiceBusRuntime(new DirectDeliveryCore(), new WcfManagementService());
            _serviceBus.AddListener(new ListenerEndpoint(Guid.NewGuid(), "Chat Service", "ChatServer", "http://localhost/chatServer", typeof(IChatService), new WcfServiceHostListener()));
            _serviceBus.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "No subscribers", "ChatClient", "", typeof(IChatService), new MethodDispatcher(new UnhandledReplyHandler(_serviceBus)), new UnhandledMessageFilter(typeof(SendMessageRequest)), true));
            _serviceBus.UnhandledException += (o, ex) =>
            {
                Console.WriteLine("Unhandled Exception: " + ex.ExceptionObject);
            };
        }
        public void Heartbeat_Requires_Timer_Service()
        {
            try
            {
                using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore(), new HeartbeatRuntimeService()))
                {
                    runtime.Start();
                }

                Assert.Fail();
            }
            catch(ValidationException) // should not be able to start service bus without both timer runtime service
            {

            }
        }
        public void Heartbeat_Timeout_Causes_Failure_Request()
        {
            using (HeartbeatRuntimeService heartbeatService = new HeartbeatRuntimeService())
            {
                using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore(), new TimerRuntimeService(), heartbeatService))
                {
                    heartbeatService.RegisterHeartbeat(new Heartbeat(Guid.NewGuid(), TimeSpan.FromSeconds(5), new PublishRequest(null, null, "BeatRequest"),
                                                        new PublishRequest(null, null, "Success"), new PublishRequest(null, null, "Failure"),
                                                        new PredicateMessageFilter(pr => (string)pr.Message == "BeatResponse"), TimeSpan.FromSeconds(1)));

                    AutoResetEvent failEvt = new AutoResetEvent(false);
                    AutoResetEvent successEvt = new AutoResetEvent(false);
                    AutoResetEvent responseEvt = new AutoResetEvent(false);

                    /*runtime.Subscribe(new SubscriptionEndpoint("BeatResponse", null, null, null, new ActionDispatcher((se, md) => {
                        responseEvt.Set(); ThreadPool.QueueUserWorkItem(s => { Thread.Sleep(2000); runtime.PublishOneWay(new PublishRequest(null, null, "BeatResponse")); });
                    }),
                        new PredicateMessageFilter(pr => (string)pr.Message == "BeatRequest")));*/

                    runtime.Subscribe(new SubscriptionEndpoint("Success", null, null, null, new ActionDispatcher((se, md) => successEvt.Set()), new PredicateMessageFilter(pr => (string)pr.Message == "Success")));
                    runtime.Subscribe(new SubscriptionEndpoint("Failure", null, null, null, new ActionDispatcher((se, md) => failEvt.Set()), new PredicateMessageFilter(pr => (string)pr.Message == "Failure")));

                    ServiceBusTest tester = new ServiceBusTest(runtime);

                    tester.StartAndStop(() =>
                    {
                        if (!failEvt.WaitOne(TimeSpan.FromSeconds(10)))
                        {
                            if (!responseEvt.WaitOne(0))
                            {
                                Assert.Fail("The heartbeat request was never published.");
                            }

                            if (successEvt.WaitOne(0))
                            {
                                Assert.Fail("The heartbeat success event was published instead of the failure event");
                            }
                            Assert.Fail("The heartbeat failure event was not published");
                        }

                    });

                }
            }
        }
        public void WcfListener_Publishes_Incoming_Messages_Properly()
        {
            ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore());
            runtime.AddListener(new ListenerEndpoint("test", "NamedPipeListener", "net.pipe://localhost/remotehello", typeof(IContract), new WcfServiceHostListener()));

            string message = "This is a test";

            runtime.Subscribe(new SubscriptionEndpoint("test subscription", null, null, typeof(IContract), new ActionDispatcher((se, md) => { Assert.AreEqual(message, (string)md.Message); }), new PassThroughMessageFilter()));

            ServiceBusTest tester = new ServiceBusTest(runtime);
            tester.WaitForDeliveries(1, TimeSpan.FromSeconds(5), () =>
            {
                Service.Use<IContract>("NamedPipeClient", contract =>
                {
                    contract.PublishThis(message);
                });
            });
        }
Beispiel #24
0
        public void SmtpDispatcher_Can_Send_Messages()
        {
            if (Config.FromMailAddress != null && Config.ToMailAddress != null)
            {
                ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
                var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "Smtp Dispatcher", null, null, typeof(IContract), new SmtpDispatcher("this is a test", new MailAddress(Config.FromMailAddress), new MailAddress[] { new MailAddress(Config.ToMailAddress) }), new PassThroughMessageFilter());

                ServiceBusTest tester = new ServiceBusTest(dispatchRuntime);
                tester.StartAndStop(() =>
                {
                    dispatchRuntime.Subscribe(subscription);
                    dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", "this is a test message");
                });
            }
            else
            {
                NUnit.Framework.Assert.Ignore("From and to email addresses must be configured to run smtp tests");
            }
        }
Beispiel #25
0
        public void Heartbeat_Timeout_Causes_Failure_Request()
        {
            using (HeartbeatRuntimeService heartbeatService = new HeartbeatRuntimeService())
            {
                using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore(), new TimerRuntimeService(), heartbeatService))
                {
                    heartbeatService.RegisterHeartbeat(new Heartbeat(Guid.NewGuid(), TimeSpan.FromSeconds(5), new PublishRequest(null, null, "BeatRequest"),
                                                                     new PublishRequest(null, null, "Success"), new PublishRequest(null, null, "Failure"),
                                                                     new PredicateMessageFilter(pr => (string)pr.Message == "BeatResponse"), TimeSpan.FromSeconds(1)));

                    AutoResetEvent failEvt     = new AutoResetEvent(false);
                    AutoResetEvent successEvt  = new AutoResetEvent(false);
                    AutoResetEvent responseEvt = new AutoResetEvent(false);

                    /*runtime.Subscribe(new SubscriptionEndpoint("BeatResponse", null, null, null, new ActionDispatcher((se, md) => {
                     *  responseEvt.Set(); ThreadPool.QueueUserWorkItem(s => { Thread.Sleep(2000); runtime.PublishOneWay(new PublishRequest(null, null, "BeatResponse")); });
                     * }),
                     *  new PredicateMessageFilter(pr => (string)pr.Message == "BeatRequest")));*/

                    runtime.Subscribe(new SubscriptionEndpoint("Success", null, null, null, new ActionDispatcher((se, md) => successEvt.Set()), new PredicateMessageFilter(pr => (string)pr.Message == "Success")));
                    runtime.Subscribe(new SubscriptionEndpoint("Failure", null, null, null, new ActionDispatcher((se, md) => failEvt.Set()), new PredicateMessageFilter(pr => (string)pr.Message == "Failure")));

                    ServiceBusTest tester = new ServiceBusTest(runtime);

                    tester.StartAndStop(() =>
                    {
                        if (!failEvt.WaitOne(TimeSpan.FromSeconds(10)))
                        {
                            if (!responseEvt.WaitOne(0))
                            {
                                Assert.Fail("The heartbeat request was never published.");
                            }

                            if (successEvt.WaitOne(0))
                            {
                                Assert.Fail("The heartbeat success event was published instead of the failure event");
                            }
                            Assert.Fail("The heartbeat failure event was not published");
                        }
                    });
                }
            }
        }
        public void WcfListener_Publishes_Incoming_Messages_Properly()
        {
            ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore());

            runtime.AddListener(new ListenerEndpoint("test", "NamedPipeListener", "net.pipe://localhost/remotehello", typeof(IContract), new WcfServiceHostListener()));

            string message = "This is a test";

            runtime.Subscribe(new SubscriptionEndpoint("test subscription", null, null, typeof(IContract), new ActionDispatcher((se, md) => { Assert.AreEqual(message, (string)md.Message); }), new PassThroughMessageFilter()));

            ServiceBusTest tester = new ServiceBusTest(runtime);

            tester.WaitForDeliveries(1, TimeSpan.FromSeconds(5), () =>
            {
                Service.Use <IContract>("NamedPipeClient", contract =>
                {
                    contract.PublishThis(message);
                });
            });
        }
        public void WcfListener_Can_Listen_For_Raw_Messages()
        {
            ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore());
            runtime.AddListener(new ListenerEndpoint("test", "PassThroughListener", "net.pipe://localhost/passthrough", typeof(IPassThroughServiceContract), new WcfServiceHostListener()));

            string action = "http://someaction";
            string body = "some body";

            runtime.Subscribe(new SubscriptionEndpoint("test subscription", null, null, typeof(IContract), new ActionDispatcher((se, md) => { Assert.AreEqual(action, ((Message)md.Message).Headers.Action); Assert.AreEqual(body, ((Message)md.Message).GetBody<string>()); }), new PassThroughMessageFilter()));

            ServiceBusTest tester = new ServiceBusTest(runtime);
            tester.WaitForDeliveries(1, TimeSpan.FromSeconds(5), () =>
            {
                Service.Use<IPassThroughServiceContract>("PassThroughClient", contract =>
                {
                    Message message = Message.CreateMessage(MessageVersion.Default, action, body);
                    contract.Send(message);
                });
            });
        }
        public void Can_Add_And_Remove_Subscriptions()
        {
            using(ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore(), new WcfManagementService()))
            {
                ServiceBusTest tester = new ServiceBusTest(runtime);
                tester.StartAndStop(() =>
                {
                    Service.Use<IServiceBusManagementService>(managementService =>
                        {
                            ListenerEndpoint endpoint = new ListenerEndpoint(Guid.NewGuid(), "name of endpoint", "NamedPipeListener", "net.pipe://test/someservice/", typeof(IContract), new WcfServiceHostListener());
                            managementService.AddListener(endpoint);

                            ListenerEndpoint added = managementService.ListListeners().First();
                            tester.AssertEqual(endpoint, added);

                            managementService.RemoveListener(endpoint.Id);
                            Assert.IsEmpty(managementService.ListListeners());
                        });
                });
            }
        }
        public void Can_Add_And_Remove_Listeners()
        {
            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore(), new WcfManagementService()))
            {
                ServiceBusTest tester = new ServiceBusTest(runtime);
                tester.StartAndStop(() =>
                {
                    Service.Use <IServiceBusManagementService>(managementService =>
                    {
                        SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "name of endpoint", "NamedPipeClient", "net.pipe://test/someservice/", typeof(IContract), new WcfProxyDispatcher(), null);
                        managementService.Subscribe(endpoint);

                        SubscriptionEndpoint added = managementService.ListSubscribers().First();
                        tester.AssertEqual(endpoint, added);

                        managementService.Unsubscribe(endpoint.Id);
                        Assert.IsEmpty(managementService.ListSubscribers());
                    });
                });
            }
        }
        public void WcfListener_Can_Listen_For_Raw_Messages()
        {
            ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore());

            runtime.AddListener(new ListenerEndpoint("test", "PassThroughListener", "net.pipe://localhost/passthrough", typeof(IPassThroughServiceContract), new WcfServiceHostListener()));

            string action = "http://someaction";
            string body   = "some body";

            runtime.Subscribe(new SubscriptionEndpoint("test subscription", null, null, typeof(IContract), new ActionDispatcher((se, md) => { Assert.AreEqual(action, ((Message)md.Message).Headers.Action); Assert.AreEqual(body, ((Message)md.Message).GetBody <string>()); }), new PassThroughMessageFilter()));

            ServiceBusTest tester = new ServiceBusTest(runtime);

            tester.WaitForDeliveries(1, TimeSpan.FromSeconds(5), () =>
            {
                Service.Use <IPassThroughServiceContract>("PassThroughClient", contract =>
                {
                    Message message = Message.CreateMessage(MessageVersion.Default, action, body);
                    contract.Send(message);
                });
            });
        }
        public void Action_Ticks_On_Intervals()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();

            timerService.AddEvent(new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(1000)));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(9100);

                long curCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.AreEqual(9, curCount);
            }
        }
 public ServiceBusManagementService(ServiceBusRuntime runtime)
 {
     Runtime = runtime;
 }
        public void WcfDispatcher_Publishes_Fault_Messages()
        {
            //Assert.Ignore("Bug in .NET framework prevents this from working properly");

            // Code in

            /*
             *
             * private void ValidateScopeRequiredAndAutoComplete(OperationDescription operation, bool singleThreaded, string contractName)
             * {
             *  OperationBehaviorAttribute attribute = operation.Behaviors.Find<OperationBehaviorAttribute>();
             *  if (attribute != null)
             *  {
             *      if (!attribute.TransactionScopeRequired && !attribute.TransactionAutoComplete)
             *      {
             *          string name = "SFxTransactionAutoEnlistOrAutoComplete2";
             *          throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(name, new object[] { contractName, operation.Name })));
             *      }
             *      if (!singleThreaded && !attribute.TransactionAutoComplete)
             *      {
             *          string str2 = "SFxTransactionNonConcurrentOrAutoComplete2";
             *          throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(str2, new object[] { contractName, operation.Name })));
             *      }
             *  }
             * }
             *
             * throws:
             *
             *  System.InvalidOperationException : The operation 'ThrowFaultException' on contract 'IEcho' is configured with TransactionAutoComplete set to true and with TransactionScopeRequired set to false. TransactionAutoComplete requires that TransactionScopeRequired is set to true.
             *      at System.ServiceModel.Dispatcher.TransactionValidationBehavior.ValidateScopeRequiredAndAutoComplete(OperationDescription operation, Boolean singleThreaded, String contractName)
             *      at System.ServiceModel.Dispatcher.TransactionValidationBehavior.System.ServiceModel.Description.IServiceBehavior.Validate(ServiceDescription service, ServiceHostBase serviceHostBase)
             *      at System.ServiceModel.Description.DispatcherBuilder.ValidateDescription(ServiceDescription description, ServiceHostBase serviceHost)
             *      at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
             *      at System.ServiceModel.ServiceHostBase.InitializeRuntime()
             *      at System.ServiceModel.ServiceHostBase.OnBeginOpen()
             *      at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
             *      at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
             *      at System.ServiceModel.Channels.CommunicationObject.Open()
             *
             * Check that throws this exception appears to be coded incorrectly, since it checks !attribute.TransactionAutoComplete instead of attribute.TransactionAutoComplete before throwing the message, so we
             * can't tell WCF not to cancel the transaction.
             *
             */


            using (ServiceBusRuntime runtime = Create.MsmqRuntime <IEcho>())
            {
                CEcho echo = new CEcho();

                ServiceHost echoHost = new ServiceHost(typeof(CEcho));

                try
                {
                    echoHost.Open();

                    SubscriptionEndpoint replyEndpoint = new SubscriptionEndpoint(Guid.NewGuid(), "EchoClient", "EchoHostClient", "net.pipe://localhost/echo", typeof(IEcho), new WcfProxyDispatcher(), new PredicateMessageFilter(m => m.Action == "ThrowFaultException"));
                    runtime.Subscribe(replyEndpoint);
                    runtime.Start();

                    string message = "fault reason";

                    MessageDelivery[] output = runtime.PublishTwoWay(new PublishRequest(typeof(IEcho), "ThrowFaultException", message), TimeSpan.FromSeconds(10));

                    Assert.IsNotNull(output);
                    Assert.IsInstanceOfType(typeof(FaultException <SendFault>), output[0].Message);
                    Assert.AreEqual(message, ((FaultException <SendFault>)output[0].Message).Reason.ToString());
                    echoHost.Close();
                }
                finally
                {
                    echoHost.Abort();
                }
            }
        }
 public UnhandledReplyHandler(ServiceBusRuntime serviceBus)
 {
     _serviceBus = serviceBus;
 }
Beispiel #35
0
 public UnhandledReplyHandler(ServiceBusRuntime serviceBus)
 {
     _serviceBus = serviceBus;
 }
        // todo: What if I want to publish a single message, but get multiple responses?
        internal void Execute(ServiceBusRuntime runtime)
        {
            lock (_executeLock)
            {
                Event.Reset();

                SubscriptionEndpoint subscription = new SubscriptionEndpoint(Guid.NewGuid(), "Heartbeat " + HeartbeatId, null, null, HearbeatRequest.ContractType, new HeartbeatReplyDispatcher(this), ResponseFilter, true);
                runtime.Subscribe(subscription);
                try
                {
                    runtime.PublishOneWay(HearbeatRequest);
                    if (Event.WaitOne(Timeout))
                    {
                        // Heartbeat success
                        runtime.PublishOneWay(SuccessRequest);
                    }
                    else
                    {
                        // Hearbeat timeout
                        runtime.PublishOneWay(FailureRequest);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    runtime.RemoveSubscription(subscription);
                }
            }
        }
 public ServiceBusTest(ServiceBusRuntime runtime)
 {
     serviceBusRuntime = runtime;
 }
        public void Can_Dispatch_Raw_Messages_To_Typed_Endpoint()
        {
            ContractImplementation ci = new ContractImplementation();
            ServiceHost host = new ServiceHost(ci);
            host.Open();

            WcfProxyDispatcher contractDispatcher = new WcfProxyDispatcher();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore()))
            {

                SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", "PassThroughClient", "net.pipe://localhost/remotehello", typeof(IPassThroughServiceContract), contractDispatcher, null);

                runtime.Subscribe(endpoint);

                runtime.Start();

                string action = "PublishThis";
                string body = "blah blah test test";

                XmlDocument document = new XmlDocument();
                document.LoadXml("<PublishThis xmlns='http://tempuri.org/'><message>" + body + "</message></PublishThis>");
                Message message = Message.CreateMessage(MessageVersion.Default, action, new XmlNodeReader(document));
                contractDispatcher.Dispatch(new MessageDelivery(endpoint.Id, typeof(IPassThroughServiceContract), action, message, 3, new MessageDeliveryContext()));

                Assert.AreEqual(1, ci.PublishedCount);
                Assert.AreEqual(body, ci.PublishedMessages[0]);

                runtime.Stop();
            }

            host.Close();
        }
        public void Not_Yet_Expired_Subscriptions_Get_Messages()
        {
            using (var serviceBusRuntime = new ServiceBusRuntime())
            {
                ServiceBusTest tester = new ServiceBusTest(serviceBusRuntime);

                string message = "Publish this message";
                ContractImplementation ci = new ContractImplementation();

                tester.AddTestSubscription(ci, new PassThroughMessageFilter(), DateTime.MaxValue);

                try
                {
                    tester.WaitForDeliveries(2, TimeSpan.FromSeconds(1), () =>
                    {
                        serviceBusRuntime.PublishOneWay(new PublishRequest(typeof(IContract), "PublishThis", message));
                    });
                }
                catch (TimeoutException)
                {
                    Assert.Fail("Message should have been delivered to not yet expired subscription.");
                }
            }
        }
        public void Can_Dispatch_To_ServiceHost()
        {
            ContractImplementation ci = new ContractImplementation();
            ServiceHost host = new ServiceHost(ci);
            host.Open();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(new DirectDeliveryCore()))
            {
                WcfProxyDispatcher contractDispatcher = new WcfProxyDispatcher();

                SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "test", "NamedPipeClient", "net.pipe://localhost/remotehello", typeof(IContract), contractDispatcher, null);

                runtime.Subscribe(endpoint);

                runtime.Start();

                string message = "blah blah test test";

                contractDispatcher.Dispatch(new MessageDelivery(endpoint.Id, typeof(IContract), "PublishThis", message, 3, new MessageDeliveryContext()));

                Assert.AreEqual(1, ci.PublishedCount);
                Assert.AreEqual(message, ci.PublishedMessages[0]);

                runtime.Stop();
                host.Close();
            }
        }
        public void Event_Auto_Starts_When_Running()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();
            var evt = new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(100));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(500);

                long curCount = Interlocked.Read(ref count);
                Assert.AreEqual(0, curCount);

                timerService.AddEvent(evt);

                Thread.Sleep(500);

                curCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.GreaterOrEqual(curCount, 3);
            }
        }
Beispiel #42
0
        public static ServiceBusRuntime MemoryQueueRuntime()
        {
            ServiceBusRuntime runtime = new ServiceBusRuntime(new QueuedDeliveryCore(new NonTransactionalMemoryQueue(), new NonTransactionalMemoryQueue(), new NonTransactionalMemoryQueue()));

            return(runtime);
        }
 public ServiceBusTest(ServiceBusRuntime runtime)
 {
     serviceBusRuntime = runtime;
 }
        public void Event_Starts_At_Preset_Time()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();
            timerService.AddEvent(new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(100), DateTime.Now.AddSeconds(5)));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(3000);

                long curCount = Interlocked.Read(ref count);
                Assert.AreEqual(0, curCount);

                Thread.Sleep(3000);

                curCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.GreaterOrEqual(curCount, 0);
            }
        }
        public void Action_Ticks_On_Intervals()
        {
            long count = 0;

            TimerRuntimeService timerService = new TimerRuntimeService();
            timerService.AddEvent(new TimerEvent(() => { Interlocked.Increment(ref count); }, TimeSpan.FromMilliseconds(1000)));

            DeliveryCore deliveryCore = new DirectDeliveryCore();

            using (ServiceBusRuntime runtime = new ServiceBusRuntime(deliveryCore, timerService))
            {
                runtime.Start();

                Thread.Sleep(9100);

                long curCount = Interlocked.Read(ref count);

                runtime.Stop();

                Assert.AreEqual(9, curCount);
            }
        }
Beispiel #46
0
 public ServiceBusManagementService(ServiceBusRuntime runtime)
 {
     Runtime = runtime;
 }
 /// <summary>
 /// Dynamically generate a service host
 /// </summary>
 public static ServiceHost CreateHost(ServiceBusRuntime runtime, Type contractType, Type implementationType, string configurationName, string address)
 {
     if (configurationName == null)
     {
         throw new InvalidOperationException("The endpoint's ConfigurationName was not set");
     }
     object host = Activator.CreateInstance(implementationType);
     ((WcfListenerServiceImplementationBase)host).Runtime = runtime;
     ServiceHost serviceHost = new WcfListenerServiceHost(host, contractType.FullName, configurationName, address);
     return serviceHost;
 }