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 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 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();
                }
            }
        }
Exemple #4
0
        public void Enqueue_Transactions_Abort_Properly()
        {
            recreateQueue();


            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

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

            MsmqMessageDeliveryQueue queue = new MsmqMessageDeliveryQueue(Config.TestQueuePath, formatter);

            SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "SubscriptionName", "http://localhost/test", "SubscriptionConfigName", typeof(IContract), new WcfProxyDispatcher(), new PassThroughMessageFilter());

            MessageDelivery enqueued = new MessageDelivery(endpoint.Id, typeof(IContract), "PublishThis", "randomMessageData", 3, new MessageDeliveryContext());

            Assert.IsNull(queue.Peek(TimeSpan.FromSeconds(1))); // make sure queue is null before starting

            // Enqueue, but abort transaction
            using (TransactionScope ts = new TransactionScope())
            {
                queue.Enqueue(enqueued);
            }

            using (TransactionScope ts = new TransactionScope())
            {
                MessageDelivery dequeued = queue.Dequeue(TimeSpan.FromSeconds(5));
                Assert.IsNull(dequeued);
            }
        }
Exemple #5
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 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_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 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_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 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 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();
                }
            }
        }
 protected override void CreateSubscription(SubscriptionEndpoint subscription)
 {
     if (!subscription.Transient)
     {
         _db.CreateSubscription(subscription);
     }
 }
 protected override void DeleteSubscription(SubscriptionEndpoint subscription)
 {
     if (!subscription.Transient)
     {
         _db.DeleteSubscription(subscription.Id);
     }
 }
        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 AssertEqual(SubscriptionEndpoint endpoint1, SubscriptionEndpoint endpoint2)
        {
            Assert.AreEqual(endpoint1.Id, endpoint2.Id);
            Assert.AreEqual(endpoint1.Name, endpoint2.Name);
            Assert.AreEqual(endpoint1.ConfigurationName, endpoint2.ConfigurationName);
            Assert.AreEqual(endpoint1.ContractType, endpoint2.ContractType);
            Assert.AreEqual(endpoint1.Address, endpoint2.Address);

            Assert.IsInstanceOfType(endpoint1.Dispatcher.GetType(), endpoint2.Dispatcher);
        }
        public void AssertEqual(SubscriptionEndpoint endpoint1, SubscriptionEndpoint endpoint2)
        {
            Assert.AreEqual(endpoint1.Id, endpoint2.Id);
            Assert.AreEqual(endpoint1.Name, endpoint2.Name);
            Assert.AreEqual(endpoint1.ConfigurationName, endpoint2.ConfigurationName);
            Assert.AreEqual(endpoint1.ContractType, endpoint2.ContractType);
            Assert.AreEqual(endpoint1.Address, endpoint2.Address);

            Assert.IsInstanceOfType(endpoint1.Dispatcher.GetType(), endpoint2.Dispatcher);
        }
Exemple #17
0
        public void Can_Create_Remove_Update_And_Delete_Endpoints()
        {
            SqlSubscriptionDB db = new SqlSubscriptionDB(_connectionString, new Type[] { typeof(WcfProxyDispatcher) }, new Type[] { typeof(WcfServiceHostListener) }, new Type[] { typeof(PassThroughMessageFilter) });

            Assert.AreEqual(0, db.LoadListenerEndpoints().Count());
            Assert.AreEqual(0, db.LoadSubscriptionEndpoints().Count());

            ListenerEndpoint listener = new ListenerEndpoint(Guid.NewGuid(), "listener", "ListenerConfig", "http://localhost/test", typeof(IContract), new WcfServiceHostListener());

            db.CreateListener(listener);

            IEnumerable <ListenerEndpoint> listeners = db.LoadListenerEndpoints();

            Assert.AreEqual(1, listeners.Count());

            ListenerEndpoint savedListener = listeners.First();

            Assert.AreEqual(listener.Name, savedListener.Name);
            Assert.AreEqual(listener.Id, savedListener.Id);
            Assert.AreEqual(listener.ContractType, savedListener.ContractType);
            Assert.AreEqual(listener.ConfigurationName, savedListener.ConfigurationName);
            Assert.AreEqual(listener.Address, savedListener.Address);

            SubscriptionEndpoint subscription = new SubscriptionEndpoint(Guid.NewGuid(), "subscription", "SubscriptionConfig", "http://localhost/test/subscription", typeof(IContract), new WcfProxyDispatcher(), new PassThroughMessageFilter());

            db.CreateSubscription(subscription);

            IEnumerable <SubscriptionEndpoint> subscriptions = db.LoadSubscriptionEndpoints();

            Assert.AreEqual(1, subscriptions.Count());

            SubscriptionEndpoint savedSubscription = subscriptions.First();

            Assert.AreEqual(subscription.Name, savedSubscription.Name);
            Assert.AreEqual(subscription.Address, savedSubscription.Address);
            Assert.AreEqual(subscription.ConfigurationName, savedSubscription.ConfigurationName);
            Assert.AreEqual(subscription.ContractType, savedSubscription.ContractType);
            // TODO: Compare dispatchers
            Assert.AreEqual(subscription.Id, savedSubscription.Id);
            Assert.AreEqual(subscription.Filter.GetType(), savedSubscription.Filter.GetType());


            db.DeleteListener(listener.Id);
        }
 public void CreateSubscription(SubscriptionEndpoint subscription)
 {
     using (SqlConnection connection = getConnection())
     {
         using (SqlCommand command = new SqlCommand("sp_subscription_create", connection))
         {
             command.CommandType = CommandType.StoredProcedure;
             command.Parameters.AddWithValue("@id", subscription.Id);
             command.Parameters.AddWithValue("@filter_data", getFilterPersistenceData(subscription.Filter));
             command.Parameters.AddWithValue("@address", subscription.Address);
             command.Parameters.AddWithValue("@configuration_name", subscription.ConfigurationName);
             command.Parameters.AddWithValue("@contract_type", subscription.ContractTypeName);
             command.Parameters.AddWithValue("@name", subscription.Name);
             command.Parameters.AddWithValue("@expiration", (object)subscription.Expiration ?? DBNull.Value);
             command.Parameters.AddWithValue("@dispatcher_data", getDispatcherPersistenceData(subscription.Dispatcher));
             command.ExecuteNonQuery();
         }
     }
 }
Exemple #19
0
        ActionLookup initActionLookup(SubscriptionEndpoint endpoint)
        {
            ActionLookup lookup = null;

            if (_lookup != null)
            {
                return(_lookup);
            }

            lookup = new ActionLookup();

            Dictionary <string, MethodInfo> actionLookup      = new Dictionary <string, MethodInfo>();
            Dictionary <string, string>     replyActionLookup = new Dictionary <string, string>();

            foreach (OperationDescription operation in ContractDescription.GetContract(endpoint.ContractType).Operations)
            {
                MessageDescription requestMessage  = operation.Messages.Where(md => md.Direction == MessageDirection.Input).First();
                MessageDescription responseMessage = operation.Messages.Where(md => md.Direction == MessageDirection.Output).FirstOrDefault();

                if (requestMessage.Action == "*")
                {
                    _passThrough = true;
                }

                actionLookup.Add(requestMessage.Action, operation.SyncMethod);

                if (responseMessage != null)
                {
                    string replyAction = responseMessage.Action;

                    if (replyAction != null)
                    {
                        replyActionLookup.Add(requestMessage.Action, replyAction);
                    }
                }
            }
            lookup.MethodLookup      = actionLookup;
            lookup.ReplyActionLookup = replyActionLookup;

            _lookup = lookup;

            return(lookup);
        }
Exemple #20
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");
            }
        }
Exemple #21
0
        void testMessageDelivery <T>(string messageAction, object messageData)
        {
            Type interfaceType = typeof(T);

            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder           encoder            = element.CreateMessageEncoderFactory().Encoder;
            MessageDeliveryFormatter formatter          = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(T)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(T)));


            MsmqMessageDeliveryQueue queue = new MsmqMessageDeliveryQueue(Config.TestQueuePath, formatter);

            SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "SubscriptionName", "http://localhost/test", "SubscriptionConfigName", interfaceType, new WcfProxyDispatcher(), new PassThroughMessageFilter());

            MessageDelivery enqueued = new MessageDelivery(endpoint.Id, interfaceType, messageAction, messageData, 3, new MessageDeliveryContext());

            using (TransactionScope ts = new TransactionScope())
            {
                queue.Enqueue(enqueued);
                ts.Complete();
            }

            // Peek
            MessageDelivery dequeued = queue.Peek(TimeSpan.FromSeconds(30));

            Assert.IsNotNull(dequeued);
            Assert.AreEqual(enqueued.Action, dequeued.Action);
            Assert.AreEqual(enqueued.SubscriptionEndpointId, dequeued.SubscriptionEndpointId);

            using (TransactionScope ts = new TransactionScope())
            {
                // Pull for real
                dequeued = queue.Dequeue(TimeSpan.FromSeconds(30));
                ts.Complete();
            }
            Assert.IsNotNull(dequeued);
            Assert.AreEqual(enqueued.Action, dequeued.Action);
            Assert.AreEqual(enqueued.SubscriptionEndpointId, dequeued.SubscriptionEndpointId);

            // Should now be empty
            dequeued = queue.Peek(TimeSpan.FromSeconds(1));
            Assert.IsNull(dequeued);
        }
 public override void Deliver(MessageDelivery delivery)
 {
     if (!Started)
     {
         throw new InvalidOperationException("Cannot deliver messages before the bus is started");
     }
     try
     {
         SubscriptionEndpoint endpoint = Runtime.GetSubscription(delivery.SubscriptionEndpointId);
         if (endpoint != null) // subscription may be removed
         {
             endpoint.Dispatcher.Dispatch(delivery);
         }
         NotifyDelivery(delivery);
     }
     catch (Exception ex)
     {
         throw new DeliveryException("Unhandled exception while attempting to deliver the message", ex);
     }
 }
        public IEnumerable <SubscriptionEndpoint> LoadSubscriptionEndpoints()
        {
            List <SubscriptionEndpoint> endpoints = new List <SubscriptionEndpoint>();

            using (SqlConnection connection = getConnection())
            {
                using (SqlCommand command = new SqlCommand("sp_subscription_list", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    using (SqlDataReader dataReader = command.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            SubscriptionEndpoint subscription = getSubscription(dataReader);
                            endpoints.Add(subscription);
                        }
                    }
                }
            }
            return(endpoints);
        }
        SubscriptionEndpoint getSubscription(IDataReader dr)
        {
            SubscriptionEndpoint endpoint = new SubscriptionEndpoint(
                (Guid)dr["id"],
                dr["name"] as string,
                dr["configuration_name"] as string,
                dr["address"] as string,
                Type.GetType(dr["contract_type"] as string),
                getDispatcherFromPersistenceData((byte[])dr["dispatcher_data"]),
                getFilterFromPersistenceData((byte[])dr["filter_data"]),
                false,
                dr["expiration"] == DBNull.Value ? default(DateTime?) : Convert.ToDateTime(dr["expiration"]))
            ;

            if (endpoint.ContractType == null)
            {
                throw new InvalidOperationException("Contract type could not be loaded");
            }

            return(endpoint);
        }
Exemple #25
0
        protected override void OnStart()
        {
            foreach (Endpoint e in LoadEndpoints())
            {
                ListenerEndpoint     le = e as ListenerEndpoint;
                SubscriptionEndpoint se = e as SubscriptionEndpoint;

                if (le != null)
                {
                    _managedEndpoints.Add(le);
                }
                else if (se != null)
                {
                    _managedEndpoints.Add(se);
                }
                else
                {
                    throw new InvalidOperationException("Invalid endpoint type encountered");
                }
            }
        }
        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 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 Can_Create_Remove_Update_And_Delete_Endpoints()
        {
            SqlSubscriptionDB db = new SqlSubscriptionDB(_connectionString, new Type[] { typeof(WcfProxyDispatcher) }, new Type[] { typeof(WcfServiceHostListener)  }, new Type[] { typeof(PassThroughMessageFilter) });

            Assert.AreEqual(0, db.LoadListenerEndpoints().Count());
            Assert.AreEqual(0, db.LoadSubscriptionEndpoints().Count());

            ListenerEndpoint listener = new ListenerEndpoint(Guid.NewGuid(), "listener", "ListenerConfig", "http://localhost/test", typeof(IContract), new WcfServiceHostListener());
            db.CreateListener(listener);

            IEnumerable<ListenerEndpoint> listeners = db.LoadListenerEndpoints();
            Assert.AreEqual(1, listeners.Count());

            ListenerEndpoint savedListener = listeners.First();

            Assert.AreEqual(listener.Name, savedListener.Name);
            Assert.AreEqual(listener.Id, savedListener.Id);
            Assert.AreEqual(listener.ContractType, savedListener.ContractType);
            Assert.AreEqual(listener.ConfigurationName, savedListener.ConfigurationName);
            Assert.AreEqual(listener.Address, savedListener.Address);

            SubscriptionEndpoint subscription = new SubscriptionEndpoint(Guid.NewGuid(), "subscription", "SubscriptionConfig", "http://localhost/test/subscription", typeof(IContract), new WcfProxyDispatcher(), new PassThroughMessageFilter());
            db.CreateSubscription(subscription);

            IEnumerable<SubscriptionEndpoint> subscriptions = db.LoadSubscriptionEndpoints();
            Assert.AreEqual(1, subscriptions.Count());

            SubscriptionEndpoint savedSubscription = subscriptions.First();

            Assert.AreEqual(subscription.Name, savedSubscription.Name);
            Assert.AreEqual(subscription.Address, savedSubscription.Address);
            Assert.AreEqual(subscription.ConfigurationName, savedSubscription.ConfigurationName);
            Assert.AreEqual(subscription.ContractType, savedSubscription.ContractType);
            // TODO: Compare dispatchers
            Assert.AreEqual(subscription.Id, savedSubscription.Id);
            Assert.AreEqual(subscription.Filter.GetType(), savedSubscription.Filter.GetType());

            db.DeleteListener(listener.Id);
        }
Exemple #29
0
        protected override void OnStop()
        {
            // Clear out all the stuff we loaded
            foreach (Endpoint e in _managedEndpoints)
            {
                ListenerEndpoint     le = e as ListenerEndpoint;
                SubscriptionEndpoint se = e as SubscriptionEndpoint;

                if (le != null)
                {
                    Runtime.RemoveListener(le);
                }
                else if (se != null)
                {
                    Runtime.RemoveSubscription(se);
                }
                else
                {
                    throw new InvalidOperationException("Unexpected endpoint type encountered");
                }
            }
        }
 public MethodDispatcher(SubscriptionEndpoint endpoint)
     : base(endpoint)
 {
 }
 public WcfProxyDispatcher(SubscriptionEndpoint endpoint)
     : base(endpoint)
 {
 }
        ActionLookup initActionLookup(SubscriptionEndpoint endpoint)
        {
            ActionLookup lookup = null;

            if (_lookup != null) return _lookup;

            lookup = new ActionLookup();

            Dictionary<string, MethodInfo> actionLookup = new Dictionary<string, MethodInfo>();
            Dictionary<string, string> replyActionLookup = new Dictionary<string, string>();
            foreach (OperationDescription operation in ContractDescription.GetContract(endpoint.ContractType).Operations)
            {
                MessageDescription requestMessage = operation.Messages.Where(md => md.Direction == MessageDirection.Input).First();
                MessageDescription responseMessage = operation.Messages.Where(md => md.Direction == MessageDirection.Output).FirstOrDefault();

                if (requestMessage.Action == "*")
                {
                    _passThrough = true;
                }

                actionLookup.Add(requestMessage.Action, operation.SyncMethod);

                if (responseMessage != null)
                {
                    string replyAction = responseMessage.Action;

                    if (replyAction != null)
                    {
                        replyActionLookup.Add(requestMessage.Action, replyAction);
                    }
                }

            }
            lookup.MethodLookup = actionLookup;
            lookup.ReplyActionLookup = replyActionLookup;

            _lookup = lookup;

            return lookup;
        }
        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 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();
                }

            }
        }
        protected internal override void OnSubscriptionAdded(SubscriptionEndpoint endpoint)
        {
            base.OnSubscriptionAdded(endpoint);

            CreateSubscription(endpoint);
        }
Exemple #36
0
 public SubscriptionIntegrationTest(APIClientFixture fixture)
 {
     endpoint = fixture.SendOwlAPIClient.Subscription;
     CreatedSubcriptionIds = fixture.CreatedSubscriptionIds;
     ExistingProductIds    = fixture.ExistingProductIds;
 }
Exemple #37
0
 /// <summary>
 /// Create a subscription in the persistence store.
 /// </summary>
 /// <param name="subscription"></param>
 protected abstract void CreateSubscription(SubscriptionEndpoint subscription);
        public void UnhandledMessageFilter_Receives_Unhandled_Messages()
        {
            int handledCount = 0;
            int unhandledCount = 0;

            using (var runtime = Create.BinaryMsmqRuntime())
            {
                runtime.MessageDeliveryExpired += (o, msg) => System.Diagnostics.Trace.WriteLine("expired");

                runtime.UnhandledException += (ex, p) => System.Diagnostics.Trace.WriteLine("Unhandled Exception = "+ex);
                AutoResetEvent reset = new AutoResetEvent(false);

                SubscriptionEndpoint handled = new SubscriptionEndpoint(Guid.NewGuid(), "Handled", null, null, typeof(void), new ActionDispatcher((e, d) => {
                    Interlocked.Increment(ref handledCount);
                    System.Diagnostics.Trace.WriteLine("Handled Message = " + d.Message);
                    reset.Set();
                }), null);
                SubscriptionEndpoint unhandled = new SubscriptionEndpoint(Guid.NewGuid(), "Unhandled", null, null, typeof(void), new ActionDispatcher((e, d) => {
                    Interlocked.Increment(ref unhandledCount);
                    System.Diagnostics.Trace.WriteLine("Unhandled Message = " + d.Message);
                    reset.Set(); }),
                    new UnhandledMessageFilter(true, typeof(object)));

                runtime.Subscribe(handled);
                runtime.Subscribe(unhandled);

                runtime.Start();

                runtime.PublishOneWay(null, null, "Handled");

                // Make sure that unhandled doesn't get the message if it is handled
                if (reset.WaitOne(1000 * 10, true))
                {
                    Assert.AreEqual(1, handledCount);
                    Assert.AreEqual(0, unhandledCount);
                }
                else
                {
                    throw new InvalidOperationException("Waited too long");
                }

                runtime.RemoveSubscription(handled);

                handledCount = 0;
                unhandledCount = 0;

                runtime.PublishOneWay(null, null, "Unhandled");

                // Make sure that unhandled gets the message if it is handled
                if (reset.WaitOne(1000 * 10, true))
                {
                    Assert.AreEqual(0, handledCount);
                    Assert.AreEqual(1, unhandledCount);
                }
                else
                {
                    throw new InvalidOperationException("Waited too long");
                }

                runtime.Stop();
            }
        }
 /// <summary>
 /// Create a subscription in the persistence store.
 /// </summary>
 /// <param name="subscription"></param>
 protected abstract void CreateSubscription(SubscriptionEndpoint subscription);
 /// <summary>
 /// Delete a subscription from the persistence store.
 /// </summary>
 /// <param name="subscription"></param>
 protected abstract void DeleteSubscription(SubscriptionEndpoint subscription);
Exemple #41
0
 /// <summary>
 /// Delete a subscription from the persistence store.
 /// </summary>
 /// <param name="subscription"></param>
 protected abstract void DeleteSubscription(SubscriptionEndpoint subscription);
 public void Subscribe(SubscriptionEndpoint subscription)
 {
     Runtime.Subscribe(subscription);
 }
Exemple #43
0
 protected WcfDispatcher(SubscriptionEndpoint endpoint)
     : base(endpoint)
 {
 }
        protected internal override void OnSubscriptionRemoved(SubscriptionEndpoint endpoint)
        {
            base.OnSubscriptionRemoved(endpoint);

            DeleteSubscription(endpoint);
        }
        // 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 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 MethodDispatcher(SubscriptionEndpoint endpoint) : base(endpoint)
 {
 }
        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();
                }
            }
        }
Exemple #49
0
        protected internal override void OnSubscriptionAdded(SubscriptionEndpoint endpoint)
        {
            base.OnSubscriptionAdded(endpoint);

            CreateSubscription(endpoint);
        }
        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();
                }

            }
        }
 protected WcfDispatcher(SubscriptionEndpoint endpoint)
     : base(endpoint)
 {
 }
Exemple #52
0
        protected internal override void OnSubscriptionRemoved(SubscriptionEndpoint endpoint)
        {
            base.OnSubscriptionRemoved(endpoint);

            DeleteSubscription(endpoint);
        }