Пример #1
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();
        }
Пример #2
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();
        }
Пример #3
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");
        }
Пример #4
0
        public static async Task <Message> ProcessManagementRequestAsync(Message message, ManagementRequestProcessor processor)
        {
            ContainerHost host = Open();

            try
            {
                host.RegisterRequestProcessor("$management", processor);
                Connection connection = await host.ConnectAsync();

                var session = new Session(connection);
                try
                {
                    return(await session.SendControlRequestAsync("$management", message));
                }
                finally
                {
                    await session.CloseAsync();

                    await connection.CloseAsync();
                }
            }
            finally
            {
                host.Close();
            }
        }
Пример #5
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();
        }
Пример #6
0
        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();
            }
        }
Пример #7
0
        public static async Task <IDictionary <string, object> > ProcessCbsRequestAsync(string messageId, CbsRequestProcessor processor)
        {
            var           responseProperties = new Dictionary <string, object>();
            ContainerHost host = Open();

            try
            {
                host.RegisterRequestProcessor("$cbs", processor);
                Connection connection = await host.ConnectAsync();

                var session = new Session(connection);
                try
                {
                    Message response = await session.SendCbsRequestAsync(messageId);

                    responseProperties["CorrelationId"] = response.Properties.CorrelationId;
                    responseProperties["status-code"]   = response.ApplicationProperties["status-code"];
                }
                finally
                {
                    await session.CloseAsync();

                    await connection.CloseAsync();
                }
            }
            finally
            {
                host.Close();
            }
            return(responseProperties);
        }
Пример #8
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);

            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();
        }
Пример #9
0
        private void Cleanup()
        {
            var temp = Interlocked.Exchange(ref inboundHost, null);

            if (temp != null)
            {
                foreach (InternalMessageProcessor p in listeners.Values)
                {
                    temp.UnregisterMessageProcessor(p.TargetAddress);
                }
                listeners.Clear();

                foreach (InternalSourceProcessor p in sources.Values)
                {
                    p.MessageQueue.Clear();
                    p.MessageQueue.Close();
                    temp.UnregisterMessageProcessor(p.SourceAddress);
                }
                sources.Clear();

                temp.UnregisterRequestProcessor(RequestHandle);
                temp.Close();
            }

            this.inboundHost = null;
        }
Пример #10
0
        static void Main(string[] args)
        {
            Address address = new Address("amqp://*****:*****@127.0.0.1:5672");

            if (args.Length > 0)
            {
                address = new Address(args[0]);
            }

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

            ContainerHost host = new ContainerHost(address);

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

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

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

            host.Close();
        }
Пример #11
0
 /// <summary>
 /// Constructor of MessageProcessor
 /// </summary>
 /// <param name="options">receiver options</param>
 /// <param name="host">container host listener</param>
 public MessageProcessor(ReceiverOptions options, ContainerHost host)
 {
     this.received = 0;
     this.options  = options;
     this.count    = options.MsgCount;
     this.host     = host;
 }
Пример #12
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 = (l, 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);

            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 exit...");
            Console.ReadLine();

            client.Close();
            host.Close();
        }
Пример #13
0
        static void Main(string[] args)
        {
            //Create host and register custom transport listener
            var host = new ContainerHost(new Address(address));

            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");
        }
Пример #14
0
        public static void StartHost()
        {
            if (Host != null)
            {
                throw new InvalidOperationException("Host is already running.");
            }

            // Create listener and start it.
            Uri addressUri = new Uri(address);

            Host = new ContainerHost(addressUri);
            Host.Listeners[0].SSL.Certificate = GetSslCertificate();
            Host.Listeners[0].SASL.EnableAnonymousMechanism = true;
            // These next 2 lines are for test servers only!
            //Host.Listeners[0].SSL.ClientCertificateRequired = true;
            //Host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;

            // TODO: implement a max concurrent connections
            Host.Open();
            System.Console.WriteLine($"MessageBroker Host is listenening on {addressUri.Host}:{addressUri.Port}");

            // Attach custom logic when links attempt to attach to the host
            Host.RegisterLinkProcessor(new LinkProcessor());
            System.Console.WriteLine($"MessageBroker link processor is now registered.");
        }
Пример #15
0
        static void Main(string [] args)
        {
            string address = "amqp://*****:*****@10.67.1.82:5672";

            if (args.Length > 0)
            {
                address = args [0];
            }

            Uri           addressUri = new Uri(address);
            ContainerHost host       = new ContainerHost(new Uri [] { addressUri }, null, addressUri.UserInfo);

            host.Open();
            Console.WriteLine("Raspberry Pi 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 exit...");
            Console.ReadLine();

            host.Close();
        }
Пример #16
0
 public void Initialize()
 {
     this.host = new ContainerHost(new List <Uri>()
     {
         Uri
     }, null, Uri.UserInfo);
     this.host.Open();
 }
 public TestContainerHost(Endpoint endpoint, IHandler handler = null)
 {
     Endpoint = endpoint;
     _host    = new ContainerHost(endpoint.Address);
     _host.Listeners[0].HandlerFactory = listener => handler;
     _linkProcessor = new TestLinkProcessor();
     _host.RegisterLinkProcessor(_linkProcessor);
 }
Пример #18
0
        public static async Task <Connection> ConnectAsync(this ContainerHost host)
        {
            var factory = new ConnectionFactory();

            factory.SASL.Profile = SaslProfile.Anonymous;
            var address = new Address("localhost", host.Listeners[0].Address.Port, null, null, "/", "amqp");

            return(await factory.CreateAsync(address));
        }
Пример #19
0
        public void Open(string cfxHandle, Uri requestUri, X509Certificate2 certificate = null)
        {
            IsOpen = false;
            if (string.IsNullOrEmpty(cfxHandle))
            {
                throw new ArgumentException("You must supply a CFX Handle");
            }

            this.CFXHandle = cfxHandle;
            RequestUri     = requestUri;

            inboundHost = new ContainerHost(RequestUri);

            if (!string.IsNullOrWhiteSpace(RequestUri.UserInfo))
            {
                inboundHost = new ContainerHost(new Uri[] { RequestUri }, null, RequestUri.UserInfo);
            }
            else
            {
                inboundHost = new ContainerHost(RequestUri);
            }

            var listener = inboundHost.Listeners[0];

            if (string.Compare(requestUri.Scheme, "amqps", true) == 0)
            {
                listener.SSL.Certificate = certificate;
                listener.SSL.ClientCertificateRequired           = true;
                listener.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                listener.SASL.EnableExternalMechanism            = true;
            }

            if (string.IsNullOrWhiteSpace(RequestUri.UserInfo))
            {
                listener.SASL.EnableExternalMechanism  = false;
                listener.SASL.EnableAnonymousMechanism = true;
            }
            else
            {
                listener.SASL.EnableExternalMechanism  = true;
                listener.SASL.EnableAnonymousMechanism = false;
                //listener.SASL.EnablePlainMechanism(RequestUri.UserInfo.Split(':')[0], RequestUri.UserInfo.Split(':')[1]);
            }

            listener.SSL.Certificate = certificate;
            listener.SSL.ClientCertificateRequired           = true;
            listener.SSL.ClientCertificateRequired           = false;
            listener.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;

            inboundHost.Open();
            AppLog.Info($"Container host is listening on {RequestUri.Host}:{RequestUri.Port}.  User {requestUri.UserInfo}");

            inboundHost.RegisterRequestProcessor(RequestHandle, new InternalRequestProcessor(this));
            AppLog.Info($"Request processor is registered on {RequestHandle}");
            IsOpen = true;
        }
Пример #20
0
        public void Setup()
        {
            string address = "amqp://*****:*****@127.0.0.1:5672";

            Uri           addressUri = new Uri(address);
            ContainerHost host       = new ContainerHost(new[] { addressUri }, null, addressUri.UserInfo);

            host.Open(); // Throws socketexception - AddressAlreadyInUse - only one usage of each socket address (protocol/network address/port) is normally permitted
            host.RegisterLinkProcessor(new LinkProcessor());
        }
Пример #21
0
        public void ClassInitialize()
        {
            // pick a port other than 5762 so that it doesn't conflict with the test broker
            this.Uri = new Uri("amqp://*****:*****@localhost:15672");

            this.host = new ContainerHost(new List<Uri>() { this.Uri }, null, this.Uri.UserInfo);
            this.host.Listeners[0].SASL.EnableExternalMechanism = true;
            this.host.Listeners[0].SASL.EnableAnonymousMechanism = true;
            this.host.Open();
        }
Пример #22
0
        public static ContainerHost Open(int preferredPort = 0)
        {
            var port    = preferredPort == 0 ? TestTcpUtils.FindFreePort() : preferredPort;
            var address = new Address($"amqp://localhost:{port}");
            var host    = new ContainerHost(address);

            host.Listeners[0].SASL.EnableExternalMechanism  = true;
            host.Listeners[0].SASL.EnableAnonymousMechanism = true;
            host.Open();
            return(host);
        }
Пример #23
0
        public void ContainerHostX509PrincipalTest()
        {
            string           name    = "ContainerHostX509PrincipalTest";
            string           address = "amqps://localhost:5676";
            X509Certificate2 cert    = null;

            try
            {
                cert = GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
            }
            catch (PlatformNotSupportedException)
            {
                // Unix machine, ignored
                return;
            }

            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();
            }
        }
Пример #24
0
        private void Cleanup()
        {
            var temp = Interlocked.Exchange(ref inboundHost, null);

            if (temp != null)
            {
                temp.Close();
            }

            this.inboundHost = null;
        }
Пример #25
0
        public static async Task <Session> OpenAndLinkProcessorAsync(ILinkProcessor linkProcessor)
        {
            ContainerHost host = Open();

            host.RegisterLinkProcessor(linkProcessor);
            Connection connection = await host.ConnectAsync();

            var session = new Session(connection);

            session.AddClosedCallback((_, __) => host.Close());
            return(session);
        }
Пример #26
0
        public void ContainerHostCloseTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;

            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());

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

            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
            this.host.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
            this.host = new ContainerHost(new List <Uri>()
            {
                Uri
            }, null, Uri.UserInfo);
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());
            this.host.Open();

            connection = new Connection(Address);
            session    = new Session(connection);
            sender     = new SenderLink(session, "sender-link", name);
            sender.Send(new Message("Hello"), SendTimeout);
            connection.Close();
        }
Пример #27
0
        public void ClassInitialize()
        {
            // pick a port other than 5762 so that it doesn't conflict with the test broker
            this.Uri = new Uri("amqp://*****:*****@localhost:15672");

            this.host = new ContainerHost(new List <Uri>()
            {
                this.Uri
            }, null, this.Uri.UserInfo);
            this.host.Listeners[0].SASL.EnableExternalMechanism  = true;
            this.host.Listeners[0].SASL.EnableAnonymousMechanism = true;
            this.host.Open();
        }
Пример #28
0
            public override void Run()
            {
                Uri           addressUri = new Uri(this.Args.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.RegisterMessageProcessor(this.Args.Node, this);
                Console.WriteLine("Message processor is registered on {0}", this.Args.Node);

                this.Wait();

                host.Close();
            }
Пример #29
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();
            }
Пример #30
0
        public Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            var serviceEndpoint = this.context.CodePackageActivationContext.GetEndpoint("AMQPEndpoint");
            var port            = serviceEndpoint.Port;

            this.listeningAddress = string.Format(CultureInfo.InvariantCulture, "amqp://*****:*****@+:{0}/{1}/{2}", port, this.context.PartitionId, this.context.ReplicaId);
            this.publishAddress   = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN);
            var addressUri = new Uri(this.publishAddress);

            this.host = new ContainerHost(new[] { addressUri }, null, addressUri.UserInfo);
            this.host.Open();
            var requestProcessor = "request_processor";

            this.host.RegisterRequestProcessor(requestProcessor, new DummyCollector(this.context, this.stateManager));
            return(Task.FromResult(this.publishAddress));
        }
Пример #31
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");
        }
Пример #32
0
        public static async Task <Connection> ConnectAndAttachAsync(this ContainerHost host, int nSessions = 1)
        {
            Connection connection = await host.ConnectAsync();

            try
            {
                IEnumerable <SenderLink> links = Enumerable
                                                 .Range(1, nSessions)
                                                 .Select(i => new SenderLink(new Session(connection), "A" + i, "A" + i));

                Parallel.ForEach(links, link => link.Send(new Message("msg1"), TimeSpan.FromMilliseconds(500)));
            }
            catch
            {
                // ignore
            }
            return(connection);
        }
Пример #33
0
        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();
        }
Пример #34
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");
        }
Пример #35
0
        public BaseHostTest()
        {
            random = new Random();
            var start = random.Next(10000, Int16.MaxValue);
            var port  = GetAvailablePort(start);

            receiverSettings = new DomainEventReceiverSettings()
            {
                Protocol   = "amqp",
                PolicyName = "guest",
                Key        = "guest",
                Namespace  = $"localhost:{port}",
                Queue      = "queue",
                AppName    = "unittest" + port.ToString()
            };

            publisterSettings = new DomainEventPublisherSettings()
            {
                Protocol   = "amqp",
                PolicyName = "guest",
                Key        = "guest",
                Namespace  = $"localhost:{port}",
                Topic      = "/exchange/test/",
                AppName    = "unittest" + port.ToString()
            };
            Address = new Address(publisterSettings.ConnectionString);

            host = new ContainerHost(Address);
            host.Listeners[0].SASL.EnableExternalMechanism  = true;
            host.Listeners[0].SASL.EnableAnonymousMechanism = true;
            host.Open();

            eventTypes = new Dictionary <string, Type> {
                { typeof(TestEvent).FullName, typeof(TestEvent) }
            };

            var services = new ServiceCollection();

            provider = services.BuildServiceProvider();
        }
Пример #36
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();
        }
Пример #37
0
        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();
        }
Пример #38
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();
            }
Пример #39
0
        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();
            }
        }
Пример #40
0
 public void Initialize()
 {
     this.host = new ContainerHost(new List<Uri>() { Uri }, null, Uri.UserInfo);
     this.host.Open();
 }
Пример #41
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();
            }
        }
Пример #42
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();
            }
Пример #43
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();
            }
        }
Пример #44
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();
        }
Пример #45
0
        public void ContainerHostCloseTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());

            //Create a client to send data to the host message processor
            var closedEvent = new ManualResetEvent(false);
            var connection = new Connection(Address);
            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
            this.host.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
            this.host = new ContainerHost(new List<Uri>() { Uri }, null, Uri.UserInfo);
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());
            this.host.Open();

            connection = new Connection(Address);
            session = new Session(connection);
            sender = new SenderLink(session, "sender-link", name);
            sender.Send(new Message("Hello"), SendTimeout);
            connection.Close();
        }
Пример #46
0
        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();
            }
        }