public async Task StartAsync(CancellationToken cancellationToken) { // delay startup to let broker start first var delay = TimeSpan.FromSeconds(10); Console.WriteLine($"Starting in {delay}"); await Task.Delay(delay, cancellationToken); // get env variables _brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616"; _serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "MyService"; Console.WriteLine($"Starting {_serviceName}, connecting to broker {_brokerUri}"); // create singleton ServiceBus var serviceBus = ServiceBus.Configure() .WithActiveMQEndpoints <IServiceMessage1>() // you can use different transports for each service .Named(_serviceName) // used to prefix AMQ topic names .UsingQueueFor <ICommand>() // optional, default is topic .ConnectToBroker(_brokerUri) .WithCredentials("admin", "admin") .SerializedAsJson() // you can use different serialization formats for each service .AsServer() // will subscribe to commands and requests, and publish events and responses .UsingConsoleLogging() // optional logging extensions available .Create(); // subscribe to commands and publish events _subscription = serviceBus.Commands.OfType <Command1>().Subscribe(async cmd => { await serviceBus.PublishAsync(new Event1 { Data = cmd.Data }); }); }
public void VerifyMessageTypesMappedEntit() { IEnumerable <MessageTypeMessagingEntityMappingDetails> configuredMessageTypePathMappings = null; _mockMessagingEntityVerifier.Setup(mev => mev.EnsureMessagingEntitiesExist(It.IsAny <IEnumerable <MessageTypeMessagingEntityMappingDetails> >())) .Callback <IEnumerable <MessageTypeMessagingEntityMappingDetails> >(mtpm => configuredMessageTypePathMappings = mtpm); ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .UsingQueueFor <ICommand>("commands", MessagingEntityCreationOptions.VerifyAlreadyExists) .UsingQueueFor <IRequest>("requests", MessagingEntityCreationOptions.VerifyAlreadyExists) .UsingQueueFor <IResponse>("responses", MessagingEntityCreationOptions.VerifyAlreadyExists) .UsingTopicFor <IEvent>("events", MessagingEntityCreationOptions.VerifyAlreadyExists) .UsingSubscriptionFor <IEvent>("events", "my-event-subscription", MessagingEntityCreationOptions.VerifyAlreadyExists) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .FilterMessageTypeAssemblies(assembly => assembly.GetName().Name == "Obvs.AzureServiceBus.Tests") .AsClientAndServer() .CreateServiceBus(); _mockMessagingEntityVerifier.Verify(mev => mev.EnsureMessagingEntitiesExist(It.IsAny <IEnumerable <MessageTypeMessagingEntityMappingDetails> >()), Times.Once()); configuredMessageTypePathMappings.Should().NotBeNull(); configuredMessageTypePathMappings.Should().BeEquivalentTo(new [] { new MessageTypeMessagingEntityMappingDetails(typeof(ICommand), "commands", MessagingEntityType.Queue, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock), new MessageTypeMessagingEntityMappingDetails(typeof(IRequest), "requests", MessagingEntityType.Queue, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock), new MessageTypeMessagingEntityMappingDetails(typeof(IResponse), "responses", MessagingEntityType.Queue, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock), new MessageTypeMessagingEntityMappingDetails(typeof(IEvent), "events", MessagingEntityType.Topic, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock), new MessageTypeMessagingEntityMappingDetails(typeof(IEvent), "events/subscriptions/my-event-subscription", MessagingEntityType.Subscription, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock), }); }
private Task StartWatcher(int i, int count) { IServiceBus serviceBus = ServiceBus.Configure() .WithKafkaEndpoints <ITestMessage1>() .Named("Obvs.TestService") .ConnectToKafka(_kafkaAddresses) .SerializedAsJson() .AsServer() //.UsingConsoleLogging() .Create(); double?[] times = new double?[count]; long[] received = { 0 }; var dis = serviceBus.Commands.OfType <TestCommand>().Subscribe(x => { Interlocked.Increment(ref received[0]); var ms = (Stopwatch.GetTimestamp() - x.Ticks) / ((double)Stopwatch.Frequency / 1000); times[x.Id] = ms; }); return(Task.Run(() => { SpinWait.SpinUntil(() => Interlocked.Read(ref received[0]) == count); Console.WriteLine($"******* Watcher {i}: Total {_sw.ElapsedMilliseconds}ms ({count} msgs), Min/Avg/Max (ms) = {times.Min(d=>d.Value):0}/{times.Average(d => d.Value):0}/{times.Max(d => d.Value):0}"); dis.Dispose(); ((IDisposable)serviceBus).Dispose(); })); }
private async Task SendCommands(int count) { IServiceBus serviceBus = ServiceBus.Configure() .WithKafkaEndpoints <ITestMessage1>() .Named("Obvs.TestService") .WithKafkaSourceConfiguration(new KafkaSourceConfiguration()) .WithKafkaProducerConfiguration(new KafkaProducerConfiguration()) .ConnectToKafka(_kafkaAddresses) .SerializedAsJson() .AsClient() //.UsingConsoleLogging() .Create(); Stopwatch sw = Stopwatch.StartNew(); var sendTasks = Enumerable.Range(0, count) .Select(i => serviceBus.SendAsync(new TestCommand { Id = i })); await Task.WhenAll(sendTasks); _sw = Stopwatch.StartNew(); Console.WriteLine($"###$$$$### Sends: {sw.ElapsedMilliseconds}ms"); ((IDisposable)serviceBus).Dispose(); }
private static void Main(string[] args) { var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616"; var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Service1"; Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}"); var serviceBus = ServiceBus.Configure() .WithActiveMQEndpoints <IServiceMessage1>() .Named(serviceName) .UsingQueueFor <ICommand>() .ConnectToBroker(brokerUri) .WithCredentials("TESTUSER", "testpassword1") .SerializedAsJson() .AsClient() .CreateClient(); serviceBus.Events.Subscribe(c => Console.WriteLine("Received an event!")); Console.WriteLine("Hit <Enter> to send a command."); while (true) { string data = Console.ReadLine(); serviceBus.SendAsync(new Command1 { Data = data }); } }
public void Test_ServiceBusClientCreation_ThrowsInvalidServiceName() { Action action = () => ServiceBus.Configure() .WithAzureStorageQueueEndpoint <TestMessage>() .Named(null); Assert.Throws(typeof(InvalidServiceNameException), action); }
public async Task ShouldSendAndReceiveMessagesOverServiceBus() { IServiceBus serviceBus = ServiceBus.Configure() .WithRabbitMQEndpoints <ITestMessage>() .Named("Obvs.TestService") .ConnectToBroker("amqp://192.168.99.100:32769") // edit to correspond with 5672 port on local RabbitMQ from DockerHub .SerializedAsJson() .AsClientAndServer() .PublishLocally().AnyMessagesWithNoEndpointClients() .UsingConsoleLogging() .Create(); // create threadsafe collection to hold received messages in var messages = new ConcurrentBag <IMessage>(); // create some actions that will act as a fake services acting on incoming commands and requests Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent { Id = command.Id }); Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse { Id = request.Id }); var observer = new AnonymousObserver <IMessage>(msg => { messages.Add(msg); Console.WriteLine(msg); }, exception => Console.WriteLine(exception)); // subscribe to all messages on the ServiceBus var sub1 = serviceBus.Events.Subscribe(observer); var sub2 = serviceBus.Commands.Subscribe(observer); var sub3 = serviceBus.Requests.Subscribe(observer); var sub4 = serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1); var sub5 = serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2); // send some messages await serviceBus.SendAsync(new TestCommand { Id = 123 }); var sub6 = serviceBus.GetResponses(new TestRequest { Id = 456 }).Subscribe(observer); // wait some time until we think all messages have been sent and received from RabbitMQ await Task.Delay(TimeSpan.FromSeconds(1)); // test we got everything we expected Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received"); Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received"); Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received"); Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received"); // dispose subscriptions sub1.Dispose(); sub2.Dispose(); sub3.Dispose(); sub4.Dispose(); sub5.Dispose(); sub6.Dispose(); // always call Dispose on serviceBus when exiting process ((IDisposable)serviceBus).Dispose(); }
public void Test_ServiceBusClientCreation_ThrowsInvalidAccountCredentials() { Action action = () => ServiceBus.Configure() .WithAzureStorageQueueEndpoint <TestMessage>() .Named("service-name") .WithAccountCredentials(null, "accountKey"); Assert.Throws(typeof(InvalidCredentialsConfigurationException), action); }
public void ConfigureAzureServiceBusEndpointWithNullNamespaceManagerThrows() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithNamespaceManager((NamespaceManager)null); action.ShouldThrow <ArgumentNullException>(); }
public void Test_ServiceBusClientCreation_ThrowsInvalidConnectionStringCredentials() { Action action = () => ServiceBus.Configure() .WithAzureStorageQueueEndpoint <TestMessage>() .Named("service-name") .WithConnectionString("invalidconnstring"); Assert.Throws(typeof(InvalidCredentialsConfigurationException), action); }
public void ConfigureAzureServiceBusEndpointWithNullConnectionStringThrows() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithConnectionString(null); action.ShouldThrow <ArgumentNullException>(); }
public void ConfigureNullMessagingEntityVerifierShouldThrow() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingEntityVerifier(null); action.ShouldThrow <ArgumentNullException>() .And.ParamName.Should().Be("messagingEntityVerifier"); }
public async Task ShouldSendAndReceiveMessagesOverServiceBus_OnlyMessagesWithNoEndpoints() { IServiceBus serviceBus = ServiceBus.Configure() .WithNoneEndpoints() .PublishLocally().OnlyMessagesWithNoEndpoints() .UsingConsoleLogging() .Create(); await ShouldSendAndReceiveMessagesOverServiceBus(serviceBus); }
public async void TestServiceEndpointsOverLocalHostSockets() { // set up ServiceBus using fluent interfaces and all current endpoints and pointing at localhost var serviceBus = ServiceBus.Configure() .WithNetMqEndpoints <ITestMessage>() .Named("Obvs.TestNetMqService") .BindToAddress("tcp://localhost") .OnPort(5555) .SerializedAsJson() .AsClientAndServer() .UsingConsoleLogging() .Create(); // create threadsafe collection to hold received messages in var messages = new ConcurrentBag <IMessage>(); // create some actions that will act as a fake services acting on incoming commands and requests Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent { Id = command.Id }); Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse { Id = request.Id }); var observer = new AnonymousObserver <IMessage>(msg => { messages.Add(msg); Console.WriteLine(msg); }, exception => Console.WriteLine(exception)); // subscribe to all messages on the ServiceBus serviceBus.Events.Subscribe(observer); serviceBus.Commands.Subscribe(observer); serviceBus.Requests.Subscribe(observer); serviceBus.Commands.OfType <TestCommand>().SubscribeOn(TaskPoolScheduler.Default).Subscribe(fakeService1); serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2); // send some messages await serviceBus.SendAsync(new TestCommand { Id = 123 }); serviceBus.GetResponses(new TestRequest { Id = 456 }).Subscribe(observer); // wait some time until we think all messages have been sent and received over AMQ await Task.Delay(TimeSpan.FromSeconds(2)); // test we got everything we expected Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received"); Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received"); Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received"); Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received"); // win! }
static BusHub() { Bus = ServiceBus.Configure() .WithNetMqEndpoints <ITestMessage>() .Named("Obvs.Samples.SignalR") .BindToAddress("tcp://localhost") .OnPort(3000) .SerializedAsJson() .FilterMessageTypeAssemblies("Obvs.Samples.Messages") .AsClientAndServer() .Create(); }
public void ConfigureMultipleProvidersForSameMessageType() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .UsingQueueFor <ICommand>("test") .UsingMessagePropertyProviderFor <TestCommand>(new FuncMessagePropertyProvider <TestCommand>(tc => new KeyValuePair <string, object>("CommandProp1", "CommandPropValue1"))) .UsingMessagePropertyProviderFor <TestCommand>(new FuncMessagePropertyProvider <TestCommand>(tc => new KeyValuePair <string, object>("CommandProp2", "CommandPropValue2"))) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .AsClientAndServer(); }
public void ConfiguringANullProviderInstanceThrows() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .UsingQueueFor <ICommand>("test") .UsingMessagePropertyProviderFor <TestCommand>(null) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .AsClientAndServer(); action.ShouldThrow <ArgumentNullException>(); }
public void ConfigureNoMessageTypesShouldThrow() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .AsClientAndServer() .CreateServiceBus(); action.ShouldThrow <ArgumentException>() .And.ParamName.Should().Be("messageTypePathMappings"); }
public void Test_FluentConfigAsClient_Succeeds() { var defaultQueueRequestOptions = new QueueRequestOptions { }; var queueRequestOptionsCmd1 = new QueueRequestOptions { }; var serviceBusClient = ServiceBus.Configure() .WithAzureStorageQueueEndpoint <ITestServiceMessage>() .Named("service-name") .WithAccountCredentials("accountName", "accountKey".ToBase64String()) .WithCommandQueue("queue1", queueRequestOptionsCmd1) .WithEventQueue("events", queueRequestOptionsCmd1) .SerializedWith(_messageSerializer, _messageDeserializerFactory) .AsClient(); }
public void ConfigureSameMessageTypeForSameRoleMoreThanOnceShouldThrow() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .UsingQueueFor <ICommand>("commands") .UsingQueueFor <ICommand>("commandsAgain"); var exceptionAssertion = action.ShouldThrow <MappingAlreadyExistsForMessageTypeException>(); exceptionAssertion.And.MessageType.Should().Be(typeof(ICommand)); exceptionAssertion.And.EntityType.Should().Be(MessagingEntityType.Queue); }
public void ConfiguringAProviderForAMessageThatIsNotDerivedFromTheServiceMessageTypeThrows() { Action action = () => ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .UsingQueueFor <ICommand>("test") .UsingMessagePropertyProviderFor <NotATestMessage>(new FuncMessagePropertyProvider <NotATestMessage>(c => null)) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .AsClientAndServer(); action.ShouldThrow <ArgumentException>() .And.ParamName.Should().Be("messagePropertyProvider"); }
public async Task TestBasicSendReceiveOfAllMessageTypes() { var bus = ServiceBus.Configure() .WithNatsEndpoint <ITestService, IMessage, ICommand, IEvent, IRequest, IResponse>(settings => { settings.ServiceName = "Obvs.NATS.TestService"; settings.Configure(connection => { connection.Url = "nats://192.168.99.100:32774"; // change to local Docker address:port that maps onto 4222 connection.IsShared = true; }); settings.Configure(messageProperty => { messageProperty.Filter = properties => properties.ContainsKey("blah"); messageProperty.Provider = message => new Dictionary <string, string> { { "blah", "foo" } }; }); }).SerializedAsJson().AsClientAndServer() .Create(); bus.Commands.OfType <TestCommand>().Subscribe(command => { Console.WriteLine(command); bus.PublishAsync(new TestEvent { Id = command.Id }); }); bus.Requests.OfType <TestRequest>().Subscribe(request => { Console.WriteLine(request); bus.ReplyAsync(request, new TestResponse { Id = request.Id }); }); bus.Events.Subscribe(Console.WriteLine); await bus.SendAsync(new TestCommand { Id = 1 }); var response = await bus.GetResponse <TestResponse>(new TestRequest()); Console.WriteLine(response); await Task.Delay(TimeSpan.FromSeconds(1)); ((IDisposable)bus).Dispose(); }
public void ShouldSendAndReceiveMessagesOverServiceBus() { IServiceBus serviceBus = ServiceBus.Configure() .WithRabbitMQEndpoints <ITestMessage>() .Named("Obvs.TestService") .ConnectToBroker("amqp://localhost") .SerializedAsJson() .AsClientAndServer() .UsingConsoleLogging() .Create(); // create threadsafe collection to hold received messages in ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>(); // create some actions that will act as a fake services acting on incoming commands and requests Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent { Id = command.Id }); Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse { Id = request.Id }); AnonymousObserver <IMessage> observer = new AnonymousObserver <IMessage>(msg => { messages.Add(msg); Console.WriteLine(msg); }, exception => Console.WriteLine(exception)); // subscribe to all messages on the ServiceBus serviceBus.Events.Subscribe(observer); serviceBus.Commands.Subscribe(observer); serviceBus.Requests.Subscribe(observer); serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1); serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2); // send some messages serviceBus.SendAsync(new TestCommand { Id = 123 }); serviceBus.GetResponses(new TestRequest { Id = 456 }).Subscribe(observer); // wait some time until we think all messages have been sent and received from RabbitMQ Thread.Sleep(TimeSpan.FromSeconds(1)); // test we got everything we expected Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received"); Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received"); Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received"); Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received"); }
public async Task EnsureProvidedPropertiesArePresent() { BrokeredMessage brokeredMessage = null; Mock <IMessageSender> mockMessageSender = new Mock <IMessageSender>(); mockMessageSender.Setup(ms => ms.SendAsync(It.IsAny <BrokeredMessage>())) .Callback <BrokeredMessage>(bm => brokeredMessage = bm) .Returns(Task.FromResult(true)); _mockMessagingFactory.Setup(mf => mf.CreateMessageSender(It.IsAny <Type>(), It.IsAny <string>())) .Returns(mockMessageSender.Object); CompositeMessagePropertyProvider <TestCommand> propertyProvider = new CompositeMessagePropertyProvider <TestCommand>(); propertyProvider.Providers.AddRange( c => new KeyValuePair <string, object>("SomeProp", "SomeValue"), c => new KeyValuePair <string, object>("SomeOtherProp", "SomeOtherValue")); FuncMessagePropertyProvider <TestCommand> propertyProvider2 = new FuncMessagePropertyProvider <TestCommand>(c => new KeyValuePair <string, object>("SomeThirdProp", "SomeThirdValue")); IServiceBus serviceBus = ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object) .UsingQueueFor <ICommand>("test") .UsingMessagePropertyProviderFor <TestCommand>(propertyProvider) .UsingMessagePropertyProviderFor <TestCommand>(propertyProvider2) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .AsClientAndServer() .Create(); await serviceBus.SendAsync(new TestCommand()); brokeredMessage.Should().NotBeNull(); brokeredMessage.Properties.Should() .Contain(new KeyValuePair <string, object>("SomeProp", "SomeValue")) .And.Contain(new KeyValuePair <string, object>("SomeOtherProp", "SomeOtherValue")) .And.Contain(new KeyValuePair <string, object>("SomeThirdProp", "SomeThirdValue")); }
static void Main(string[] args) { IServiceBus serviceBus = ServiceBus.Configure() .WithActiveMQEndpoints <IMyServiceMessage>() .Named("MyService") .UsingQueueFor <ICommand>() .ConnectToBroker("tcp://192.168.99.100:32780") // local docker port for 61616 .WithCredentials("TESTUSER", "testpassword") .SerializedAsJson() .AsServer() .Create(); serviceBus.Commands.Subscribe(async c => { Console.WriteLine("Received command " + c); await serviceBus.PublishAsync(new MyEvent()); }); Console.WriteLine("Hit <Enter> to exit program."); Console.ReadLine(); }
static void Main(string[] args) { var serviceBus = ServiceBus.Configure() .WithActiveMQEndpoints <IMyServiceMessage>() .Named("MyService") .UsingQueueFor <ICommand>() .ConnectToBroker("tcp://192.168.99.100:32780") // local docker port for 61616 .WithCredentials("TESTUSER", "testpassword1") .SerializedAsJson() .AsClient() .CreateClient(); serviceBus.Events.Subscribe(c => Console.WriteLine("Received an event!")); Console.WriteLine("Hit <Enter> to send a command."); while (true) { string data = Console.ReadLine(); serviceBus.SendAsync(new MyCommand { Data = data }); } }
public void ExplicitMessageReceiveModeIsSetCorrectly_PeekLock() { Mock <IMessageReceiver> mockMessageReceiver = new Mock <IMessageReceiver>(); mockMessageReceiver.Setup(mmr => mmr.IsClosed) .Returns(true); _mockMessagingFactory.Setup(mf => mf.CreateMessageReceiver(typeof(TestCommand), "test", It.IsAny <MessageReceiveMode>())) .Returns(mockMessageReceiver.Object); IServiceBus serviceBus = ServiceBus.Configure() .WithAzureServiceBusEndpoint <TestMessage>() .Named("Test Service Bus") .WithMessagingFactory(_mockMessagingFactory.Object) .UsingQueueFor <TestCommand>("test", MessageReceiveMode.PeekLock) .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object) .AsClientAndServer() .Create(); serviceBus.Commands.Subscribe(c => c.ToString()); _mockMessagingFactory.Verify(mf => mf.CreateMessageReceiver(typeof(TestCommand), "test", MessageReceiveMode.PeekLock)); }
public async void TestIntegration() { const string token = "xoxb-13657478324-zaLy8ERhYFl4plNtNOM5OvWb"; var serviceBus = ServiceBus.Configure() .WithEndpoint(new FakeEndpoint()) .WithSlackIntegration() .ConnectUsingToken(token) .Create(); var sub = serviceBus.Events.OfType <SlackMessageReceived>().Subscribe(Console.WriteLine); var sub2 = serviceBus.Events.OfType <SlackMessageReceived>().Subscribe(msg => serviceBus.SendAsync(new SendSlackMessage { ChannelId = msg.ChannelId, Text = "Message received" })); await Task.Delay(TimeSpan.FromSeconds(30)); sub.Dispose(); sub2.Dispose(); ((IDisposable)serviceBus).Dispose(); }
public async Task TestServiceEndpointsOverLocalHostSockets() { // create a server that hosts endpoints for two services var serviceBus = ServiceBus.Configure() .WithNetMqEndpoints <ITestService1>() .Named("Obvs.TestNetMqService1") .BindToAddress("tcp://localhost") .OnPort(5555) .SerializedAsJson() // messages will be serialized as strings .AsServer() .WithNetMqEndpoints <ITestService2>() .Named("Obvs.TestNetMqService2") .BindToAddress("tcp://localhost") .OnPort(6555) .SerializedAsProtoBuf() // messages will be serialized as binary .AsServer() .UsingConsoleLogging() // useful for debugging, but check out other proper logging extensions .Create(); // create a client that connects to both services var serviceBusClient1 = ServiceBus.Configure() .WithNetMqEndpoints <ITestService1>() .Named("Obvs.TestNetMqService1") .BindToAddress("tcp://localhost") .OnPort(5555) .SerializedAsJson() .AsClient() .WithNetMqEndpoints <ITestService2>() .Named("Obvs.TestNetMqService2") .BindToAddress("tcp://localhost") .OnPort(6555) .SerializedAsProtoBuf() .AsClient() .UsingConsoleLogging() .CreateClient(); // create a second client which only connects to one of the services var serviceBusClient2 = ServiceBus.Configure() .WithNetMqEndpoints <ITestService1>() .Named("Obvs.TestNetMqService1") .BindToAddress("tcp://localhost") .OnPort(5555) .SerializedAsJson() .AsClient() .UsingConsoleLogging() .CreateClient(); // create action to record all observed messages so we can assert later var messages = new ConcurrentBag <IMessage>(); Action <IMessage> messageRecorder = msg => messages.Add(msg); // create some actions that will act as a fake services acting on incoming commands and requests Action <ITestService1> fakeService1 = msg => { messageRecorder(msg); Console.WriteLine("Service1 received: {0}", msg); var command = msg as TestCommand1; if (command != null) { serviceBus.PublishAsync(new TestEvent1 { Id = command.Id }); } var request = msg as TestRequest1; if (request != null) { serviceBus.ReplyAsync(request, new TestResponse1 { Id = request.Id }); } }; Action <ITestService2> fakeService2 = msg => { messageRecorder(msg); Console.WriteLine("Service2 received: {0}", msg); var command = msg as TestCommand2; if (command != null) { serviceBus.PublishAsync(new TestEvent2 { Id = command.Id }); } var request = msg as TestRequest2; if (request != null) { serviceBus.ReplyAsync(request, new TestResponse2 { Id = request.Id }); } }; // create some actions that will act as simple clients which display events and responses received Action <IMessage> fakeClient1 = msg => { messageRecorder(msg); Console.WriteLine("Client1 received: {0}", msg); }; Action <IMessage> fakeClient2 = msg => { messageRecorder(msg); Console.WriteLine("Client2 received: {0}", msg); }; // subscribe to events on clients serviceBusClient1.Events.Subscribe(fakeClient1); serviceBusClient2.Events.Subscribe(fakeClient2); // subscribe to commands and requests on server // each ObserveOn creates a queue and can be a very useful way of dispatching messages serviceBus.Commands.OfType <ITestService1>().ObserveOn(Scheduler.Default).Subscribe(fakeService1); serviceBus.Requests.OfType <ITestService1>().ObserveOn(Scheduler.Default).Subscribe(fakeService1); serviceBus.Commands.OfType <ITestService2>().ObserveOn(Scheduler.Default).Subscribe(fakeService2); serviceBus.Requests.OfType <ITestService2>().ObserveOn(Scheduler.Default).Subscribe(fakeService2); // send some messages from client1 await serviceBusClient1.SendAsync(new TestCommand1 { Id = 1 }); await serviceBusClient1.SendAsync(new TestCommand2 { Id = 3 }); serviceBusClient1.GetResponses(new TestRequest1 { Id = 2 }).Subscribe(fakeClient1); serviceBusClient1.GetResponses(new TestRequest2 { Id = 4 }).Subscribe(fakeClient1); // send some messages from client2 await serviceBusClient2.SendAsync(new TestCommand1 { Id = 5 }); serviceBusClient2.GetResponses(new TestRequest1 { Id = 6 }).Subscribe(fakeClient1); // wait some time until we think all messages have been sent and received await Task.Delay(TimeSpan.FromSeconds(3)); // test we got everything we expected Assert.True(messages.OfType <TestCommand1>().Count() == 2, "TestCommand1"); Assert.True(messages.OfType <TestEvent1>().Count() == 4, "TestEvent1"); Assert.True(messages.OfType <TestCommand2>().Count() == 1, "TestCommand2"); Assert.True(messages.OfType <TestEvent2>().Count() == 1, "TestEvent2"); Assert.True(messages.OfType <TestRequest1>().Count() == 2, "TestRequest1"); Assert.True(messages.OfType <TestResponse1>().Count() == 2, "TestResponse1"); Assert.True(messages.OfType <TestRequest2>().Count() == 1, "TestRequest2"); Assert.True(messages.OfType <TestResponse2>().Count() == 1, "TestResponse2"); // win! }
static void Main(string[] args) { const string token = "<insert your token here>"; var serviceBus = ServiceBus.Configure() .WithEndpoint(new FakeEndpoint()) .WithSlackIntegration() .ConnectUsingToken(token) .Create(); var sub1 = serviceBus.Events.Subscribe(Console.WriteLine); var sub2 = serviceBus.Events.OfType <SlackMessageReceived>().Subscribe(msg => { serviceBus.SendAsync(new SendSlackMessage { ChannelId = msg.ChannelId, Text = null, Attachments = new List <SendSlackMessage.Attachment> { new SendSlackMessage.Attachment { Title = "Message Received", Colour = "good", Pretext = "Testing message attachments", Fallback = "My fallback text", Text = "This is where you write the main body of the message", Fields = new [] { new SendSlackMessage.Field { Short = true, Title = "User", Value = $"@{msg.UserName}" }, new SendSlackMessage.Field { Short = true, Title = "Time", Value = DateTime.Now.ToString("HH:mm:ss") }, new SendSlackMessage.Field { Short = true, Title = "Channel", Value = $"#{msg.ChannelName}" } } } } }); }); serviceBus.GetResponses <GetSlackChannelsResponse>(new GetSlackChannels()) .Subscribe(r => { var channels = r.Channels.Select(c => $"#{c.Name}").ToArray(); Console.WriteLine(string.Join("\n", channels)); }); serviceBus.GetResponses <GetSlackUsersResponse>(new GetSlackUsers()) .Subscribe(r => { var users = r.Users.Select(user => $"@{user.Name}").ToArray(); Console.WriteLine(string.Join("\n", users)); }); Console.WriteLine("Hit enter to exit."); Console.ReadLine(); sub1.Dispose(); sub2.Dispose(); ((IDisposable)serviceBus).Dispose(); }