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(); }
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(); }
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"); }
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(); } }
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(); }
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(); } }
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); }
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(); }
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; }
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(); }
/// <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; }
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(); }
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"); }
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."); }
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(); }
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); }
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)); }
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; }
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()); }
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(); }
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); }
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(); } }
private void Cleanup() { var temp = Interlocked.Exchange(ref inboundHost, null); if (temp != null) { temp.Close(); } this.inboundHost = null; }
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); }
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(); }
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(); }
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(); }
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(); }
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)); }
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"); }
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); }
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 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(); }
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 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(); } }
public void Initialize() { this.host = new ContainerHost(new List<Uri>() { Uri }, null, Uri.UserInfo); this.host.Open(); }
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 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(); }
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(); } }
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 = 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(); }