public void Initialize() { connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); options = new DbContextOptionsBuilder <KlantContext>() .UseSqlite(connection) .Options; using (var context = new KlantContext(options)) { context.Database.EnsureCreated(); } _context = new TestBusContext(); var services = new ServiceCollection(); services.AddTransient <ICommandPublisher, CommandPublisher>(); services.AddSingleton <DbContextOptions>(options); services.AddSingleton <KlantContext>(); services.AddTransient <IKlantDatamapper, KlantDatamapper>(); services.AddSingleton <IBusContext <IConnection> >(_context); services.AddTransient <IEventPublisher, EventPublisher>(); var builder = new MicroserviceHostBuilder() .RegisterDependencies(services) .WithContext(_context) .AddCommandListener <KlantListener>(); _host = builder.CreateHost(); _host.StartListening(); Thread.Sleep(1000); }
public static async Task ScrapeAuditLog(IBusContext <IConnection> mainContext, ServiceCollection collection, DateTime startTime) { var exchangeName = "Audit_Bestelling " + Guid.NewGuid(); var connectionBuilder = new RabbitMQContextBuilder() .ReadFromEnvironmentVariables().WithExchange(exchangeName); var builder = new MicroserviceHostBuilder(); builder .RegisterDependencies(collection) .WithContext(connectionBuilder.CreateContext()) .ExitAfterIdleTime(new TimeSpan(0, 0, 2, 0)) .UseConventions(); builder.CreateHost().StartListeningInOtherThread(); var publisher = new CommandPublisher(mainContext); var replayEventsCommand = new ReplayEventsCommand { ToTimestamp = startTime.Ticks, ExchangeName = exchangeName }; var result = await publisher.Publish <bool>(replayEventsCommand, "AuditlogReplayService", "Minor.WSA.AuditLog.Commands.ReplayEventsCommand"); }
public void UseConventionsRegistersProperTopics(string messageText) { // Arrange var testContext = new TestBusContext(); var hostBuilder = new MicroserviceHostBuilder().WithBusContext(testContext); // Act hostBuilder.UseConventions(); hostBuilder.CreateHost().Start(); // Assert var message = new DummyEvent("IrrelevantTopic") { DummyText = messageText }; new EventPublisher(testContext).Publish(message); Thread.Sleep(WaitTime); Assert.IsNull(EventListenerDummy.HandlesResult); Assert.IsNull(EventListenerDummy2.HandlesResult); Assert.AreEqual(message, EventListenerDummy3.HandlesResult); }
public void Initialize() { connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); options = new DbContextOptionsBuilder <WebshopContext>() .UseSqlite(connection) .Options; using (var context = new WebshopContext(options)) { context.Database.EnsureCreated(); } var services = new ServiceCollection(); services.AddSingleton <DbContextOptions>(options); services.AddTransient <WebshopContext, WebshopContext>(); services.AddTransient <IArtikelDatamapper, ArtikelDatamapper>(); services.AddTransient <IKlantDatamapper, KlantDatamapper>(); _context = new TestBusContext(); var builder = new MicroserviceHostBuilder() .RegisterDependencies(services) .WithContext(_context) .AddEventListener <MagazijnListener>(); _host = builder.CreateHost(); _host.StartListening(); }
public void FanInListenerReceivesAllMessages(string firstName, string lastName, string email, string phone) { // Arrange using var busContext = new RabbitMqContextBuilder() .WithConnectionString("amqp://*****:*****@localhost") .WithExchange("TestExchange") .CreateContext(); var builder = new MicroserviceHostBuilder() .WithBusContext(busContext) .AddEventListener <FanInEventListener>(); using var host = builder.CreateHost(); host.Start(); var publisher = new EventPublisher(busContext); var personEvent = new PersonAddedEvent { Person = new Person { FirstName = firstName, LastName = lastName, Email = email, PhoneNumber = phone } }; // Act publisher.Publish(personEvent); Thread.Sleep(WaitTime); // Assert Assert.AreEqual(personEvent, FanInEventListener.ResultEvent); }
private static void ConfigureNijn(IServiceCollection services) { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider( new ConsoleLoggerProvider( (text, logLevel) => logLevel >= LogLevel.Debug, true)); var connectionBuilder = new RabbitMQContextBuilder() .ReadFromEnvironmentVariables(); var nijnContext = connectionBuilder.CreateContext(); services.AddTransient <ICommandPublisher, CommandPublisher>(); services.AddTransient <IEventPublisher, EventPublisher>(); var builder = new MicroserviceHostBuilder() .SetLoggerFactory(loggerFactory) .RegisterDependencies(services) .WithContext(nijnContext) .UseConventions(); var host = builder.CreateHost(); host.CreateQueues(); host.StartListeningInOtherThread(); var logger = NijnLogger.CreateLogger <Program>(); logger.LogInformation("Started..."); }
private IBusContext <IConnection> CreateNijnConfig(IServiceCollection serviceCollection) { //Deprecated method, maar kan even niet anders ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider( new ConsoleLoggerProvider( (text, logLevel) => logLevel >= LogLevel.Debug, true)); var connectionBuilder = new RabbitMQContextBuilder() .ReadFromEnvironmentVariables(); _context = connectionBuilder.CreateContext(); var builder = new MicroserviceHostBuilder() .SetLoggerFactory(loggerFactory) .RegisterDependencies(serviceCollection) .WithContext(_context) .UseConventions(); var host = builder.CreateHost(); host.StartListeningInOtherThread(); return(_context); }
private static void Main(string[] args) { var connectionString = Environment.GetEnvironmentVariable("SPRINTERDB"); var options = new DbContextOptionsBuilder <BeheerContext>() .UseNpgsql(connectionString) .Options; ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider( new ConsoleLoggerProvider( (text, logLevel) => logLevel >= LogLevel.Debug, true)); var connectionBuilder = new RabbitMQContextBuilder() .ReadFromEnvironmentVariables(); var nijnContext = connectionBuilder.CreateContext(); var services = new ServiceCollection(); services.AddTransient <ICommandPublisher, CommandPublisher>(); services.AddTransient <IEventPublisher, EventPublisher>(); services.AddSingleton <DbContextOptions>(options); services.AddTransient <BeheerContext, BeheerContext>(); services.AddTransient <IArtikelDatamapper, ArtikelDatamapper>(); services.AddTransient <IBestellingDatamapper, BestellingDatamapper>(); services.AddSingleton <IBusContext <IConnection> >(nijnContext); services.AddTransient <IKlantDatamapper, KlantDatamapper>(); var builder = new MicroserviceHostBuilder() .SetLoggerFactory(loggerFactory) .RegisterDependencies(services) .WithContext(nijnContext) .UseConventions(); var host = builder.CreateHost(); host.CreateQueues(); using (var context = new BeheerContext(options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); if (!context.Artikelen.Any()) { ScrapeAuditLog(nijnContext, services, DateTime.Now).Wait(); } } host.StartListeningInOtherThread(); var logger = NijnLogger.CreateLogger <Program>(); logger.LogInformation("Started..."); }
static void Main(string[] args) { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider( new ConsoleLoggerProvider( (text, logLevel) => logLevel >= LogLevel.Debug, true)); //192.168.99.100 var connectionBuilder = new RabbitMQContextBuilder() .WithExchange("MVM.EventExchange") .WithAddress("192.168.99.100", 5672) .WithCredentials(userName: "******", password: "******"); using (var context = connectionBuilder.CreateContext()) { var builder = new MicroserviceHostBuilder() .SetLoggerFactory(loggerFactory) .RegisterDependencies((services) => { services.AddTransient <IDataMapper, SinaasAppelDataMapper>(); }) .WithContext(context) .UseConventions(); using (var host = builder.CreateHost()) { host.StartListening(); Console.WriteLine("ServiceHost is listening to incoming events..."); Console.WriteLine("Press any key to quit."); var publisher = new EventPublisher(context); publisher.Publish(new PolisToegevoegdEvent("MVM.Polisbeheer.PolisToegevoegd") { Message = "Hey" }); publisher.Publish(new HenkToegevoegdEvent("Test") { Test = "Oi" }); int i = 0; while (true) { Console.ReadKey(); Test(context, i); Test(context, i * 100); i++; } } } }
static void Main(string[] args) { ILoggerFactory loggerFactory = new LoggerFactory(); //Deprecated method, maar kan even niet anders ConsoleLoggerOptions options = new ConsoleLoggerOptions(); loggerFactory.AddProvider( new ConsoleLoggerProvider( (text, logLevel) => logLevel >= LogLevel.Debug, true)); //192.168.99.100 var connectionBuilder = new RabbitMQContextBuilder() .WithExchange("MVM.EventExchange") .WithAddress("localhost", 5672) .WithCredentials(userName: "******", password: "******"); var context = new TestBusContext(); var builder = new MicroserviceHostBuilder() .SetLoggerFactory(loggerFactory) .RegisterDependencies((services) => { services.AddTransient <IDataMapper, SinaasAppelDataMapper>(); services.AddTransient <ICommandPublisher, CommandPublisher>(); services.AddTransient <IEventPublisher, EventPublisher>(); services.AddSingleton <IBusContext <IConnection> >(context); }) .WithContext(context) .UseConventions(); var host = builder.CreateHost(); host.StartListeningInOtherThread(); Console.WriteLine("ServiceHost is listening to incoming events..."); Console.WriteLine("Press any key to quit."); var publisher = new EventPublisher(context); var commandpublisher = new CommandPublisher(context); publisher.Publish(new PolisToegevoegdEvent("MVM.Polisbeheer.PolisToegevoegd") { Message = "Hey" }); publisher.Publish(new HenkToegevoegdEvent("Test") { Test = "Oi" }); }
public void CreateHostReturnsHostWithContext() { // Arrange var contextMock = new Mock <IBusContext <IConnection> >(); var context = contextMock.Object; var builder = new MicroserviceHostBuilder(); builder.WithBusContext(context); // Act var host = builder.CreateHost(); // Arrange Assert.AreSame(context, host.Context); }
public void EventIsProperlyReceived(string data) { // Arrange AuditLogContext dbContext = new AuditLogContext(_options); TestBusContext testBusContext = new TestBusContext(); using var hostBuilder = new MicroserviceHostBuilder() .WithBusContext(testBusContext) .RegisterDependencies(services => { services.AddSingleton(dbContext); services.AddTransient <IAuditLogItemRepository, AuditLogItemRepository>(); }) .AddEventListener <IAuditLogItemRepository>() .AddEventListener <AuditEventLoggingListener>(); using var host = hostBuilder.CreateHost(); host.Start(); DummyEvent evt = new DummyEvent("test.queue") { Text = data }; IEventPublisher eventPublisher = new EventPublisher(testBusContext); // Act eventPublisher.Publish(evt); Thread.Sleep(1500); // Assert AuditLogItem[] resultData = dbContext.AuditLogItems.ToArray(); Assert.AreEqual(1, resultData.Length); string expectedData = JsonConvert.SerializeObject(evt); var firstItem = resultData.First(); Assert.AreEqual(expectedData, firstItem.Data); Assert.AreEqual(evt.Id.ToString(), firstItem.Id); Assert.AreEqual(new DateTime(evt.Timestamp).ToFileTimeUtc(), firstItem.TimeStamp); }
public void AddingListenerOnlyAddsRelevantMethod() { // Arrange var testContext = new TestBusContext(); var builder = new MicroserviceHostBuilder().WithBusContext(testContext) .WithQueueName("test.queue") .AddEventListener <MethodEventListener>(); // Act using var host = builder.CreateHost(); var result = host.Listeners.ToList(); // Assert Assert.AreEqual(1, result.Count); var firstItem = result.FirstOrDefault(); Assert.AreEqual("testPattern", firstItem?.TopicExpressions.FirstOrDefault()); }
public void UseConventionsRegistersProperCommandListeners() { // Arrange var testContext = new TestBusContext(); var hostBuilder = new MicroserviceHostBuilder() .WithBusContext(testContext); // Act hostBuilder.UseConventions(); hostBuilder.CreateHost().Start(); // Assert var message = new GetAnimalsCommand(); ICommandPublisher publisher = new CommandPublisher(testContext); Animal[] animals = publisher.PublishAsync <IEnumerable <Animal> >(message).Result.ToArray(); Assert.AreEqual(2, animals.Length); }
public void AddingListenerRegistersProperCommandReceiver() { // Arrange TestBusContext testContext = new TestBusContext(); MicroserviceHostBuilder hostBuilder = new MicroserviceHostBuilder() .WithQueueName("test.queue") .WithBusContext(testContext); // Act hostBuilder.AddEventListener <CommandListenerDummy>(); List <MicroserviceCommandListener> result = hostBuilder.CreateHost().CommandListeners.ToList(); // Assert Assert.AreEqual(1, result.Count); var firstItem = result.FirstOrDefault(); Assert.AreEqual("command.queue", firstItem?.Queue); }
public void EventMessageHandledIsFiredOnIncomingMessageWithProperValues() { // Arrange const string queueName = "test.queue"; const string topicExpression = "TestTopic"; var testContext = new TestBusContext(); var hostBuilder = new MicroserviceHostBuilder() .WithBusContext(testContext) .AddEventListener <EventListenerDummy>() .WithQueueName(queueName); using var host = hostBuilder.CreateHost(); host.Start(); EventMessage receivedEventMessage = null; EventMessageHandledEventArgs receivedEventArgs = null; host.EventMessageHandled += (eventMessage, args) => { receivedEventMessage = eventMessage; receivedEventArgs = args; }; // Act var message = new DummyEvent(topicExpression); new EventPublisher(testContext).Publish(message); Thread.Sleep(WaitTime); // Assert Assert.AreEqual(message.Type, receivedEventMessage.EventType); Assert.AreEqual(message.Id, receivedEventMessage.CorrelationId); Assert.AreEqual(message.Timestamp, receivedEventMessage.Timestamp); Assert.AreEqual(queueName, receivedEventArgs.QueueName); Assert.AreEqual(1, receivedEventArgs.TopicExpressions.Count()); Assert.AreEqual(topicExpression, receivedEventArgs.TopicExpressions.Single()); }
public void AddingListenerRegistersProperReceiver() { // Arrange var testContext = new TestBusContext(); var hostBuilder = new MicroserviceHostBuilder().WithBusContext(testContext); // Act hostBuilder.AddEventListener <EventListenerDummy>(); hostBuilder.WithQueueName("test.queue"); hostBuilder.CreateHost().Start(); // Assert var message = new DummyEvent("TestTopic"); new EventPublisher(testContext).Publish(message); Thread.Sleep(WaitTime); Assert.AreEqual(message, EventListenerDummy.HandlesResult); }
public void EventListenerIsCalledWithCorrectEvent() { var serviceMock = new Mock <IServiceMock>(MockBehavior.Strict); serviceMock.Setup(d => d.PerformAction()); using (var context = new TestBusContext()) { var builder = new MicroserviceHostBuilder() .RegisterDependencies((services) => { services.AddSingleton(serviceMock.Object); }) .WithContext(context) .UseConventions(); using (var host = builder.CreateHost()) { host.StartListening(); var eventPublisher = new EventPublisher(context); var exampleEvent = new ExampleEvent("XMPL.ExampleEvent") { Message = "Example message." }; eventPublisher.Publish(exampleEvent); } var eventListenerIsCalled = EventListenerMock.ResetEvent.WaitOne(1000); Assert.IsTrue(eventListenerIsCalled); var actualEvent = EventListenerMock.ExampleEvent; Assert.AreEqual("XMPL.ExampleEvent", actualEvent.RoutingKey); Assert.AreEqual("Example message.", actualEvent.Message); serviceMock.VerifyAll(); } }
/** * An example implementation on how to set up a * MicroserviceHost with RabbitMQ in the Main method * * Setting up a functioning RabbitMQ instance with docker is as easy as running: * docker run -d -p 15672:15672 -p 5672:5672 rabbitmq:3-management */ static void Main(string[] args) { /* * Logging is quite important, for this reason we first create * a loggerfactory that will be used in the rest of the application * * This one outputs to the console */ using ILoggerFactory loggerFactory = LoggerFactory.Create(configure => { configure.AddConsole().SetMinimumLevel(LogLevel.Error); }); /* * To reach the library classes, a static class has been put in place * to register a logger */ MiffyLoggerFactory.LoggerFactory = loggerFactory; RabbitMqLoggerFactory.LoggerFactory = loggerFactory; /* * Now that the logger is done, let's create a RabbitMq context with * an exchange called MVM.EventExchange and a connection string * that connects to a local RabbitMQ instance */ RabbitMqContextBuilder contextBuilder = new RabbitMqContextBuilder() .WithExchange("MVM.EventExchange") .WithConnectionString("amqp://*****:*****@localhost"); /* * Now instantiate the context and ensure that it's disposed of by using a * 'using' statement. */ using IBusContext <IConnection> context = contextBuilder.CreateContext(); /** * Create a dummy database context for testing with an in-memory database */ PolisContext databaseContext = new PolisContext(); /** * Now create a builder that will build our microservice host. * * First, register our logger by setting the logger factory, * next we register any dependencies we might need, like a DBContext * that is injected into our CommandListeners and EventListeners * * Since most of the inner workings of this framework are asynchronous, we * strongly urge you to set up a loggerfactory to quickly find any errors going over the bus. * * Then, throw our context into the builder and lastly, ensure that * all our event/command listeners are registered by calling UseConventions(). * * UseConventions could be replaced by multiple AddEventListener calls. */ MicroserviceHostBuilder builder = new MicroserviceHostBuilder() .SetLoggerFactory(loggerFactory) // This method also accepts a service collection as input .RegisterDependencies(services => { services.AddSingleton(databaseContext); }) .WithQueueName("ExampleService.Queue") .WithBusContext(context) .UseConventions(); /** * Lastly, instantiate a host and ensure it starts */ using IMicroserviceHost host = builder.CreateHost(); host.Start(); /** * Let's add a C# event listener for fun */ host.EventMessageReceived += (message, eventArgs) => { Console.WriteLine("Received a EventMessage!"); }; /** * Now let's pretend this service is running somewhere in a cluster * and is receiving events, let's fire some events at it */ string[] names = { "Jack", "Jake", "Penny", "Robin", "Rick", "Vinny", "Spencer" }; IEventPublisher publisher = new EventPublisher(context, loggerFactory); foreach (string name in names) { PolisToegevoegdEvent toegevoegdEvent = new PolisToegevoegdEvent { Polis = new Polis { Klantnaam = name } }; publisher.PublishAsync(toegevoegdEvent); } /** * Now let's wait 1 second for all the events to arrive and be processed */ Thread.Sleep(2000); /** * Now let's fire a command and retrieve a list of polissen */ ICommandPublisher commandPublisher = new CommandPublisher(context, loggerFactory); HaalPolissenOpCommand command = new HaalPolissenOpCommand(); HaalPolissenOpCommandResult commandResult = commandPublisher.PublishAsync <HaalPolissenOpCommandResult>(command).Result; /** * Now, print the result! */ foreach (Polis polis in commandResult.Polissen) { Console.WriteLine($"Found polis for {polis.Klantnaam} with ID {polis.Id}"); } /** * Now let's see what happens if we send a mangled json event * * This should log a critical error in the console and tell you how you might be able to diagnose the problem. */ publisher.Publish(0, "MVM.Polisbeheer.PolisToegevoegd", Guid.Empty, "PolisToegevoegdEvent", "{[somerandomjson}]"); /** * Lastly, let's see how the queue deals with exceptions on the other side */ ExceptionCommand exceptionCommand = new ExceptionCommand(); try { /** * This will throw an exception in the receiver */ _ = commandPublisher.PublishAsync <ExceptionCommand>(exceptionCommand).Result; } catch (AggregateException expectedException) { DestinationQueueException destinationQueueException = expectedException.InnerExceptions.First() as DestinationQueueException; /** * Now the expectedException.Innerexception will reveal all the info we need */ Console.WriteLine($"{destinationQueueException?.InnerException?.GetType().Name} {destinationQueueException?.InnerException?.Message}"); Console.WriteLine($"Destination queue: {destinationQueueException?.DestinationQueueName}, " + $"Reply queue: {destinationQueueException?.ReplyQueueName}, " + $"Id: {destinationQueueException?.CorrelationId}"); } }
public void Initialize() { connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); options = new DbContextOptionsBuilder <BeheerContext>() .UseSqlite(connection) .Options; using (var context = new BeheerContext(options)) { context.Database.EnsureCreated(); var artikel = new Artikel { Artikelnummer = 1, Beschrijving = "Grote fiets voor iedereen", LeverbaarTot = new DateTime(2018, 5, 5), LeverbaarVanaf = new DateTime(2017, 1, 1), Naam = "Fiets", Prijs = 40m, Voorraad = 5 }; var artikel2 = new Artikel { Artikelnummer = 2, Beschrijving = "HELE grote fiets voor iedereen", LeverbaarTot = new DateTime(2018, 5, 5), LeverbaarVanaf = new DateTime(2017, 1, 1), Naam = "Fiets Groot", Prijs = 100m, Voorraad = 8 }; var klant = new Klant { Voornaam = "Hans", Achternaam = "Van Huizen", Id = "1" }; var klantDatamapper = new KlantDatamapper(context); klantDatamapper.Insert(klant); var datamapper = new ArtikelDatamapper(context); datamapper.Insert(artikel); datamapper.Insert(artikel2); } _context = new TestBusContext(); var services = new ServiceCollection(); services.AddTransient <ICommandPublisher, CommandPublisher>(); services.AddSingleton <DbContextOptions>(options); services.AddTransient <BeheerContext, BeheerContext>(); services.AddTransient <IArtikelDatamapper, ArtikelDatamapper>(); services.AddTransient <IBestellingDatamapper, BestellingDatamapper>(); services.AddSingleton <IBusContext <IConnection> >(_context); services.AddTransient <IEventPublisher, EventPublisher>(); services.AddTransient <IKlantDatamapper, KlantDatamapper>(); var builder = new MicroserviceHostBuilder() .RegisterDependencies(services) .WithContext(_context) .AddCommandListener <BestellingListener>() .AddCommandListener <BestellingListenerIntegratieTest>() .AddEventListener <BestellingListener>(); _host = builder.CreateHost(); _host.StartListening(); }