Skip to content

Commit

Permalink
Merge pull request #37 from lrodolfol/main
Browse files Browse the repository at this point in the history
Send Upates
  • Loading branch information
tinosnegocios authored Aug 30, 2024
2 parents 3c04fae + a49836f commit a53b470
Show file tree
Hide file tree
Showing 70 changed files with 897 additions and 190 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,4 @@ AppPackages/
/Registration/src/Application/Registration.API/appsettings.uat.json
/Registration/src/Application/Registration.API/Migrations/20240319015849_InitialCreate.cs
/Registration/src/Application/Registration.API/Migrations/DataContextModelSnapshot.cs
/Registration/docker-compose.uat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="MySql.Data" Version="8.0.33" />
<PackageReference Include="RabbitMQ.Client" Version="6.5.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
Expand All @@ -32,4 +33,8 @@
</None>
</ItemGroup>

<ItemGroup>
<Folder Include="Models\Entities\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace ConsumerChurchMonthWork.MessageBrocker.Config;
public class RabbitMQConfiguration
{
public const string ConfigurationSection = "RabbitMQ";
public string? Host { get; set; }
public string? VirtualHost { get; set; }
public int Port { get; set; }
public string? Username { get; set; }
public string? Password { get; set; }
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using ConsumerChurchMonthWork.Models;
using Microsoft.Extensions.Hosting;
using Serilog;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
using RabbitMQ.Client.Exceptions;
using System.Security.Cryptography;
using ConsumerChurchMonthWork.Services;

namespace ConsumerChurchMonthWork.MessageBrocker.Consumer;
public class NewUserCreatedListerner : BackgroundService
{
private readonly IModel _channel;
private readonly ILogger _logger;
private readonly string _queueName = "user_created";
public NewUserCreatedListerner(IModel channel, ILogger logger)
{
_channel = channel;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await ExecuteConsume(stoppingToken);
}
catch(Exception ex) when (ex is BrokerUnreachableException || ex is OperationInterruptedException)
{
_logger.Error("An error with rabbitMq configs occurred before the connection: {0}", ex.Message);
}
catch (Exception ex)
{
_logger.Error("An error occurred before the connection: {0}", ex.Message);
}
}

private async Task ExecuteConsume(CancellationToken stoppingToken)
{
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += OnMessageReceived;
_channel.BasicConsume(_queueName, false, consumer);

while (!stoppingToken.IsCancellationRequested)
await Task.Delay(1000, stoppingToken);

_logger.Warning("Dispose connection");
_channel.Dispose();
}

private async void OnMessageReceived(object? sender, BasicDeliverEventArgs eventsArgs)
{
try
{
byte[] rawMessage = eventsArgs.Body.ToArray();
string message = Encoding.UTF8.GetString(rawMessage);
UserCreatedMessageDto? objMessage = JsonSerializer.Deserialize<UserCreatedMessageDto>(message);

if(objMessage is null || objMessage.EmailAddress is null)
throw new ArgumentNullException();

//await new SendEmailNewUser().SendEmailAsync(objMessage);

_channel.BasicAck(eventsArgs.DeliveryTag, false);
_logger.Information($"Message newUserCreated processed successful - {objMessage.EmailAddress}");
}
catch(Exception ex) when (ex is JsonException || ex is ArgumentNullException)
{
_logger.Error("There was an error deserializing the message: {0}", ex.Message);
_channel.BasicNack(eventsArgs.DeliveryTag, false, false);
}
catch (Exception ex)
{
_logger.Error("There was an error processing the message: {0}", ex.Message);
_channel.BasicNack(eventsArgs.DeliveryTag, false, false);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
using ConsumerChurchMonthWork.Entitie;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Serilog;
using System.ComponentModel;
using System.Text;
using System.Text.Json;
using System.Threading.Channels;

namespace ConsumerChurchMonthWork.MessageBrocker;
namespace ConsumerChurchMonthWork.MessageBrocker.Consumer;

internal class RabbitMq : IMessageBrocker
internal class RabbitMq : BackgroundService
{
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
private ConnectionFactory _connectionFactory;
private ConnectionFactory _connectionFactory = null!;

public RabbitMq(IConfiguration configuration, ILogger logger)
{
Expand All @@ -22,14 +23,14 @@ public RabbitMq(IConfiguration configuration, ILogger logger)

LoadConfig();
}
public string Exchange { get; private set; }
public string Host { get; private set; }
public string VirtualHost { get; private set; }
public string Port { get; private set; }
public string UserName { get; private set; }
public string Password { get; private set; }
public string RoutingKey { get; private set; }
public string Queue { get; private set; }
public string Exchange { get; private set; } = null!;
public string Host { get; private set; } = null!;
public string VirtualHost { get; private set; } = null!;
public string Port { get; private set; } = null!;
public string UserName { get; private set; } = null!;
public string Password { get; private set; } = null!;
public string RoutingKey { get; private set; } = null!;
public string Queue { get; private set; } = null!;


private void LoadConfig()
Expand All @@ -46,7 +47,7 @@ private void LoadConfig()

private ConnectionFactory CreateConnectionFromParameters()
{
if (someValueIsEmptyOrNull())
if (SomeValueIsEmptyOrNull())
throw new ArgumentNullException("Check the messageBroker properties");

_connectionFactory = new ConnectionFactory()
Expand All @@ -60,10 +61,10 @@ private ConnectionFactory CreateConnectionFromParameters()
return _connectionFactory;
}

private bool someValueIsEmptyOrNull() => (string.IsNullOrEmpty(Host) |
private bool SomeValueIsEmptyOrNull() => string.IsNullOrEmpty(Host) |
string.IsNullOrEmpty(UserName) |
string.IsNullOrEmpty(Password) |
string.IsNullOrEmpty(Port));
string.IsNullOrEmpty(Port);



Expand All @@ -74,8 +75,8 @@ public void StartConsumer()

_logger.Information("Consumindo monthly closing");

using var connection = _connectionFactory.CreateConnection();
using var channel = connection.CreateModel();
using IConnection connection = _connectionFactory.CreateConnection();
using IModel channel = connection.CreateModel();

channel.ExchangeDeclare(exchange: Exchange, type: ExchangeType.Topic);
channel.QueueDeclare(queue: Queue,
Expand Down Expand Up @@ -115,6 +116,11 @@ private static void ReadMessage(BasicDeliverEventArgs ea)

var objBody = JsonSerializer.Deserialize<ObjMessage>(message);

Console.WriteLine($"Received message: {objBody.ChurcId}, {objBody.YearMonth}");
Console.WriteLine($"Received message: {objBody!.ChurcId}, {objBody.YearMonth}");
}

protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
throw new NotImplementedException();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
public class ObjMessage
{
public int ChurcId { get; set; }
public string YearMonth { get; set; }
public string YearMonth { get; set; } = null!;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
namespace ConsumerChurchMonthWork.Models;
public record UserCreatedMessageDto(short Id, string EmailAddress, DateTime OcurredOn, string Password);
Original file line number Diff line number Diff line change
@@ -1,41 +1,76 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using ConsumerChurchMonthWork.MessageBrocker;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using ConsumerChurchMonthWork.MessageBrocker.Config;
using ConsumerChurchMonthWork.MessageBrocker.Consumer;

IConfigurationRoot configuration;
Serilog.ILogger logger;

ServiceCollection serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
//ServiceCollection serviceCollection = new ServiceCollection();
//ConfigureServices(serviceCollection);

//var churchId = 1;
//var competence = "05-2023";
//void ConfigureServices(IServiceCollection serviceCollection)
//{
logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();

//IDataBase dataBase = new MysqlDataBase(configuration);
configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.Build();

//var report = new Report(dataBase, churchId, competence);
//var listMonthleClosing = report.Generate();
// serviceCollection.AddSingleton<IConfigurationRoot>(configuration);
// serviceCollection.AddSingleton<ILogger>(logger);
// serviceCollection.AddHostedService<NewUserCreatedListerner>();
//}

//var jsonObj = JsonSerializer.Serialize(listMonthleClosing.Result);
//var returnList = JsonSerializer.Deserialize<List<Entitie.MonthlyClosing>>(jsonObj);
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddSingleton<IConfigurationRoot>(configuration);
services.AddSingleton<ILogger>(logger);

services.Configure<RabbitMQConfiguration>(configuration.GetSection("MessageBroker"));

void ConfigureServices(IServiceCollection serviceCollection)
{
logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
services.AddSingleton(serviceProvider =>
{
RabbitMQConfiguration rabbitMQConfiguration =
serviceProvider.GetRequiredService<IOptions<RabbitMQConfiguration>>().Value;

configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.Build();
var factory = new ConnectionFactory
{
HostName = rabbitMQConfiguration.Host,
UserName = rabbitMQConfiguration.Username,
Password = rabbitMQConfiguration.Password,
Port = rabbitMQConfiguration.Port
};

serviceCollection.AddSingleton<IConfigurationRoot>(configuration);
serviceCollection.AddSingleton<ILogger>(logger);
}
IConnection connection = factory.CreateConnection();
return connection;
});

services.AddHostedService(serviceProvider =>
{
var config = serviceProvider.GetRequiredService<IOptions<RabbitMQConfiguration>>();
IConnection connection = serviceProvider.GetRequiredService<IConnection>();

RabbitMq rabbit = new RabbitMq(configuration, logger);
rabbit.StartConsumer();
return new NewUserCreatedListerner(
connection.CreateModel(),
logger
);
});



})
.Build();

await host.RunAsync();

//RabbitMq rabbit = new RabbitMq(configuration, logger);
//rabbit.StartConsumer();
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"profiles": {
"ConsumerChurchMonthWork": {
"commandName": "Project",
"environmentVariables": {
"PASSEMAIL": "#Sojesussalva",
"KEYUSERCREATED": "AAECAwQFBgcICQoLDA0ODw=="
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using ConsumerChurchMonthWork.Repository;
using ConsumerChurchMonthWork.Repository.Connections;

namespace ConsumerChurchMonthWork;
public class Report
Expand All @@ -15,7 +15,7 @@ public Report(IDataBase repository, int churchId, string competence)
public string Competence { get; private set; }


public async Task<List<Entitie.MonthlyClosing>> Generate()
public async Task<List<Entitie.MonthlyClosing>?> Generate()
{
if (ValidateProperties())
return null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using Entitie = ConsumerChurchMonthWork.Entitie;

namespace ConsumerChurchMonthWork.Repository;
namespace ConsumerChurchMonthWork.Repository.Connections;

public interface IDataBase {
public interface IDataBase
{
public Task<List<Entitie.MonthlyClosing>> SelectReport(string churchId, string month, string year);
}
Loading

0 comments on commit a53b470

Please sign in to comment.