public void Init() { _busOptions = new BusOptions { ExchangeName = "TestExchange1", HostName = "localhost", Port = 5672, Username = "******", Password = "******" }; _direct = new BusOptions { ExchangeName = "", HostName = "localhost", Port = 5672, Username = "******", Password = "******" }; }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); Func <IServiceProvider, LogService> logServiceFactory = (provider) => new LogService(new DirectoryInfo(Environment.GetEnvironmentVariable("logpath"))); Func <IServiceProvider, RabbitMqConnection> rabbitMqConnectionFactory = (provider) => new RabbitMqConnection(BusOptions.CreateFromEnvironment()); Func <IServiceProvider, RdwApkAgent> rwdAgentFactory = (provider) => new RdwApkAgent(Environment.GetEnvironmentVariable("rdw-requesturl")); Func <IServiceProvider, RdwApkManager> apkManagerFactory = provider => new RdwApkManager( provider.GetService <IRdwApkAgent>(), provider.GetService <IKeuringsVerzoekConverter>(), provider.GetService <IRepository <ApkAanvraagLog, long> >(), Environment.GetEnvironmentVariable("keuringsverzoek-xmlns"), Environment.GetEnvironmentVariable("keuringsverzoek-apk"), provider.GetService <IEventPublisher>() ) ; services.AddSingleton <ILogService, LogService>(logServiceFactory); services.AddScoped <IRabbitMqConnection, RabbitMqConnection>(rabbitMqConnectionFactory); services.AddScoped <IEventPublisher, EventPublisher>(); services.AddScoped <IRdwApkAgent, RdwApkAgent>(rwdAgentFactory); services.AddScoped <IRdwApkManager, RdwApkManager>(apkManagerFactory); services.AddScoped <IKeuringsVerzoekConverter, KeuringsVerzoekConverter>(); // Setup database with docker connectionstring var dockerConnectionString = Environment.GetEnvironmentVariable("dbconnectionstring"); services.AddDbContext <RdwContext> ( options => options.UseSqlServer(dockerConnectionString) ); services.AddScoped <IRepository <ApkAanvraagLog, long>, ApkAanvraagLogRepository>(); services.AddSwaggerGen(); services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "RDW Integration Service", Description = "RDW Integration Service", TermsOfService = "None" }); }); }
public EventPublishService(IConnection connection, IModel channel, BusOptions busOptions = null) { _connection = connection; _channel = channel; BusOptions = busOptions ?? new BusOptions(); // Declare exchange _channel.ExchangeDeclare(BusOptions.ExchangeName, ExchangeType.Topic); }
private static void RegisterBusOptions(this IContainer container, Action <BusOptions> busOptionsSetup) { var busOptions = new BusOptions(); busOptionsSetup?.Invoke(busOptions); busOptions.Client = busOptions.Client ?? Queues.Default; container.RegisterInstance(busOptions); }
public void Dispatcher_DuplicateMethodWithParameterName() { // Arrange var options = new BusOptions { ExchangeName = "TestExchange1", HostName = "Localhost", Port = 5672, Username = "******", Password = "******" }; Action act = () => new TestDispatcherWithDuplicateParameters(options); Assert.ThrowsException <DuplicateMethodWithSameEventParameterException>(act); }
public void MicroserviceHostFindsQueueNameInBusOptions() { var options = new BusOptions { QueueName = "ThrowAwayName" }; using (var host = new MicroserviceHost <OtherMicroserviceMock>(options)) { Assert.Equal(1, host.ServiceModel.QueueNames.Count()); Assert.True(host.ServiceModel.QueueNames.Contains("ThrowAwayName")); } }
public async Task PublishAsync <TMessage>(string contextName, TMessage message, Action <IBusOptions> config = null) where TMessage : IBusMessage { IBusOptions options = new BusOptions(ConnectionStringNames.Rabbit); config?.Invoke(options); await Task.Run(() => { Get(options.Key).Enqueue(contextName, message); }); }
public MicroserviceProxy(BusOptions options = default(BusOptions)) : base(options) { try { Open(); } catch { Dispose(); throw; } }
public void DefaultBusoptions() { // Act var result = new BusOptions(); // Assert Assert.Equal("WSA.DefaultEventBus", result.ExchangeName); Assert.Equal(null, result.QueueName); Assert.Equal("localhost", result.HostName); Assert.Equal(5672, result.Port); Assert.Equal("guest", result.UserName); Assert.Equal("guest", result.Password); }
public void CustomBusoptions() { var options = new BusOptions { HostName = "127.0.0.1" }; using (var target = new EventPublisher(options)) { var result = target.BusOptions; Assert.Equal("127.0.0.1", result.HostName); } }
/// <summary> /// Конвертирует настройки публикации сообщения в заголовки сообщения. /// </summary> /// <param name="requestOptions">Настройки публикации сообщения.</param> /// <returns>Заголовки сообщения.</returns> private IDictionary <string, object> ApplyOptions(RequestOptions requestOptions) { IDictionary <string, object> headers = this.ApplyOptions(requestOptions as PublishingOptions); Maybe <TimeSpan?> timeout = BusOptions.Pick(requestOptions.Timeout, this.Configuration.Options.GetRequestTimeout()); if (timeout != null && timeout.HasValue) { headers[Headers.Timeout] = timeout.Value; } return(headers); }
public AuditPublisher(BusOptions options = null) { var busOptions = options ?? new BusOptions(); ConnectionFactory factory = new ConnectionFactory { HostName = busOptions.HostName, UserName = busOptions.Username, Password = busOptions.Password, Port = busOptions.Port, }; _connection = factory.CreateConnection(); _model = _connection.CreateModel(); }
public EventDispatcher(BusOptions options = null, string queueName = null) { var type = this.GetType(); var routingKey = type.GetTypeInfo().GetCustomAttributes <RoutingKeyAttribute>().FirstOrDefault()?.Topic ?? "#"; var attributeOptions = type.GetTypeInfo().GetCustomAttributes <BusOptions>().FirstOrDefault(); var busOptions = options ?? attributeOptions ?? new BusOptions(); _channel = new Channel(busOptions); _channel.CreateBinding(queueName, routingKey); SetupMethodInfo(); _channel.Consume(OnReceivedEvent); }
public Channel(BusOptions busOptions) { _busOptions = busOptions; ConnectionFactory factory = new ConnectionFactory { HostName = busOptions.HostName, UserName = busOptions.Username, Password = busOptions.Password, Port = busOptions.Port, RequestedHeartbeat = 60 }; _connection = factory.CreateConnection(); _model = _connection.CreateModel(); }
public Bus( BusOptions options, ILogger <Bus> logger, IStorageApiWrapper storageApiWrapper, ILifetimeScope lifetimeScope, IClock clock) { _busOptions = options; _logger = logger; _storageApiWrapper = storageApiWrapper; _lifetimeScope = lifetimeScope; _clock = clock; MessageHandlerCollection = new MessageHandlerCollection(_clock); BusId = RandomIdHelper.GetId(); }
public static void Main(string[] args) { string connectionString = @"server=db;userid=admin;password=1234;database=auditlog;"; DbContextOptions options = new DbContextOptionsBuilder().UseMySQL(connectionString).Options; AuditLogDbContext context = new AuditLogDbContext(options); BusOptions busOptions = new BusOptions(hostname: "rabbitmq", port: 5672, username: "******", password: "******", exchangeName: "Lapiwe.GMS"); using (IRepository repo = new AuditLogRepository(context)) using (var all = new AllEventDispatcher(repo, busOptions)) using (var publisher = new AuditPublisher(busOptions)) using (var dispatcher = new AuditDispatcher(repo, publisher, busOptions)) { Console.Read(); } }
public void PublishedTestEventIsReceivedByOtherRoutingKey() { var options = new BusOptions { ExchangeName = "TestExchange5", HostName = "Localhost", Port = 5672, Username = "******", Password = "******" }; using (var consumer = new TestDispatcherAttribute(options)) using (var target = new EventPublisher(options)) { target.Publish(new TestEvent("Test.Routing")); Thread.Sleep(100); Assert.AreEqual(1, consumer.receivedTestEventCount); } }
public void DispatcherUsesBusOptionsAttribute() { var options = new BusOptions { ExchangeName = "TestExchange1", HostName = "Localhost", Port = 5672, Username = "******", Password = "******" }; using (var consumer = new TestDispatcherBusOptionsAttribute(options)) using (var target = new TestPublisherAttr(options)) { target.Publish(new TestEvent()); Thread.Sleep(100); Assert.AreEqual(1, consumer.receivedTestEventCount); } }
public void Init(ref BusOptions busoptions, ref ParamListContainer deviceParamlistContainer, ref ParamListContainer sflParamlistContainer) { m_busoption = busoptions; m_Section_ParamlistContainer = deviceParamlistContainer; m_SFLs_ParamlistContainer = sflParamlistContainer; //SectionParameterListInit(ref deviceParamlistContainer); m_HwMode_RegList.Add(ElementDefine.OperationElement, m_OpRegImg); SharedAPI.ReBuildBusOptions(ref busoptions, ref deviceParamlistContainer); InitialImgReg(); m_dem_bm.Init(this); m_dem_dm.Init(this); LibInfor.AssemblyRegister(Assembly.GetExecutingAssembly(), ASSEMBLY_TYPE.OCE); }
public async Task ConcurrentAsync() { var options = new BusOptions { EnvelopName = "afEvent" }; var api = new MemoryStorageApi(options); using var mocker = AutoMock.GetLoose(builder => { builder.RegisterInstance(api) .AsImplementedInterfaces(); }); var factory = mocker.Create <Bus.Factory>(); var channel = factory.Invoke(options); await channel.EnsureStartAsync(); channel.RegisterHandler <TestRequest>((scope, payload, message) => { channel.SendResponse(new TestResponse { Greetings = GetGreetings(payload.Name) }, message); }); const int maxCount = 100; // act var tasks = Enumerable.Range(0, maxCount) .Select(x => channel.SendRequest <TestRequest, TestResponse>(new TestRequest { Name = x.ToString() })); var results = await Task.WhenAll(tasks); var expectation = Enumerable.Range(0, maxCount) .Select(x => GetGreetings(x.ToString())).OrderBy(x => x); results.Select(x => x.Greetings).OrderBy(x => x) .Should().BeEquivalentTo(expectation); channel.MessageHandlerCollection.HandlerItems.Count.Should().Be(1); string GetGreetings(string n) { return($"hi, {n}"); } }
public void MicroserviceHostFailsIfRabbitMQIsNotReachable() { var serviceMock = new SomeMicroserviceMock(); var options = new BusOptions { HostName = "NonExistingName" }; MicroserviceConfigurationException ex = Assert.Throws <MicroserviceConfigurationException>(() => { using (var host = new MicroserviceHost <SomeMicroserviceMock>(serviceMock, options)) { host.Open(); } }); Assert.Equal("The Eventbus (RabbitMQ service) cannot be reached.", ex.Message); }
public static void Main(string[] args) { var options = BusOptions.CreateFromEnvironment(); var logger = new LogService(new DirectoryInfo(Path.Combine(Environment.GetEnvironmentVariable("logpath"), "RabbitMqLog"))); var dbConnectionString = Environment.GetEnvironmentVariable("dbconnectionstring"); var eventListener = new MaRoWoEventListener(options, dbConnectionString, logger); eventListener.Start(); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .Build(); host.Run(); }
public void EventDispatcherBusOptionsNullExpectDefaultTest() { // Arrange using (var eventDispatcher = new EventDispatcherMock()) { // Act var expectedBusOptions = new BusOptions(); // Assert Assert.AreEqual(expectedBusOptions.ExchangeName, eventDispatcher.BusOptions.ExchangeName); Assert.AreEqual(expectedBusOptions.HostName, eventDispatcher.BusOptions.HostName); Assert.AreEqual(expectedBusOptions.Port, eventDispatcher.BusOptions.Port); Assert.AreEqual(expectedBusOptions.UserName, eventDispatcher.BusOptions.UserName); Assert.AreEqual(expectedBusOptions.Password, eventDispatcher.BusOptions.Password); Assert.IsNotNull(eventDispatcher.BusOptions.QueueName); } }
public void PublishedTestEventReceivedByTwoDispatchers() { var options = new BusOptions { ExchangeName = "TestExchange3", HostName = "Localhost", Port = 5672, Username = "******", Password = "******" }; using (var consumer1 = new TestDispatcher(options)) using (var consumer2 = new TestDispatcher(options)) using (var target = new EventPublisher(options)) { target.Publish(new TestEvent()); Thread.Sleep(100); Assert.AreEqual(1, consumer1.receivedTestEventCount); Assert.AreEqual(1, consumer2.receivedTestEventCount); } }
public void MicroserviceHostSilentlyIgnoresUnknownCommands() { var serviceMock = new SomeMicroserviceMock(); using (var host = new MicroserviceHost <SomeMicroserviceMock>(serviceMock)) { var options = new BusOptions() { QueueName = "microserviceQueue" }; var command = new KeyValuePair <string, int>("Test", 42); SendMessage(command, options); serviceMock.ReceivedFlag.WaitOne(500); Assert.False(serviceMock.SomeCommandHandlerHasBeenCalled); Assert.False(serviceMock.TestCommandHandlerHasBeenCalled); } }
public Task <RabbitMqHelper> Initialize(Bus bus, BusOptions options) { this.bus = bus; this.options = options; //this.waitingList = waitingList; try { this.IsActive = this.GetConnection(true) != null; this.IsActive = this.IsActive && this.GetRequestChannel() != null; this.GetReplyChannel(); } catch (Exception err) { this.IsActive = false; } return(Task.FromResult(this)); }
public MqttEventBus( IMqttPersisterConnection mqttPersisterConnection, IEventProvider eventProvider, IConsumeMethodInvoker consumeMethodInvoker, IEventBusLogger <MqttEventBus> logger, IServiceScopeFactory scopeFactory, ISubscriptionsManager subsManager, BusOptions busOptions) { _mqttPersisterConnection = mqttPersisterConnection ?? throw new ArgumentNullException(nameof(mqttPersisterConnection)); _mqttPersisterConnection.ClientConnectionChanged += OnConnectionLostAsync; _eventProvider = eventProvider; _consumeMethodInvoker = consumeMethodInvoker; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _subsManager = subsManager ?? throw new ArgumentNullException(nameof(ISubscriptionsManager)); _retryCount = busOptions?.RetryCount ?? 5; _scopeFactory = scopeFactory; _asyncLocker = new SemaphoreSlim(busOptions.MaxConcurrentCalls, busOptions.MaxConcurrentCalls); }
public void ConfigureServices(IServiceCollection services) { var idInfo = new IdentifyingInformation( "communications", "Comms.Reservation.Reminder.Policy", "*****@*****.**"); var busOpts = new BusOptions() .SetIdentifyingInformation(idInfo) .SetLogger(EDALogger.Global) .SetRegion(Region.RS); busOpts.SetDeployEnvironment(DeployEnvironment.PP); bool connected = false; int attempt = 1; while (!connected && attempt < 5) { try { services.AddSingleton <IBus>(new Bus(busOpts)); connected = true; } catch (Exception e) { Console.WriteLine($"Error contacting EDA ({e.Message})"); Console.WriteLine(e); attempt++; Thread.Sleep(TimeSpan.FromSeconds(attempt * 10)); } } if (!connected) { throw new ApplicationException("Could not connect to EDA (I did try a few times but it would not answer)"); } services.AddSingleton <IEdaSource, EdaSource>(); services.AddSingleton <IConsumeFromEda, ReservationConsumer>(); services.AddSingleton <IHostedService, GuestGroupChat>(); }
public void RoutingKeyWorksWithNonAllowingKey() { BusOptions options = new BusOptions { ExchangeName = "TestExchange_RoutingTest" }; using (var publisher = new EventPublisher(options)) using (var target = new RoutedDispatcherMock(options)) { target.Open(); publisher.Publish(new TestEvent()); Thread.Sleep(100); Assert.False(target.TestEventHandlerHasBeenCalled, "TestEventHandler should NOT have been called"); Assert.False(target.RoutedEventHandlerHasBeenCalled, "RoutedEventHandler should NOT have been called"); } }
/// <summary> /// Конвертирует настройки публикации сообщения в заголовки сообщения. /// </summary> /// <param name="options">Настройки публикации сообщения.</param> /// <returns>Заголовки сообщения.</returns> private IDictionary <string, object> ApplyOptions(PublishingOptions options) { var storage = this.Configuration.Options.GetIncomingMessageHeaderStorage().Value; var inputHeaders = storage.Load() ?? new Dictionary <string, object>(); var outputHeaders = new Dictionary <string, object>(inputHeaders); Headers.ApplyBreadcrumbs(outputHeaders, this.endpoint.Address); Headers.ApplyOriginalMessageId(outputHeaders); Maybe <bool> persist = BusOptions.Pick(options.Persistently, this.Configuration.Options.IsPersistently()); Headers.ApplyPersistently(outputHeaders, persist); Maybe <TimeSpan?> ttl = BusOptions.Pick(options.Ttl, this.Configuration.Options.GetTtl()); Headers.ApplyTtl(outputHeaders, ttl); return(outputHeaders); }
/// <summary> /// Инициализирует новый экземпляр класса <see cref="RabbitReceiverOptions"/>. /// </summary> /// <param name="parent"> /// The parent. /// </param> public RabbitReceiverOptions(BusOptions parent) : base(parent) { }
/// <summary> /// Инициализирует новый экземпляр класса <see cref="SenderOptions"/>. /// </summary> /// <param name="parent">Базовые настройки.</param> public SenderOptions(BusOptions parent) : base(parent) { }