From c550a3387eee49f161f5811e9b94a57911f4a8d2 Mon Sep 17 00:00:00 2001 From: mtokarev Date: Thu, 16 May 2024 09:45:34 +0400 Subject: [PATCH] Fix minor bugs --- mailSender/Ex3.cs | 19 ++++++++++--- mailSender/MailService.cs | 52 +++++++++++++++++++++++++++--------- mailSender/Program.cs | 5 ++-- mailSender/UserService.cs | 5 ++++ mailSender/appsettings.json | 10 +++---- mailSender/mailSender.csproj | 3 +-- 6 files changed, 68 insertions(+), 26 deletions(-) diff --git a/mailSender/Ex3.cs b/mailSender/Ex3.cs index b0b53dc..cf64537 100644 --- a/mailSender/Ex3.cs +++ b/mailSender/Ex3.cs @@ -8,23 +8,34 @@ class Ex3 { [JsonPropertyName("DOB")] public string DobStr { get; set; } + + private DateTime _dob; + private bool _isDobFormatted = false; [JsonIgnore] public DateTime Dob { get { - // We expect to have string in the specific format 'dd/MM/yyyy' + // If we already tried to parse the date, then return cached result + if (_isDobFormatted) + { + return _dob; + } + + // We expect to have string in the specific format 'M/d/yyyy' + // e.g. '2/3/1990', '11/12/1985' if (DateTime.TryParseExact(DobStr, - "dd/MM/yyyy", + "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var value)) { - return value; + _dob = value; } - return DateTime.MinValue; + _isDobFormatted = true; + return _dob; } set { diff --git a/mailSender/MailService.cs b/mailSender/MailService.cs index d2a04f4..929da48 100644 --- a/mailSender/MailService.cs +++ b/mailSender/MailService.cs @@ -18,14 +18,15 @@ public class MailService private readonly EmailAddress _mailFrom; private readonly bool _isSimulationModeEnabled; private readonly string _mailSubject, + _mailTemplateFile, _ccRecipient; public MailService(IConfiguration config, Logger logger) { + _logger = logger; + ValidateAndAssignConfig(config); - _config = config; - _logger = logger; _mailFrom = new EmailAddress(_config.GetSection("SendGrid:SenderEmail").Value, _config.GetSection("SendGrid:SenderName").Value); @@ -33,17 +34,17 @@ public MailService(IConfiguration config, Logger logger) _config.GetSection("SendGrid:SimulationModeEnabled").Value); _mailSubject = _config.GetSection("SendGrid:MailSubject").Value; _ccRecipient = _config.GetSection("SendGrid:CcRecipient").Value; + _mailTemplateFile = _config.GetSection("SendGrid:MailTemplateHtml").Value; } public async Task SendBrthEmailsAsync(List sendTos) { string mailTemplate; - try { // Read file from mail template. - mailTemplate = File.ReadAllText(_config.GetSection("SendGrid:MailTemplateHtml").Value); + mailTemplate = File.ReadAllText(_mailTemplateFile); } catch (Exception e) { @@ -80,7 +81,7 @@ public async Task SendBrthEmailsAsync(List sendTos) // If simulation mode is enabled just log message and continue. if (_isSimulationModeEnabled) { - _logger.Information($"E-mail won't sent to '{user.EmailAddress}'."); + _logger.Information($"E-mail won't be sent to '{user.EmailAddress}'."); continue; } @@ -120,34 +121,59 @@ private static SendGridMessage CreateMail(EmailAddress mailFrom, private void ValidateAndAssignConfig(IConfiguration config) { - string sender = _config.GetSection("SendGrid:SenderEmail").Value; - if (string.IsNullOrEmpty(_config.GetSection("SendGrid:SenderName").Value) + if (config is null) + { + throw new ArgumentNullException($"'{nameof(config)}' is null. Please provide a valid configuration."); + } + + bool isValid = true; + string sender = config.GetSection("SendGrid:SenderEmail").Value; + if (string.IsNullOrEmpty(config.GetSection("SendGrid:SenderName").Value) && string.IsNullOrEmpty(sender)) { _logger.Fatal("Please provide 'SenderEmail' and 'SenderName' in appSettings.json"); + isValid = false; } if (!string.IsNullOrEmpty(sender) && !MailAddress.TryCreate(sender, out var _)) { _logger.Fatal("'SenderEmail' must be a valid email address. Value provided: '{Sender}'.", sender); + isValid = false; } - if (bool.TryParse(_config.GetSection("SendGrid:SimulationModeEnabled").Value, out bool _)) + if (!bool.TryParse(config.GetSection("SendGrid:SimulationModeEnabled").Value, out bool _)) { _logger.Fatal("'SimulationModeEnabled' must to be set in appsetting.json as 'true' or 'false'."); + isValid = false; } - string ccRecipient = _config.GetSection("SendGrid:CcRecipient").Value; - if (!MailAddress.TryCreate(sender, out var _) - && !string.IsNullOrEmpty(ccRecipient)) + string ccRecipient = config.GetSection("SendGrid:CcRecipient").Value; + if (!string.IsNullOrEmpty(ccRecipient) + && !MailAddress.TryCreate(ccRecipient, out var _)) { _logger.Fatal("'CcResipient' must be empty or have a valid email address. Value provided: '{CcRecipient}'.", ccRecipient); + isValid = false; } - throw new ArgumentException($"One or more parameter provided for '{nameof(MailService)}' are incorrect. " + - "Please check the log for more information"); + string templateFileName = config.GetSection("SendGrid:MailTemplateHtml").Value; + if (string.IsNullOrEmpty(templateFileName)) + { + _logger.Fatal("Please provide a 'MailTemplateHtml' parameter in appsetting.json"); + isValid = false; + } + else if (!File.Exists(templateFileName)) + { + _logger.Fatal("Template file {FileName} does not exist.", templateFileName); + isValid = false; + } + + if (!isValid) + { + throw new ArgumentException($"One or more parameter provided for '{nameof(MailService)}' are incorrect. " + + "Please check the log for more details."); + } } } } diff --git a/mailSender/Program.cs b/mailSender/Program.cs index 63e45b7..be49b06 100644 --- a/mailSender/Program.cs +++ b/mailSender/Program.cs @@ -24,13 +24,14 @@ static async Task Main(string[] args) _logger = InitLogger(_config); _logger.Information($"Starting '{nameof(mailSender)}'."); - // Find all active users who celebrate birthday today + var mailService = new MailService(_config, _logger); var userService = new UserService(_logger); + + // Find all active users who celebrate birthday today var enabledUsers = userService.GetEnabledDomainUsers(domainName: Environment.UserDomainName); var celebratingUser = userService.GetCelebratingUsers(enabledUsers); // Send celebration message and waiting when task is done. - var mailService = new MailService(_config, _logger); await mailService.SendBrthEmailsAsync(celebratingUser); // Stop timer and log time diff --git a/mailSender/UserService.cs b/mailSender/UserService.cs index e5c1881..bca7334 100644 --- a/mailSender/UserService.cs +++ b/mailSender/UserService.cs @@ -23,6 +23,11 @@ public List GetEnabledDomainUsers(string domainName, boo using (var ctx = new PrincipalContext(ContextType.Domain, domainName)) { var userPrinciple = new UserPrincipalExtension(ctx); + if (hasEmail) + { + userPrinciple.EmailAddress = "*"; + } + using var search = new PrincipalSearcher(userPrinciple); // Filter only active users diff --git a/mailSender/appsettings.json b/mailSender/appsettings.json index b3da2fa..e8a1eea 100644 --- a/mailSender/appsettings.json +++ b/mailSender/appsettings.json @@ -1,17 +1,17 @@ { "Logger": { - //Optional (can be removed). + // Optional (can be removed). "LogPath": "logs/log.log" }, "SendGrid": { "ApiKey": "Do not store your keys into git repos", - "SenderEmail": "no-reply@domain", + "SenderEmail": "no-reply@domain.com", "SenderName": "NoReply", "MailSubject": "Happy Birthday {{name}}!", "MailTemplateHtml": "mailTempl.html", + "SimulationModeEnabled": true, - //Optional (can be removed). - "CcRecipient": "addToCc@domain", - "SimulationModeEnabled": true + // Optional (can be removed). + "CcRecipient": "addToCc@domain.com" } } \ No newline at end of file diff --git a/mailSender/mailSender.csproj b/mailSender/mailSender.csproj index 71156da..564697d 100644 --- a/mailSender/mailSender.csproj +++ b/mailSender/mailSender.csproj @@ -8,8 +8,7 @@ true win-x64 f8fad4a5-3942-435f-bec7-b234a053a912 - None - false + true mail.ico