public ActionResult <Message> PostMessage(
            [FromServices] RabbitMQConfigurations configurations,
            [FromBody] Message message)
        {
            lock (_COUNTER)
            {
                _COUNTER.Increment();

                var factory = new ConnectionFactory()
                {
                    HostName = configurations.HostName,
                    Port     = configurations.Port,
                    UserName = configurations.UserName,
                    Password = configurations.Password
                };

                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        message.Id        = _COUNTER.Value;
                        message.CreatedOn = DateTime.Now;
                        var serializerSettings = new JsonSerializerSettings();
                        serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                        var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, serializerSettings));
                        channel.BasicPublish(exchange: "subject_logs",
                                             routingKey: message.Type,
                                             basicProperties: null,
                                             body: body);
                    }
                return(CreatedAtAction(nameof(PostMessage), new { id = _COUNTER }, message));
            }
        }
        private void Configuracao()
        {
            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            var factory = new ConnectionFactory()
            {
                HostName = rabbitMQConfigurations.HostName,
                Port     = rabbitMQConfigurations.Port,
                UserName = rabbitMQConfigurations.UserName,
                Password = rabbitMQConfigurations.Password
            };

            _connection = factory.CreateConnection();

            _channel = _connection.CreateModel();

            _channel.QueueDeclare(queue: filaAdmissao,
                                  durable: false,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);

            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += Consumer_Received;
            _channel.BasicConsume(queue: filaAdmissao,
                                  autoAck: true,
                                  consumer: consumer);
        }
Beispiel #3
0
        public object Post([FromServices] RabbitMQConfigurations configurations, [FromBody] MessageDTO message)
        {
            var factory = new ConnectionFactory()
            {
                HostName = configurations.HostName,
                Port     = configurations.Port,
                UserName = configurations.UserName,
                Password = configurations.Password
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "web-api-test-queue",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    string formattedMessage =
                        $"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} - {Guid.NewGuid()} - Conteúdo da Mensagem: {message.Content}";
                    var body = Encoding.UTF8.GetBytes(formattedMessage);

                    channel.BasicPublish(exchange: "",
                                         routingKey: "web-api-test-queue",
                                         basicProperties: null,
                                         body: body);
                }

            return(new
            {
                Result = "Mensagem encaminhada com sucesso"
            });
        }
Beispiel #4
0
        public ReviewEventsManager([FromServices] RabbitMQConfigurations rabbitMQConfiguration, IServiceScopeFactory serviceScopeFactory, ILogService logger)
        {
            Console.WriteLine($"{nameof(ReviewEventsManager)} initialized");
            _logger = logger;

            try
            {
                _serviceScopeFactory = serviceScopeFactory;
                _factory             = new ConnectionFactory()
                {
                    HostName = rabbitMQConfiguration.HostName,
                    Port     = rabbitMQConfiguration.Port,
                    UserName = rabbitMQConfiguration.UserName,
                    Password = rabbitMQConfiguration.Password
                };

                _connection = _factory.CreateConnection();
                _channel    = _connection.CreateModel();
            }
            catch (Exception ex)
            {
                _logger.Log(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error, System.Net.HttpStatusCode.InternalServerError, nameof(ReviewEventsManager));
                throw ex;
            }
        }
Beispiel #5
0
        public object Post([FromServices] RabbitMQConfigurations configurations, Conteudo conteudo)
        {
            lock (_contador)
            {
                _contador.Incrementar();

                var factory = new ConnectionFactory()
                {
                    HostName = configurations.HostName,
                    Port     = configurations.Port,
                    UserName = configurations.UserName,
                    Password = configurations.Password
                };

                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: "TestesASPNETCore", durable: false, exclusive: false, autoDelete: false, arguments: null);
                        string message = $"{DateTime.Now.ToLongDateString()} - Conte'udo da mensgem: {conteudo.Mensagem}";

                        var body = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "", routingKey: "TestesASPNETCore", basicProperties: null, body: body);
                    }
            }

            return(new
            {
                Resultado = "Mensagem encaminhada com sucesso"
            });
        }
Beispiel #6
0
        public DeliveriesEventManager(IServiceScopeFactory serviceScopeFactory, [FromServices] RabbitMQConfigurations rabbitMQConfiguration, ILogService logger)
        {
            Console.WriteLine($"{nameof(DeliveriesEventManager)} initialized");
            _logger = logger;

            try
            {
                _serviceScopeFactory = serviceScopeFactory;

                _factory = new ConnectionFactory()
                {
                    HostName = rabbitMQConfiguration.HostName,
                    Port     = rabbitMQConfiguration.Port,
                    UserName = rabbitMQConfiguration.UserName,
                    Password = rabbitMQConfiguration.Password
                };

                _connection = _factory.CreateConnection();
                _channel    = _connection.CreateModel();

                _channel.QueueDeclare(queue: ApplicationEvents.OrderQueue, durable: true, exclusive: false, autoDelete: false, arguments: null);
                _channel.QueueDeclare(queue: ApplicationEvents.DeliveryQueue, durable: true, exclusive: false, autoDelete: false, arguments: null);

                var consumer = new EventingBasicConsumer(_channel);
                consumer.Received += DeliveryEvent_Received;
                _channel.BasicConsume(ApplicationEvents.DeliveryQueue, true, consumer);
            }
            catch (Exception ex)
            {
                _logger.Log(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error, System.Net.HttpStatusCode.InternalServerError, nameof(DeliveriesEventManager));
                throw ex;
            }
        }
Beispiel #7
0
        public IActionResult StartMeasure(
            [FromBody] StartMeasureModel measureModel,
            [FromServices] RabbitMQConfigurations configurations
            )
        {
            var factory = new ConnectionFactory()
            {
                HostName = configurations.HostName,
                Port     = configurations.Port,
                UserName = configurations.UserName,
                Password = configurations.Password,
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "Measure",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    string Message = $"Mac={measureModel.MacAddress};UserId={measureModel.UserId}";
                    var    body    = Encoding.UTF8.GetBytes(Message);

                    channel.BasicPublish(exchange: "", "Measure", null, body);
                }

            return(Ok(true));
        }
Beispiel #8
0
        public static void Main(string[] args)
        {
            //Wait RabbitMq
            Task.Delay(1000).Wait();
            Console.WriteLine("Wait RabbitMq");

            //Set configurations
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile($"appsettings.json");

            _configuration = builder.Build();

            //Import configurations from appsettings.json
            var rabbitMQConfigurations = new RabbitMQConfigurations();

            _configuration.GetSection("RabbitMQConfigurations").Bind(rabbitMQConfigurations);


            // Start to Message Broker
            MessageService messageService = new MessageService(rabbitMQConfigurations);

            //Create a Consumer to listening weatherForecastResponse queue.
            CreateConsumer(messageService.Channel());
            CreateHostBuilder(args).Build().Run();
        }
        public object CarregarCotacoes(
            [FromServices] RabbitMQConfigurations rabbitMQConfigurations)
        {
            var factory = new ConnectionFactory()
            {
                HostName = rabbitMQConfigurations.HostName,
                Port     = rabbitMQConfigurations.Port,
                UserName = rabbitMQConfigurations.UserName,
                Password = rabbitMQConfigurations.Password
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "CarregarCotacoes",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    string message = "Hello Word - " +
                                     $"API Cotacoes - {DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}";
                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "",
                                         routingKey: "CarregarCotacoes",
                                         basicProperties: null,
                                         body: body);
                }

            return(new
            {
                Resultado = "Mensagem encaminhada com sucesso"
            });
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // configure DI for application services
            services.AddScoped <IPaymentService, PaymentService>();
            services.AddSingleton <ILogService, LogService>();
            services.AddHostedService <ReceiptService>();

            services.AddDbContext <PaymentDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("FokPaymentDB"));
            });

            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            services.AddSingleton(rabbitMQConfigurations);

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            Mapper.Initialize(cfg => cfg.AddProfile <MappingProfile>());
            services.AddAutoMapper();
        }
Beispiel #11
0
        public void DeveriaProcessarAListaDoLegado()
        {
            // Arrange
            var funcionariolegadoRepo = new Mock <IRepository <FornecedorLegado> >();

            funcionariolegadoRepo.Setup(c => c.List())
            .Returns(ObterFornecedoresVariados(10, true));

            RabbitMQConfigurations config = new RabbitMQConfigurations();

            config.HostName = "172.28.112.1";
            config.Port     = 5672;
            config.UserName = "******";
            config.Password = "******";
            FactoryRabbitMQ _factory = new FactoryRabbitMQ(config);
            MessageBroker   _broker  = new MessageBroker(_factory);


            //List<FornecedorLegado> lista = funcionariolegadoRepo.List();
            //var clienteService = new ClienteService(clienteRepo.Object, mediatr.Object);

            // Act
            //var clientes = clienteService.ObterTodosAtivos();

            // Assert
            //clienteRepo.Verify(r => r.ObterTodos(), Times.Once);
            //Assert.True(clientes.Any());
            //Assert.False(clientes.Count(c => !c.Ativo) > 0);

            ProcessamentoDoLegadoParaBroker processInt = new ProcessamentoDoLegadoParaBroker(funcionariolegadoRepo.Object, _broker);

            processInt.Process();
        }
Beispiel #12
0
        public async Task <IActionResult> ProcessMealWaiting(
            [FromServices] RabbitMQConfigurations configurations,
            [FromServices] ConnectionFactory factory,
            [FromServices] IConnection connection,
            [FromServices] IConsumeRabbitMQService consumer)
        {
            try{
                var result = await consumer.ProcessQueue("Meal - waiting");

                if (result != null)
                {
                    using (var channel = connection.CreateModel())
                    {
                        var queue = channel.QueueDeclare(queue: "Command Queue",
                                                         durable: false,
                                                         exclusive: false,
                                                         autoDelete: false,
                                                         arguments: null);


                        //RabbitMQExtensions.GetAllMessages(queue ,configurations, "Side Dish - waiting");

                        string message = JsonConvert.SerializeObject(result);
                        var    body    = Encoding.UTF8.GetBytes(message);


                        channel.BasicPublish(exchange: "",
                                             routingKey: "Meal - preparing",
                                             basicProperties: null,
                                             body: body);

                        //channel.WaitForConfirmsOrDie(new TimeSpan(0, 0, 5));

                        //Dictionary<string, string> headers = new Dictionary<string, string>();

                        var properties = channel.CreateBasicProperties();

                        properties.Persistent = false;

                        Dictionary <string, object> dictionary = new Dictionary <string, object>();

                        dictionary.Add("Command", "MealPreparing");
                        properties.Headers = dictionary;

                        channel.BasicPublish(exchange: "",
                                             routingKey: "Command Queue",
                                             basicProperties: properties,
                                             body: body);

                        //channel.WaitForConfirmsOrDie(new TimeSpan(0, 0, 5));
                    }
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
Beispiel #13
0
        public IActionResult ShowQueueItem(
            [FromServices] RabbitMQConfigurations configurations,
            [FromServices] ConnectionFactory factory,
            [FromServices] IConnection connection,
            [FromServices] IConsumeRabbitMQService consumer,
            string kitchenAreaName,
            string status)
        {
            try
            {
                using (var channel = connection.CreateModel())
                {
                    var queue = channel.QueueDeclare(queue: kitchenAreaName + " - " + status,
                                                     durable: false,
                                                     exclusive: false,
                                                     autoDelete: false,
                                                     arguments: null);

                    var result = RabbitMQExtensions.GetAllMessages(queue, configurations, queue.QueueName);

                    if (result == null)
                    {
                        return(BadRequest());
                    }
                    return(Ok(result));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
        public MessageService(RabbitMQConfigurations configurations)
        {
            Console.WriteLine("[ Manager ] connecting to rabbit");

            _factory = new ConnectionFactory()
            {
                HostName = (InDocker) ? configurations.HostNameDocker : configurations.HostName,
                Port     = configurations.Port,
                UserName = configurations.UserName,
                Password = configurations.Password
            };

            if (InDocker)
            {
                _factory.HostName = configurations.HostNameDocker;
            }

            _conn = _factory.CreateConnection();

            _channel = _conn.CreateModel();
            _channel.QueueDeclare(queue: Constants.RabbitQueuRequest,
                                  durable: false,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);

            _channel.QueueDeclare(queue: Constants.RabbitQueuResponse,
                                  durable: false,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);
        }
Beispiel #15
0
        private static IServiceCollection ConfigureDi(IServiceCollection services, IConfiguration config)
        {
            RabbitMQConfigurations.ConfigureServices(services, config);
            StorageConfigurations.ConfigureServices(services, config);

            return(services
                   .AddSingleton(config)

                   .AddTransient <IFileArchiver, FileArchiver>()
                   .Configure <FileArchiver>(config)
                   .AddTransient <IAzureService, AzureService>()
                   .Configure <AzureService>(config)
                   .AddTransient(x => new ProcessKiller(config))
                   .AddScoped <IQueueService, QueueService>()
                   .AddLogging(loggingBuilder =>
            {
                // configure Logging with NLog
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                loggingBuilder.AddNLog();
            })
                   .AddTransient <IAzureService, AzureService>()
                   .Configure <AzureService>(config)
                   .AddTransient <IProjectBuilder, ProjectBuilder>()

                   .AddTransient <GoConsoleBuilder>()
                   .AddTransient <TSConsoleBuilder>()
                   .AddTransient <CSharpConsoleBuilder>()
                   .Configure <CSharpConsoleBuilder>(config)
                   .Configure <TSConsoleBuilder>(config)
                   .Configure <GoConsoleBuilder>(config));
        }
        public static void GetAllMessages(QueueDeclareOk queue, RabbitMQConfigurations cfg, string queueName)
        {
            var credentials = new NetworkCredential()
            {
                UserName = cfg.UserName, Password = cfg.Password
            };

            using (var handler = new HttpClientHandler {
                Credentials = credentials
            })
                using (var client = new HttpClient(handler)) {
                    var url = $"http://{cfg.HostName}:{cfg.ManagementPort}/api/queues/{cfg.VirtualHost}/{queueName}/get";

                    var jsonContent = new {
                        ackmode  = "ack_requeue_true",
                        count    = queue.MessageCount.ToString(),
                        encoding = "auto",
                        truncate = "50000",
                        vhost    = cfg.VirtualHost
                    };

                    var content = new StringContent(JsonConvert.SerializeObject(jsonContent), Encoding.UTF8, "application/json");
                    var result  = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
                }
        }
Beispiel #17
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var webHostBuilder = WebHost.CreateDefaultBuilder();

            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                _configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            var mongoConfigurations = new MongoDBConfigurations();

            new ConfigureFromConfigurationOptions <MongoDBConfigurations>(
                _configuration.GetSection("MongoDBConfigurations"))
            .Configure(mongoConfigurations);

            var            mongoClient    = new MongoClient(string.Format("mongodb://{0}:{1}", mongoConfigurations.Host, mongoConfigurations.Port));
            IMongoDatabase mongoDb        = mongoClient.GetDatabase("LogsDB");
            var            logsCollection = mongoDb.GetCollection <BsonDocument>("Logs");

            var factory = new ConnectionFactory()
            {
                HostName = rabbitMQConfigurations.HostName,
                Port     = rabbitMQConfigurations.Port,
                UserName = rabbitMQConfigurations.UserName,
                Password = rabbitMQConfigurations.Password
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "logQueue", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    var consumer = new EventingBasicConsumer(channel);

                    consumer.Received += (model, ea) =>
                    {
                        var body    = ea.Body;
                        var message = System.Text.Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received:\n {0}", message);

                        BsonDocument document = BsonDocument.Parse(message);
                        try
                        {
                            logsCollection.InsertOne(document);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Error in mongoDB insert: {ex.Message}");
                        }
                    };

                    channel.BasicConsume(queue: "logQueue", autoAck: true, consumer: consumer);

                    while (!stoppingToken.IsCancellationRequested)
                    {
                        await Task.Delay(5000, stoppingToken);
                    }
                }
        }
Beispiel #18
0
 public RabbitMQConsumeHelper(
     RabbitMQConfigurations configurations,
     ConnectionFactory factory,
     IConnection connection)
 {
     this.configurations = configurations;
     this.factory        = factory;
     this.connection     = connection;
 }
Beispiel #19
0
        public BasketEventsManager(IServiceScopeFactory serviceScopeFactory, [FromServices] RabbitMQConfigurations rabbitMQConfiguration)
        {
            _serviceScopeFactory = serviceScopeFactory;

            _factory = new ConnectionFactory()
            {
                HostName = rabbitMQConfiguration.HostName,
                Port     = rabbitMQConfiguration.Port
            };
        }
        public static void RegisterCustomServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddScoped <JwtIssuerOptions>();

            BLLConfigurations.ConfigureServices(services, configuration);

            DALConfigurations.ConfigureServices(services, configuration);

            RabbitMQConfigurations.ConfigureServices(services, configuration);
        }
Beispiel #21
0
 private static ConnectionFactory GetConnectionFactory(RabbitMQConfigurations rabbitMQConfigurations)
 {
     return(new ConnectionFactory()
     {
         HostName = rabbitMQConfigurations.HostName,
         Port = rabbitMQConfigurations.Port,
         UserName = rabbitMQConfigurations.UserName,
         Password = rabbitMQConfigurations.Password
     });
 }
Beispiel #22
0
        public static void AddRabbitMQConfiguration(IServiceCollection services, IConfiguration configuration)
        {
            var rabbitMQConfiguration = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfiguration);

            services.AddSingleton(rabbitMQConfiguration);
        }
Beispiel #23
0
 public ConsumeRabbitMQHostedService(IServiceProvider serviceProvider,
                                     ILogger <ConsumeRabbitMQHostedService> logger)
 {
     _logger          = logger;
     _serviceProvider = serviceProvider;
     _channel         = (IModel)_serviceProvider.GetService(typeof(IModel));
     _connection      = (IConnection)_serviceProvider.GetService(typeof(IConnection));
     _configurations  = (RabbitMQConfigurations)_serviceProvider.GetService(typeof(RabbitMQConfigurations));
     _factory         = (ConnectionFactory)_serviceProvider.GetService(typeof(ConnectionFactory));
 }
        public object ExchangeQueue(
            [FromServices] RabbitMQConfigurations configurations,
            [FromBody] MessageContent conteudo)
        {
            lock (_CONTADOR)
            {
                _CONTADOR.Incrementar();

                var factory = new ConnectionFactory()
                {
                    HostName = configurations.HostName,
                    Port     = configurations.Port,
                    UserName = configurations.UserName,
                    Password = configurations.Password
                };

                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        string exchangeName = "exchange1";
                        string queueName    = "TestesASPNETCoreExchange";
                        string routingKey   = "routing1";

                        channel.ExchangeDeclare(exchangeName, ExchangeType.Direct);
                        //channel.QueueDeclare(queueName, false, false, false, null);


                        channel.QueueDeclare(queue: queueName,
                                             durable: false,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);

                        channel.QueueBind(queueName, exchangeName, routingKey, null);

                        string message =
                            $"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} - " +
                            $"Conteúdo da Mensagem: {conteudo.Message}";
                        var body = Encoding.UTF8.GetBytes(message);

                        channel.BasicPublish(exchange: exchangeName,
                                             routingKey: routingKey,
                                             basicProperties: null,
                                             body: body);
                    }

                return(new
                {
                    Resultado = "Mensagem encaminhada com sucesso"
                });
            }
        }
Beispiel #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <UserDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("FokUserDB"));
            });

            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.DateTimeItFormatter();

            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            services.AddSingleton(rabbitMQConfigurations);

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // configure DI for application services
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ILogService, LogService>();

            Mapper.Initialize(cfg => cfg.AddProfile <MappingProfile>());
            services.AddAutoMapper();
        }
Beispiel #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            services.AddSingleton(rabbitMQConfigurations);
            services.AddSingleton <IMessageService, MessageService>();
            services.AddSingleton <IWeatherForecastService, WeatherForecastService>();

            services.AddControllers();
        }
Beispiel #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSingleton <IConfiguration> (Configuration);

            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);


            var factory = new ConnectionFactory()
            {
                HostName    = rabbitMQConfigurations.HostName,
                Port        = rabbitMQConfigurations.Port,
                UserName    = rabbitMQConfigurations.UserName,
                Password    = rabbitMQConfigurations.Password,
                VirtualHost = rabbitMQConfigurations.VirtualHost
            };



            services.AddSingleton(factory);

            var connection = factory.CreateConnection();


            RabbitMQExtensions.EnsureExistRabbitMqVirtualHost(rabbitMQConfigurations, connection);



            var channel = connection.CreateModel();



            services.AddScopedServices();
            services.AddTransientServices();
            services.AddSingletonServices(ServiceProvider);

            channel.AddChannels();
            channel.ConfirmSelect();

            services.AddSingleton(rabbitMQConfigurations);
            services.AddLogging();
            services.AddSingleton(channel);
            services.AddSingleton(connection);
        }
Beispiel #28
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            var rabbitMQConfigurations = new RabbitMQConfigurations();
            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                hostContext.Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            services.AddMessageBusConfiguration(rabbitMQConfigurations);

            services.RegisterServices();

            services.AddHostedService <Worker>();
        });
Beispiel #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var rabbitMQConfigurations = new RabbitMQConfigurations();

            new ConfigureFromConfigurationOptions <RabbitMQConfigurations>(
                Configuration.GetSection("RabbitMQConfigurations"))
            .Configure(rabbitMQConfigurations);

            var connection = Configuration["ConexaoSqlite:SqliteConnectionString"];

            services.AddDbContext <ManagerWeatherContext>(options => options.UseSqlite(connection));

            services.AddSingleton(rabbitMQConfigurations);
            services.AddSingleton <IMessageService, MessageService>();
            services.AddSingleton(new WeatherRepository(new ManagerWeatherContext()));
            services.AddControllers();
        }
        public object Post(
            [FromServices] RabbitMQConfigurations configurations,
            [FromBody] Conteudo conteudo)
        {
            lock (_CONTADOR)
            {
                _CONTADOR.Incrementar();

                var factory = new ConnectionFactory()
                {
                    HostName = configurations.HostName,
                    Port     = configurations.Port,
                    UserName = configurations.UserName,
                    Password = configurations.Password
                };

                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: "NFeQueue",
                                             durable: false,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);


                        string message = System.Text.Json.JsonSerializer.Serialize(conteudo);

                        Console.WriteLine("Chegou a mensagem " + message);

                        var body = Encoding.UTF8.GetBytes(message);

                        channel.BasicPublish(exchange: "",
                                             routingKey: "NFeQueue",
                                             basicProperties: null,
                                             body: body);
                    }

                return(new
                {
                    Resultado = "Mensagem encaminhada com sucesso"
                });
            }
        }