CreateAsync() public method

Creates a new connection.
public CreateAsync ( Address address ) : Task
address Address The address of remote endpoint to connect to.
return Task
コード例 #1
0
ファイル: Program.cs プロジェクト: Eclo/amqpnetlite
        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");
        }
コード例 #2
0
        async Task RunSampleAsync()
        {
            ConnectionFactory factory = new ConnectionFactory();
            factory.SASL.Profile = SaslProfile.External;

            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Address address = new Address(this.Namespace, 5671, null, null, "/", "amqps");
            var connection = await factory.CreateAsync(address);

            // before any operation can be performed, a token must be put to the $cbs node
            Trace.WriteLine(TraceLevel.Information, "Putting a token to the $cbs node...");
            await PutTokenAsync(connection);

            Trace.WriteLine(TraceLevel.Information, "Sending a message...");
            var session = new Session(connection);
            var sender = new SenderLink(session, "ServiceBus.Cbs:sender-link", this.Entity);
            await sender.SendAsync(new Message("test"));
            await sender.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Receiving the message back...");
            var receiver = new ReceiverLink(session, "ServiceBus.Cbs:receiver-link", this.Entity);
            var message = await receiver.ReceiveAsync();
            receiver.Accept(message);
            await receiver.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Closing the connection...");
            await session.CloseAsync();
            await connection.CloseAsync();
        }
        public async Task <IConnection> CreateAsync(Endpoint endpoint, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            cancellationToken.Register(() => _tcs.TrySetCanceled());

            var connectionFactory = new Amqp.ConnectionFactory();
            var connection        = await connectionFactory.CreateAsync(endpoint.Address, null, OnOpened).ConfigureAwait(false);

            connection.AddClosedCallback(OnClosed);
            await _tcs.Task.ConfigureAwait(false);

            connection.Closed -= OnClosed;
            return(new Connection(_loggerFactory, endpoint, connection, _messageIdPolicyFactory));
        }
コード例 #4
0
    static async Task<int> SslConnectionTestAsync(string brokerUrl, string address, string certfile)
    {
      try
      {
        ConnectionFactory factory = new ConnectionFactory();
        factory.TCP.NoDelay = true;
        factory.TCP.SendBufferSize = 16 * 1024;
        factory.TCP.SendTimeout = 30000;
        factory.TCP.ReceiveBufferSize = 16 * 1024;
        factory.TCP.ReceiveTimeout = 30000;
          
        factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
        factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certfile));
        factory.SSL.CheckCertificateRevocation = false;
          
        factory.AMQP.MaxFrameSize = 64 * 1024;
        factory.AMQP.HostName = "host.example.com";
        factory.AMQP.ContainerId = "amq.topic";
           
        Address sslAddress = new Address(brokerUrl);
        Connection connection = await factory.CreateAsync(sslAddress);

        Session session = new Session(connection);
        SenderLink sender = new SenderLink(session, "sender1", address);
        ReceiverLink receiver = new ReceiverLink(session, "helloworld-receiver", address);
           
        Message helloOut = new Message("Hello - using client cert");
        await sender.SendAsync(helloOut);

        Message helloIn = await receiver.ReceiveAsync();
        receiver.Accept(helloIn);

        await connection.CloseAsync();

        Console.WriteLine("{0}", helloIn.Body.ToString());

        Console.WriteLine("Press enter key to exit...");
        Console.ReadLine();
        return 0;
      }
      catch (Exception e)
      {
        Console.WriteLine("Exception {0}.", e);
        return 1;
      }
    }
コード例 #5
0
ファイル: Program.cs プロジェクト: rajeshganesh/amqpnetlite
        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");
        }
コード例 #6
0
            public async void Start(string address)
            {
                ConnectionFactory factory = new ConnectionFactory();

                try
                {
                    this.connection = await factory.CreateAsync(new Address(address));
                    this.session = new Session(connection);
                    this.sender = new SenderLink(session, "send-link", "control");
                    this.receiver = new ReceiverLink(session, "recv-link", "data");
                    this.receiver.Start(50, this.OnMessage);
                }
                catch
                {
                    this.Message = "err:2";
                }
            }
コード例 #7
0
ファイル: WebSocketTests.cs プロジェクト: ChugR/amqpnetlite
        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();
            }
        }
コード例 #8
0
ファイル: WebSocketTests.cs プロジェクト: ChugR/amqpnetlite
        public async Task WebSocketSendReceiveAsync()
        {
            if (Environment.GetEnvironmentVariable("CoreBroker") == "1")
            {
                // No Websocket listener on .Net Core
                return;
            }

            string testName = "WebSocketSendReceiveAsync";

            // assuming it matches the broker's setup and port is not taken
            Address wsAddress = new Address(address);
            int nMsgs = 50;

            ConnectionFactory connectionFactory = new ConnectionFactory(
                new TransportProvider[] { new WebSocketTransportFactory() });
            Connection connection = await connectionFactory.CreateAsync(wsAddress);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message();
                message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                await sender.SendAsync(message);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = await receiver.ReceiveAsync();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            await sender.CloseAsync();
            await receiver.CloseAsync();
            await session.CloseAsync();
            await connection.CloseAsync();
        }
コード例 #9
0
ファイル: TaskTests.cs プロジェクト: Eclo/amqpnetlite
        public async Task CustomTransportConfiguration()
        {
            string testName = "CustomTransportConfiguration";

            ConnectionFactory factory = new ConnectionFactory();
            factory.TCP.NoDelay = true;
            factory.TCP.SendBufferSize = 16 * 1024;
            factory.TCP.SendTimeout = 30000;
            factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            factory.AMQP.MaxFrameSize = 64 * 1024;
            factory.AMQP.HostName = "contoso.com";
            factory.AMQP.ContainerId = "container:" + testName;

            Address sslAddress = new Address("amqps://*****:*****@127.0.0.1:5671");
            Connection connection = await factory.CreateAsync(sslAddress);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            Message message = new Message("custom transport config");
            message.Properties = new Properties() { MessageId = testName };
            await sender.SendAsync(message);

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            Message message2 = await receiver.ReceiveAsync();
            Assert.IsTrue(message2 != null, "no message received");
            receiver.Accept(message2);

            await connection.CloseAsync();
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: Indifer/amqpnetlite
            protected Connection CreateConnection(Address address)
            {
                var factory = new ConnectionFactory();
                factory.BufferManager = this.bufferManager;
                factory.AMQP.MaxFrameSize = this.perfArgs.MaxFrameSize;
                if (address.Scheme.Equals("amqps", StringComparison.OrdinalIgnoreCase))
                {
                    factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                }

                return factory.CreateAsync(address).Result;
            }
コード例 #11
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();
            }
        }
コード例 #12
0
        public void ContainerHostSaslAnonymousTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            ListenerLink link = null;
            var linkProcessor = new TestLinkProcessor();
            linkProcessor.OnLinkAttached += a => link = a;
            this.host.RegisterLinkProcessor(linkProcessor);

            var factory = new ConnectionFactory();
            factory.SASL.Profile = SaslProfile.Anonymous;
            var connection = factory.CreateAsync(new Address(Address.Host, Address.Port, null, null, "/", Address.Scheme)).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 should be null");
        }
コード例 #13
0
            public async void Start()
            {
                Address address = new Address("amqp://*****:*****@192.168.1.120:5672");
                ConnectionFactory factory = new ConnectionFactory();

                try
                {
                    this.connection = await factory.CreateAsync(address);
                    this.session = new Session(connection);
                    this.sender = new SenderLink(session, "send-link", "control");
                    this.receiver = new ReceiverLink(session, "recv-link", "data");
                    this.receiver.Start(50, this.OnMessage);
                }
                catch
                {
                    this.Message = "err:2";
                }
            }
コード例 #14
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();
            }
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: helljai/amqpnetlite
            protected Connection CreateConnection(Address address)
            {
                var factory = new ConnectionFactory();
                if (address.Scheme.Equals("amqps", StringComparison.OrdinalIgnoreCase))
                {
                    factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                }

                return factory.CreateAsync(address).Result;
            }