Skip to content

Commit

Permalink
Fix minor bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
mtokarev committed May 16, 2024
1 parent 8ca0c44 commit c550a33
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 26 deletions.
19 changes: 15 additions & 4 deletions mailSender/Ex3.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
52 changes: 39 additions & 13 deletions mailSender/MailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,32 +18,33 @@ 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);
_isSimulationModeEnabled = bool.Parse(
_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<UserPrincipalExtension> sendTos)
{
string mailTemplate;

try
{
// Read file from mail template.
mailTemplate = File.ReadAllText(_config.GetSection("SendGrid:MailTemplateHtml").Value);
mailTemplate = File.ReadAllText(_mailTemplateFile);
}
catch (Exception e)
{
Expand Down Expand Up @@ -80,7 +81,7 @@ public async Task SendBrthEmailsAsync(List<UserPrincipalExtension> 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;
}

Expand Down Expand Up @@ -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.");
}
}
}
}
5 changes: 3 additions & 2 deletions mailSender/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions mailSender/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ public List<UserPrincipalExtension> 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
Expand Down
10 changes: 5 additions & 5 deletions mailSender/appsettings.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
3 changes: 1 addition & 2 deletions mailSender/mailSender.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<UserSecretsId>f8fad4a5-3942-435f-bec7-b234a053a912</UserSecretsId>
<DebugType>None</DebugType>
<DebugSymbols>false</DebugSymbols>
<DebugSymbols>true</DebugSymbols>
<ApplicationIcon>mail.ico</ApplicationIcon>
</PropertyGroup>

Expand Down

0 comments on commit c550a33

Please sign in to comment.