Exemple #1
0
        static void Main(string[] args)
        {
            //Create host and register custom transport listener
            var uri = new Uri(address);
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.CustomTransports.Add("pipe", NamedPipeTransport.Listener);
            host.RegisterMessageProcessor(nodeName, new MessageProcessor());
            host.Open();
            Console.WriteLine("Listener: running");

            //Create factory with custom transport factory
            var factory = new ConnectionFactory(new TransportProvider[] { NamedPipeTransport.Factory });
            var connection = factory.CreateAsync(new Address(address)).GetAwaiter().GetResult();
            var session = new Session(connection);
            var sender = new SenderLink(session, "message-client", nodeName);
            Console.WriteLine("Client: sending a message");
            sender.Send(new Message("Hello Pipe!"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("Client: closed");

            host.Close();
            Console.WriteLine("Listener: closed");
        }
Exemple #2
0
        static void Main(string[] args)
        {
            string address = "amqp://*****:*****@127.0.0.1:5672";
            if (args.Length > 0)
            {
                address = args[0];
            }

            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            Uri addressUri = new Uri(address);
            ContainerHost host = new ContainerHost(new Uri[] { addressUri }, null, addressUri.UserInfo);
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            string requestProcessor = "request_processor";
            host.RegisterRequestProcessor(requestProcessor, new RequestProcessor());
            Console.WriteLine("Request processor is registered on {0}", requestProcessor);

            Console.WriteLine("Press enter key to exist...");
            Console.ReadLine();

            host.Close();
        }
Exemple #3
0
        static void Main(string[] args)
        {
            string address = "amqp://*****:*****@127.0.0.1:5672";
            if (args.Length > 0)
            {
                address = args[0];
            }

            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a));

            Uri addressUri = new Uri(address);
            ContainerHost host = new ContainerHost(new Uri[] { addressUri }, null, addressUri.UserInfo);
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            host.RegisterLinkProcessor(new LinkProcessor());
            Console.WriteLine("Link processor is registered.");

            Console.WriteLine("Start the client");
            var client = new Client(address);
            var task = Task.Run(() => client.Run());

            Console.WriteLine("Press enter key to exist...");
            Console.ReadLine();

            client.Close();
            host.Close();
        }
Exemple #4
0
        static void Main(string[] args)
        {
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (l, f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            string address = "amqps://localhost:5671";

            // start a host with custom SSL and SASL settings
            Console.WriteLine("Starting server...");
            Uri           addressUri = new Uri(address);
            ContainerHost host       = new ContainerHost(addressUri);
            var           listener   = host.Listeners[0];

            listener.SSL.Certificate = GetCertificate("localhost");
            listener.SSL.ClientCertificateRequired           = true;
            listener.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            listener.SASL.EnableExternalMechanism            = true;
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            string messageProcessor = "message_processor";

            host.RegisterMessageProcessor(messageProcessor, new MessageProcessor());
            Console.WriteLine("Message processor is registered on {0}", messageProcessor);

            Console.WriteLine("Starting client...");
            ConnectionFactory factory = new ConnectionFactory();

            factory.SSL.ClientCertificates.Add(GetCertificate("localhost"));
            factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            factory.SASL.Profile = SaslProfile.External;
            Console.WriteLine("Sending message...");
            Connection connection = factory.CreateAsync(new Address(address)).Result;
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "certificate-example-sender", "message_processor");

            sender.Send(new Message("hello world"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("client done");

            host.Close();
            Console.WriteLine("server stopped");
        }
Exemple #5
0
        public void ContainerHostX509PrincipalTest()
        {
            string           name    = MethodInfo.GetCurrentMethod().Name;
            string           address = "amqps://localhost:5676";
            X509Certificate2 cert    = GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
            ContainerHost    sslHost = new ContainerHost(new Uri(address));

            sslHost.Listeners[0].SSL.Certificate = cert;
            sslHost.Listeners[0].SSL.ClientCertificateRequired           = true;
            sslHost.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            sslHost.Listeners[0].SASL.EnableExternalMechanism            = true;
            ListenerLink link          = null;
            var          linkProcessor = new TestLinkProcessor();

            linkProcessor.OnLinkAttached += a => link = a;
            sslHost.RegisterLinkProcessor(linkProcessor);
            sslHost.Open();

            try
            {
                var factory = new ConnectionFactory();
                factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                factory.SSL.ClientCertificates.Add(cert);
                factory.SASL.Profile = SaslProfile.External;
                var connection = factory.CreateAsync(new Address(address)).Result;
                var session    = new Session(connection);
                var sender     = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();

                Assert.IsTrue(link != null, "link is null");
                var listenerConnection = (ListenerConnection)link.Session.Connection;
                Assert.IsTrue(listenerConnection.Principal != null, "principal is null");
                Assert.IsTrue(listenerConnection.Principal.Identity.AuthenticationType == "X509", "wrong auth type");

                X509Identity identity = (X509Identity)listenerConnection.Principal.Identity;
                Assert.IsTrue(identity.Certificate != null, "certificate is null");
            }
            finally
            {
                sslHost.Close();
            }
        }
        public async Task IsAuthorized_ReturnsFalse_WhenSessionConnectionClosedBeforeAuthorized()
        {
            ListenerLink   link              = null;
            var            authorized        = false;
            ILinkProcessor fakeLinkProcessor = Substitute.For <ILinkProcessor>();

            fakeLinkProcessor
            .When(instance => instance.Process(Arg.Any <AttachContext>()))
            .Do(c =>
            {
                AttachContext attachContext = c.ArgAt <AttachContext>(0);
                link = attachContext.Link;
                attachContext.Complete(new Error(ErrorCode.IllegalState)
                {
                    Description = "Test"
                });
            });

            ContainerHost host = TestAmqpHost.Open();

            try
            {
                host.RegisterLinkProcessor(fakeLinkProcessor);
                Connection connection = await host.ConnectAndAttachAsync();

                await connection.CloseAsync();

                await Task.Delay(500);

                var securityContext = new SecurityContext();
                securityContext.Authorize(link.Session.Connection);

                authorized = securityContext.IsAuthorized(link.Session.Connection);
            }
            finally
            {
                host.Close();
            }

            authorized.ShouldBeFalse();
        }
        public async Task IsAuthorized_ReturnsTrue_WhenSameConnectionAuthorizedTwice()
        {
            var            authorized        = false;
            var            links             = new List <ListenerLink>();
            ILinkProcessor fakeLinkProcessor = Substitute.For <ILinkProcessor>();

            fakeLinkProcessor
            .When(instance => instance.Process(Arg.Any <AttachContext>()))
            .Do(c =>
            {
                AttachContext attachContext = c.ArgAt <AttachContext>(0);
                links.Add(attachContext.Link);
                attachContext.Complete(new Error(ErrorCode.IllegalState)
                {
                    Description = "Test"
                });
            });

            ContainerHost host = TestAmqpHost.Open();

            try
            {
                host.RegisterLinkProcessor(fakeLinkProcessor);
                Connection connection = await host.ConnectAndAttachAsync(2);

                var securityContext = new SecurityContext();
                securityContext.Authorize(links[0].Session.Connection);
                securityContext.Authorize(links[1].Session.Connection);
                authorized = securityContext.IsAuthorized(links[1].Session.Connection);

                await connection.CloseAsync();
            }
            finally
            {
                host.Close();
            }

            authorized.ShouldBeTrue();
        }
            /// <summary>
            /// Async task for handling request
            /// </summary>
            /// <param name="messageContext">context of message</param>
            /// <returns>async task</returns>
            async Task ReplyAsync(MessageContext messageContext)
            {
                while (this.received < count)
                {
                    try
                    {
                        Message message = messageContext.Message;
                        Formatter.LogMessage(message, options);
                        this.received++;
                        messageContext.Complete();
                    }
                    catch (Exception exception)
                    {
                        Console.Error.WriteLine("ERROR: {{'cause': '{0}'}}", exception.Message);
                        Environment.Exit(ReturnCode.ERROR_OTHER);
                    }

                    await Task.Delay(500);
                }
                host.Close();
                Environment.Exit(ReturnCode.ERROR_SUCCESS);
            }
            public override void Run()
            {
                Uri addressUri = new Uri(this.Args.Address);
                X509Certificate2 certificate = Extensions.GetCertificate(addressUri.Scheme, addressUri.Host, this.Args.CertValue);
                ContainerHost    host        = new ContainerHost(new Uri[] { addressUri }, certificate, addressUri.UserInfo);

                foreach (var listener in host.Listeners)
                {
                    listener.BufferManager     = this.bufferManager;
                    listener.AMQP.MaxFrameSize = this.Args.MaxFrameSize;
                }

                host.Open();
                Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

                host.RegisterMessageProcessor(this.Args.Node, this);
                Console.WriteLine("Message processor is registered on {0}", this.Args.Node);

                this.Wait();

                host.Close();
            }
Exemple #10
0
        static void Main(string[] args)
        {
            //Create host and register message processor
            var uri = new Uri(Address);
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.RegisterMessageProcessor(MsgProcName, new MessageProcessor());
            host.Open();

            //Create client
            var connection = new Connection(new Address(Address));
            var session = new Session(connection);
            var sender = new SenderLink(session, "message-client", MsgProcName);

            //Send message with an object of custom type as the body
            var person = new Person() { EyeColor = "brown", Height = 175, Weight = 75 };
            sender.Send(new Message(person));

            sender.Close();
            session.Close();
            connection.Close();

            host.Close();
        }
        public void ContainerHostCustomTransportTest()
        {
            string        name    = "ContainerHostCustomTransportTest";
            string        address = "pipe://./" + name;
            ContainerHost host    = new ContainerHost(new Uri(address));

            host.CustomTransports.Add("pipe", NamedPipeTransport.Listener);
            host.RegisterMessageProcessor(name, new TestMessageProcessor());
            host.Open();

            try
            {
                var factory    = new ConnectionFactory(new TransportProvider[] { NamedPipeTransport.Factory });
                var connection = factory.CreateAsync(new Address(address)).GetAwaiter().GetResult();
                var session    = new Session(connection);
                var sender     = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();
            }
            finally
            {
                host.Close();
            }
        }
        public void ContainerHostWebSocketWildCardAddressTest()
        {
            var host = new ContainerHost(new string[] { "ws://+:28080/test/" });
            host.Listeners[0].SASL.EnablePlainMechanism("guest", "guest");
            host.RegisterMessageProcessor("q1", new TestMessageProcessor());
            host.Open();

            try
            {
                var connection = Connection.Factory.CreateAsync(new Address("ws://*****:*****@localhost:28080/test/")).Result;
                var session = new Session(connection);
                var sender = new SenderLink(session, "ContainerHostWebSocketWildCardAddressTest", "q1");
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();
            }
            catch
            {
                System.Diagnostics.Trace.WriteLine("If the test fails with System.Net.HttpListenerException (0x80004005): Access is denied");
                System.Diagnostics.Trace.WriteLine("Run the following command with admin privilege:");
                System.Diagnostics.Trace.WriteLine("netsh http add urlacl url=http://+:28080/test/ user=domain\\user");

                throw;
            }
            finally
            {
                host.Close();
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            //Create host and register message processor
            var uri  = new Uri(Address);
            var host = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            host.RegisterMessageProcessor(MsgProcName, new MessageProcessor());
            host.Open();

            //Create client
            var connection = new Connection(new Address(Address));
            var session    = new Session(connection);
            var sender     = new SenderLink(session, "message-client", MsgProcName);

            //Send message with an object of the base class as the body
            var person = new Person()
            {
                EyeColor = "brown", Height = 175, Weight = 75
            };

            SendMessage(sender, "Person", person);

            //Send message with an object of a derived class as the body
            var student = new Student()
            {
                GPA     = 4.8,
                Address = new ListAddress()
                {
                    Street = "123 Main St.", City = "Big Apple", State = "NY", Zip = "12345"
                }
            };

            SendMessage(sender, "Person", student);

            //Send message with an object of a derived class as the body
            var teacher = new Teacher()
            {
                Department = "Computer Science",
                Classes    = new List <string>()
                {
                    "CS101", "CS106", "CS210"
                }
            };

            SendMessage(sender, "Person", teacher);

            //Send message with nested simple map as the body
            var address = new InternationalAddress()
            {
                Address = new MapAddress()
                {
                    Street = "123 Main St.", City = "Big Apple", State = "NY", Zip = "12345"
                },
                Country = "usa"
            };

            SendMessage(sender, "InternationalAddress", address);

            //Send message with an AMQP value (the described list form of a student) as the body
            var described = new DescribedValue(
                new Symbol("samples.amqpnetlite:student"),
                new List()
            {
                80,
                6,
                "black",
                4.9,
                new DescribedValue(
                    new Symbol("PeerToPeer.CustomType.ListAddress"),
                    new List()
                {
                    "123 Main St.",
                    "Big Apple",
                    "NY",
                    "12345"
                }
                    )
            }
                );

            SendMessage(sender, "Person", described);

            //Send message with an AMQP value (simple map of an InternationalAddress) as the body
            var map = new Map()
            {
                { "street", "123 Main St." },
                { "city", "Big Apple" },
                { "state", "NY" },
                { "zip", "12345" }
            };

            SendMessage(sender, "MapAddress", map);

            //Send message with an AMQP value (simple map of an InternationalAddress) as the body
            var map2 = new Map()
            {
                { "address", new Map()
                  {
                      { "street", "123 Main St." }, { "city", "Big Apple" }, { "state", "NY" }, { "zip", "12345" }
                  } },
                { "country", "usa" }
            };

            SendMessage(sender, "InternationalAddress", map2);

            sender.Close();
            session.Close();
            connection.Close();

            host.Close();
        }
Exemple #14
0
 public void Close()
 {
     containerHost.Close();
 }
Exemple #15
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName      = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri    uri           = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int    code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);

            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                                            uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert  = null;
            X509Certificate clientCert   = null;
            ListenerLink    listenerLink = null;

            var linkProcessor = new TestLinkProcessor()
            {
                OnLinkAttached = c => listenerLink = c
            };
            var host = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            host.Listeners[0].SASL.EnableExternalMechanism            = true;
            host.Listeners[0].SSL.ClientCertificateRequired           = true;
            host.Listeners[0].SSL.CheckCertificateRevocation          = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return(true); };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return(true); };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties()
                                                             {
                                                                 MessageId = testName
                                                             } });

                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
Exemple #16
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri uri = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);
            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                    uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert = null;
            X509Certificate clientCert = null;
            ListenerLink listenerLink = null;

            var linkProcessor = new TestLinkProcessor() { OnLinkAttached = c => listenerLink = c };
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.Listeners[0].SASL.EnableExternalMechanism = true;
            host.Listeners[0].SSL.ClientCertificateRequired = true;
            host.Listeners[0].SSL.CheckCertificateRevocation = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return true; };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return true; };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });                
                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
 public void Dispose() => _host.Close();
Exemple #18
0
        static void Main(string[] args)
        {
            //Create host and register message processor
            var uri = new Uri(Address);
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.RegisterMessageProcessor(MsgProcName, new MessageProcessor());
            host.Open();

            //Create client
            var connection = new Connection(new Address(Address));
            var session = new Session(connection);
            var sender = new SenderLink(session, "message-client", MsgProcName);

            //Send message with an object of the base class as the body
            var person = new Person() { EyeColor = "brown", Height = 175, Weight = 75 };
            SendMessage(sender, "Person", person);

            //Send message with an object of a derived class as the body
            var student = new Student()
            {
                GPA = 4.8,
                Address = new ListAddress() { Street = "123 Main St.", City = "Big Apple", State = "NY", Zip = "12345" }
            };
            SendMessage(sender, "Person", student);

            //Send message with an object of a derived class as the body
            var teacher = new Teacher()
            {
                Department = "Computer Science",
                Classes = new List<string>() { "CS101", "CS106", "CS210" }
            };
            SendMessage(sender, "Person", teacher);

            //Send message with nested simple map as the body
            var address = new InternationalAddress()
            {
                Address = new MapAddress() { Street = "123 Main St.", City = "Big Apple", State = "NY", Zip = "12345" },
                Country = "usa"
            };
            SendMessage(sender, "InternationalAddress", address);

            //Send message with an AMQP value (the described list form of a student) as the body
            var described = new DescribedValue(
                new Symbol("samples.amqpnetlite:student"),
                new List()
                {
                    80,
                    6,
                    "black",
                    4.9,
                    new DescribedValue(
                        new Symbol("PeerToPeer.CustomType.ListAddress"),
                        new List()
                        {
                            "123 Main St.",
                            "Big Apple",
                            "NY",
                            "12345"
                        }
                    )
                }
            );
            SendMessage(sender, "Person", described);

            //Send message with an AMQP value (simple map of an InternationalAddress) as the body
            var map = new Map()
            {
                { "street", "123 Main St." },
                { "city", "Big Apple" },
                { "state", "NY" },
                { "zip", "12345" }
            };
            SendMessage(sender, "MapAddress", map);

            //Send message with an AMQP value (simple map of an InternationalAddress) as the body
            var map2 = new Map()
            {
                { "address", new Map() { { "street", "123 Main St." }, { "city", "Big Apple" }, { "state", "NY" }, { "zip", "12345" } } },
                { "country", "usa" }
            };
            SendMessage(sender, "InternationalAddress", map2);

            sender.Close();
            session.Close();
            connection.Close();

            host.Close();
        }
        public void ContainerHostCloseTest()
        {
            string name = "ContainerHostCloseTest";
            Uri    uri  = new Uri("amqp://*****:*****@localhost:15673");

            ContainerHost h = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            h.Open();
            h.RegisterMessageProcessor(name, new TestMessageProcessor());

            //Create a client to send data to the host message processor
            var closedEvent = new ManualResetEvent(false);
            var connection  = new Connection(new Address(uri.AbsoluteUri));

            connection.Closed += (AmqpObject obj, Error error) =>
            {
                closedEvent.Set();
            };

            var session = new Session(connection);
            var sender  = new SenderLink(session, "sender-link", name);

            //Send one message while the host is open
            sender.Send(new Message("Hello"), SendTimeout);

            //Close the host. this should close existing connections
            h.Close();

            Assert.IsTrue(closedEvent.WaitOne(10000), "connection is not closed after host is closed.");

            try
            {
                sender.Send(new Message("test"));
                Assert.IsTrue(false, "exception not thrown");
            }
            catch (AmqpException exception)
            {
                Assert.IsTrue(exception.Error != null, "Error is null");
                Assert.AreEqual((Symbol)ErrorCode.ConnectionForced, exception.Error.Condition, "Wrong error code");
            }

            connection.Close();

            // Reopen the host and send again
            // Use a different port as on some system the port is not released immediately
            uri = new Uri("amqp://*****:*****@localhost:15674");
            h   = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);
            h.RegisterMessageProcessor(name, new TestMessageProcessor());
            h.Open();

            connection = new Connection(new Address(uri.AbsoluteUri));
            session    = new Session(connection);
            sender     = new SenderLink(session, "sender-link", name);
            sender.Send(new Message("Hello"), SendTimeout);
            connection.Close();

            h.Close();
        }
Exemple #20
0
            public override void Run()
            {
                Uri addressUri = new Uri(this.Args.Address);
                X509Certificate2 certificate = Extensions.GetCertificate(addressUri.Scheme, addressUri.Host, this.Args.CertValue);
                ContainerHost host = new ContainerHost(new Uri[] { addressUri }, certificate, addressUri.UserInfo);
                host.Open();
                Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

                host.RegisterMessageProcessor(this.Args.Node, this);
                Console.WriteLine("Message processor is registered on {0}", this.Args.Node);

                this.Wait();

                host.Close();
            }
Exemple #21
0
 public override void Stop()
 {
     _cancellationRegistration.Dispose();
     _host?.Close();
 }
Exemple #22
0
        public static async Task TestMany()
        {
            const string url          = "amqp://*****:*****@127.0.0.1:5672";
            const string requestUrl   = "request_processor";
            const string receiverName = "client-request-receiver";
            const string sendername   = "client-request-sender";

            using (var cts = new CancellationTokenSource())
            {
                await Task.WhenAll(
                    Task.Run(() =>
                {
                    var uri  = new Uri(url);
                    var host = new ContainerHost(new[] { uri }, null, uri.UserInfo);
                    Console.WriteLine($"opening host");
                    host.Open();
                    try
                    {
                        host.RegisterRequestProcessor(requestUrl, new RequestProcessor());
                        Console.WriteLine($"wait begin");
                        cts.Token.WaitHandle.WaitOne();
                    }
                    finally
                    {
                        host.Close();
                    }
                    Console.WriteLine($"svr thread done");
                })
                    ,
                    Task.Run(async() =>
                {
                    await Task.Delay(1000).ConfigureAwait(false);
                    var con = new Connection(new Address(url));
                    try
                    {
                        var session = new Session(con);
                        string replyTo = "client-abc";
                        var recvAttach = new Attach()
                        {
                            Source = new Source()
                            {
                                Address = requestUrl
                            },
                            Target = new Target()
                            {
                                Address = replyTo
                            }
                        };
                        var recver = new ReceiverLink(session, receiverName, recvAttach, (link, attach) =>
                        {
                            Console.WriteLine($"{link},{attach}");
                        });
                        recver.Start(300);
                        var sender = new SenderLink(session, sendername, requestUrl);
                        Console.WriteLine($"{sender.IsClosed}");
                        for (int i = 0; i < 100; i++)
                        {
                            var msg = new Message($"clientmessage{i}");
                            msg.Properties = new Properties()
                            {
                                MessageId = "command-request",
                                ReplyTo = replyTo
                            };
                            msg.ApplicationProperties = new ApplicationProperties();
                            msg.ApplicationProperties["offset"] = i;
                            sender.Send(msg);
                            var response = recver.Receive();
                            recver.Accept(response);
                            Console.WriteLine($"{response.Properties}, {response.Body}");
                        }
                    }
                    finally
                    {
                        con.Close();
                    }
                })
                    .ContinueWith(t =>
                {
                    Console.WriteLine($"cancelling:{t.Status}");
                    cts.Cancel();
                    if (t.IsCanceled)
                    {
                        Console.WriteLine($"a");
                        throw new AggregateException(t.Exception);
                    }
                    if (t.IsFaulted)
                    {
                        Console.WriteLine($"b");
                        throw new AggregateException(t.Exception);
                    }
                })
                    ).ConfigureAwait(false); // Task.WhenAll
            }
        }
        public void ContainerHostCloseTest()
        {
            string name = "ContainerHostCloseTest";
            Uri uri = new Uri("amqp://*****:*****@localhost:15673");

            ContainerHost h = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            h.Open();
            h.RegisterMessageProcessor(name, new TestMessageProcessor());

            //Create a client to send data to the host message processor
            var closedEvent = new ManualResetEvent(false);
            var connection = new Connection(new Address(uri.AbsoluteUri));
            connection.Closed += (AmqpObject obj, Error error) =>
            {
                closedEvent.Set();
            };

            var session = new Session(connection);
            var sender = new SenderLink(session, "sender-link", name);

            //Send one message while the host is open
            sender.Send(new Message("Hello"), SendTimeout);

            //Close the host. this should close existing connections
            h.Close();

            Assert.IsTrue(closedEvent.WaitOne(10000), "connection is not closed after host is closed.");

            try
            {
                sender.Send(new Message("test"));
                Assert.IsTrue(false, "exception not thrown");
            }
            catch (AmqpException exception)
            {
                Assert.IsTrue(exception.Error != null, "Error is null");
                Assert.AreEqual((Symbol)ErrorCode.ConnectionForced, exception.Error.Condition, "Wrong error code");
            }

            connection.Close();

            // Reopen the host and send again
            // Use a different port as on some system the port is not released immediately
            uri = new Uri("amqp://*****:*****@localhost:15674");
            h = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            h.RegisterMessageProcessor(name, new TestMessageProcessor());
            h.Open();

            connection = new Connection(new Address(uri.AbsoluteUri));
            session = new Session(connection);
            sender = new SenderLink(session, "sender-link", name);
            sender.Send(new Message("Hello"), SendTimeout);
            connection.Close();

            h.Close();
        }
        public void ContainerHostCustomTransportTest()
        {
            string name = "ContainerHostCustomTransportTest";
            string address = "pipe://./" + name;
            ContainerHost host = new ContainerHost(new Uri(address));
            host.CustomTransports.Add("pipe", NamedPipeTransport.Listener);
            host.RegisterMessageProcessor(name, new TestMessageProcessor());
            host.Open();

            try
            {
                var factory = new ConnectionFactory(new TransportProvider[] { NamedPipeTransport.Factory });
                var connection = factory.CreateAsync(new Address(address)).GetAwaiter().GetResult();
                var session = new Session(connection);
                var sender = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();
            }
            finally
            {
                host.Close();
            }
        }
Exemple #25
0
        public static async Task ReqRepTest(int LoopNum)
        {
            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            const string url          = "amqp://*****:*****@127.0.0.1:5672";
            const string requestUrl   = "request_processor";
            const string receiverName = "client-request-receiver";
            const string sendername   = "client-request-sender";

            using (var cts = new CancellationTokenSource())
                using (var connected = new ManualResetEventSlim())
                    using (var started = new ManualResetEventSlim())
                    {
                        await Task.WhenAll(
                            Task.Run(() =>
                        {
                            var uri  = new Uri(url);
                            var host = new ContainerHost(new[] { uri }, null, uri.UserInfo);
                            host.Open();
                            try
                            {
                                host.RegisterRequestProcessor(requestUrl, new RequestProcessor());
                                Console.WriteLine($"wait begin");
                                cts.Token.WaitHandle.WaitOne();
                            }
                            finally
                            {
                                host.Close();
                            }
                            Console.WriteLine($"svr thread done");
                        })
                            ,
                            Task.Run(async() =>
                        {
                            await Task.Yield();
                            var con = new Connection(new Address(url));
                            try
                            {
                                var session = new Session(con);
                                string replyTo = "client-abc";
                                var recvAttach = new Attach()
                                {
                                    Source = new Source()
                                    {
                                        Address = requestUrl
                                    },
                                    Target = new Target()
                                    {
                                        Address = replyTo
                                    }
                                };
                                var recver = new ReceiverLink(session, receiverName, recvAttach, (link, attach) =>
                                {
                                    Console.WriteLine($"{link},{attach}");
                                });
                                recver.Start(300);
                                var sender = new SenderLink(session, sendername, new Target()
                                {
                                    Address = requestUrl
                                }, (obj, ev) =>
                                {
                                    connected.Set();
                                });
                                connected.Wait();
                                var beginTime = sw.Elapsed;
                                Console.WriteLine($"begin sending({sw.Elapsed})");
                                for (int i = 0; i < LoopNum; i++)
                                {
                                    var msg = new Message($"clientmessage{i}");
                                    msg.Properties = new Properties()
                                    {
                                        MessageId = "command-request",
                                        ReplyTo = replyTo
                                    };
                                    msg.ApplicationProperties = new ApplicationProperties();
                                    msg.ApplicationProperties["offset"] = i;
                                    sender.Send(msg);
                                    var response = recver.Receive();
                                    recver.Accept(response);
                                }
                                var endTime = sw.Elapsed;
                                Console.WriteLine($"elapsed(amqp):({sw.Elapsed}, rps={LoopNum/endTime.Subtract(beginTime).TotalSeconds}");
                            }
                            finally
                            {
                                con.Close();
                            }
                        })
                            .ContinueWith(t =>
                        {
                            Console.WriteLine($"cancelling:{t.Status}");
                            cts.Cancel();
                            if (t.IsCanceled)
                            {
                                Console.WriteLine($"a");
                                throw new AggregateException(t.Exception);
                            }
                            if (t.IsFaulted)
                            {
                                Console.WriteLine($"b");
                                throw new AggregateException(t.Exception);
                            }
                        })
                            ).ConfigureAwait(false); // Task.WhenAll
                    }
        }
        public void ContainerHostX509PrincipalTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            string address = "amqps://localhost:5676";
            X509Certificate2 cert = GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
            ContainerHost sslHost = new ContainerHost(new Uri(address));
            sslHost.Listeners[0].SSL.Certificate = cert;
            sslHost.Listeners[0].SSL.ClientCertificateRequired = true;
            sslHost.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            sslHost.Listeners[0].SASL.EnableExternalMechanism = true;
            ListenerLink link = null;
            var linkProcessor = new TestLinkProcessor();
            linkProcessor.OnLinkAttached += a => link = a;
            sslHost.RegisterLinkProcessor(linkProcessor);
            sslHost.Open();

            try
            {
                var factory = new ConnectionFactory();
                factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                factory.SSL.ClientCertificates.Add(cert);
                factory.SASL.Profile = SaslProfile.External;
                var connection = factory.CreateAsync(new Address(address)).Result;
                var session = new Session(connection);
                var sender = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();

                Assert.IsTrue(link != null, "link is null");
                var listenerConnection = (ListenerConnection)link.Session.Connection;
                Assert.IsTrue(listenerConnection.Principal != null, "principal is null");
                Assert.IsTrue(listenerConnection.Principal.Identity.AuthenticationType == "X509", "wrong auth type");

                X509Identity identity = (X509Identity)listenerConnection.Principal.Identity;
                Assert.IsTrue(identity.Certificate != null, "certificate is null");
            }
            finally
            {
                sslHost.Close();
            }
        }
Exemple #27
0
        static void Main(string[] args)
        {
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a));

            string address = "amqps://localhost:5671";

            // start a host with custom SSL and SASL settings
            Console.WriteLine("Starting server...");
            Uri addressUri = new Uri(address);
            ContainerHost host = new ContainerHost(addressUri);
            var listener = host.Listeners[0];
            listener.SSL.Certificate = GetCertificate("localhost");
            listener.SSL.ClientCertificateRequired = true;
            listener.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            listener.SASL.EnableExternalMechanism = true;
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            string messageProcessor = "message_processor";
            host.RegisterMessageProcessor(messageProcessor, new MessageProcessor());
            Console.WriteLine("Message processor is registered on {0}", messageProcessor);

            Console.WriteLine("Starting client...");
            ConnectionFactory factory = new ConnectionFactory();
            factory.SSL.ClientCertificates.Add(GetCertificate("localhost"));
            factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            factory.SASL.Profile = SaslProfile.External;
            Console.WriteLine("Sending message...");
            Connection connection = factory.CreateAsync(new Address(address)).Result;
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "certificate-example-sender", "message_processor");
            sender.Send(new Message("hello world"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("client done");

            host.Close();
            Console.WriteLine("server stopped");
        }
Exemple #28
0
            public override void Run()
            {
                Uri addressUri = new Uri(this.Args.Address);
                X509Certificate2 certificate = Extensions.GetCertificate(addressUri.Scheme, addressUri.Host, this.Args.CertValue);
                ContainerHost host = new ContainerHost(new Uri[] { addressUri }, certificate, addressUri.UserInfo);
                foreach (var listener in host.Listeners)
                {
                    listener.BufferManager = this.bufferManager;
                    listener.AMQP.MaxFrameSize = this.Args.MaxFrameSize;
                }

                host.Open();
                Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

                host.RegisterMessageProcessor(this.Args.Node, this);
                Console.WriteLine("Message processor is registered on {0}", this.Args.Node);

                this.Wait();

                host.Close();
            }