Skip to content

Commit

Permalink
fixing build
Browse files Browse the repository at this point in the history
  • Loading branch information
ezraroi committed May 19, 2024
1 parent 977f47b commit e395e9e
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 35 deletions.
81 changes: 47 additions & 34 deletions MailSender/Notify.cs
Original file line number Diff line number Diff line change
@@ -1,93 +1,106 @@
using System;
using System.Data.Common;
using System.Net.Mail;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Mundialito.Configuration;
using Mundialito.DAL;
using Mundialito.DAL.Accounts;
using Mundialito.DAL.Bets;
using Mundialito.DAL.Games;

namespace Mundialito.Function
{
public class Notify
{
private readonly ILogger _logger;
private List<Game> openGames;
private readonly IConfigurationRoot configuration;

public Notify(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<Notify>();
configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
}

[Function("Notify")]
public void Run([TimerTrigger("0 */30 * * * *")] TimerInfo myTimer)
{
_logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

if (myTimer.ScheduleStatus is not null)
{
_logger.LogInformation($"Next timer schedule at: {myTimer.ScheduleStatus.Next}");
}
openGames = GetOpenGames(_logger);
for (int i = 0; i < openGames.Count; i++)
{
var minutes = openGames[i].Date.ToLocalTime().Subtract(DateTime.Now.ToLocalTime()).TotalMinutes;
_logger.LogInformation("Game " + openGames[i].GameId + " Minutes is " + minutes);
if (minutes < 120 && minutes > 35)
{
_logger.LogInformation("Found game that will start @ " + openGames[i].Date.ToLocalTime());
_logger.LogInformation(minutes + " Minutes until start time");
SendNotifications(openGames[i], _logger);
}
}
_logger.LogInformation("Bye Bye");
}

private static void SendNotifications(Game game, TextWriter log)
private void SendNotifications(Game game, ILogger log)
{
log.WriteLine("***** Sending notifications started *****");
log.WriteLine("Current Time: " + DateTime.Now.ToLocalTime());
log.WriteLine(string.Format("Sending notifications on game {0} ", game.GameId));
List<MundialitoUser> usersToNotify = Program.GetUsersToNotify(game);
log.WriteLine(string.Format("Sending notifications to {0} users on game {1}", usersToNotify.Count, game.GameId));
log.LogInformation("***** Sending notifications started *****");
log.LogInformation("Current Time: " + DateTime.Now.ToLocalTime());
log.LogInformation(string.Format("Sending notifications on game {0} ", game.GameId));
List<MundialitoUser> usersToNotify = GetUsersToNotify(game);
log.LogInformation(string.Format("Sending notifications to {0} users on game {1}", usersToNotify.Count, game.GameId));
foreach (MundialitoUser user in usersToNotify)
{
log.WriteLine(string.Format("Will send notification to {0}", user.Email));
Program.SendNotification(user, game, log);
log.LogInformation(string.Format("Will send notification to {0}", user.Email));
SendNotification(user, game, log);
}
log.WriteLine("***** End of Notification sending *****");
log.LogInformation("***** End of Notification sending *****");
}

private static void SendNotification(MundialitoUser user, Game game, TextWriter log)
private static void SendNotification(MundialitoUser user, Game game, ILogger log)
{
try
{
string sendGridUsername = ConfigurationManager.AppSettings["SendGridUserName"];
string sendGridPassword = ConfigurationManager.AppSettings["SendGridPassword"];
string linkAddress = ConfigurationManager.AppSettings["LinkAddress"];
string fromAddress = ConfigurationManager.AppSettings["fromAddress"];
string linkAddress = System.Environment.GetEnvironmentVariable("LinkAddress", EnvironmentVariableTarget.Process);
string fromAddress = System.Environment.GetEnvironmentVariable("FromAddress", EnvironmentVariableTarget.Process);
MailMessage message = new MailMessage();
message.To.Add(new MailAddress(user.Email, user.FirstName + " " + user.LastName));
message.From = new MailAddress(fromAddress, ConfigurationManager.AppSettings["ApplicationName"]);
message.From = new MailAddress(fromAddress, System.Environment.GetEnvironmentVariable("ApplicationName", EnvironmentVariableTarget.Process));
TimeSpan timeSpan = game.CloseTime - DateTime.UtcNow;
message.Subject = string.Format("WARNING: The game between {0} and {1}, will be closed in {2} minutes and you havn't placed a bet yet", (object)game.HomeTeam.Name, (object)game.AwayTeam.Name, (object)(int)timeSpan.TotalMinutes);
string content1 = string.Format("Please submit your bet as soon as possible");
string content2 = "<p>Please submit your bet as soon as possible. <a href='" + linkAddress + "'>Click here for the Bets Center</a></p>";
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content1, (Encoding)null, "text/plain"));
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content2, (Encoding)null, "text/html"));
SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
NetworkCredential networkCredential = new NetworkCredential(sendGridUsername, sendGridPassword);
smtpClient.Credentials = (ICredentialsByHost)networkCredential;
smtpClient.Send(message);
}
catch (Exception ex)
{
log.WriteLine("Failed to send notification. Exception is " + ex.Message);
log.LogError("Failed to send notification. Exception is " + ex.Message);
if (ex.InnerException != null)
{
log.WriteLine("Innber excpetion: " + ex.InnerException.Message);
log.LogError("Innber excpetion: " + ex.InnerException.Message);
}

}
}

private static List<MundialitoUser> GetUsersToNotify(Game game)
private List<MundialitoUser> GetUsersToNotify(Game game)
{
IEnumerable<MundialitoUser> source = new UsersRepository().AllUsers();
Dictionary<string, Bet> gameBets = Enumerable.ToDictionary<Bet, string, Bet>(new BetsRepository().GetGameBets(game.GameId), (Func<Bet, string>)(bet => bet.UserId), (Func<Bet, Bet>)(bet => bet));
return Enumerable.ToList<MundialitoUser>(Enumerable.Where<MundialitoUser>(source, (Func<MundialitoUser, bool>)(user => !gameBets.ContainsKey(user.Id))));
var db = new MundialitoDbContext(configuration);
IEnumerable<MundialitoUser> source = db.Users.ToList();
Dictionary<string, Bet> gameBets = Enumerable.ToDictionary<Bet, string, Bet>(new BetsRepository(db).GetGameBets(game.GameId), bet => bet.UserId, bet => bet);
return Enumerable.ToList<MundialitoUser>(Enumerable.Where<MundialitoUser>(source, user => !gameBets.ContainsKey(user.Id)));
}

private static List<Game> GetOpenGames(TextWriter log)
private List<Game> GetOpenGames(ILogger log)
{
List<Game> list1 = Enumerable.ToList<Game>(new GamesRepository().Get(null, null, ""));
log.WriteLine(string.Format("Got {0} games from database", list1.Count));
List<Game> list1 = Enumerable.ToList<Game>(new GamesRepository(new MundialitoDbContext(configuration)).Get(null, null, ""));
log.LogInformation(string.Format("Got {0} games from database", list1.Count));
List<Game> list2 = Enumerable.ToList<Game>(Enumerable.Where<Game>((IEnumerable<Game>)Enumerable.OrderBy<Game, DateTime>((IEnumerable<Game>)list1, (Func<Game, DateTime>)(game => game.Date)), (Func<Game, bool>)(game => game.IsOpen())));
log.WriteLine(string.Format("{0} games still can be notified", list2.Count));
log.LogInformation(string.Format("{0} games still can be notified", list2.Count));
return list2;
}

Expand Down
24 changes: 24 additions & 0 deletions MailSender/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"App": {
"ApplicationName": "EuroChamp",
"PrivateKeyProtection": true,
"FromAddress": "[email protected]",
"UseSqlLite": false
},
"JwtTokenSettings": {
"ValidIssuer": "ExampleIssuer",
"ValidAudience": "ValidAudience",
"SymmetricSecurityKey": "fvh8456477hth44j6wfds98bq9hp8bqh9ubq9gjig3qr0[94vj5",
"JwtRegisteredClaimNamesSub": "345h098bb8reberbwr4vvb8945"
},
"ConnectionStrings": {
"App": "DataSource = identityDb.db; Cache=Shared"
}
}
2 changes: 1 addition & 1 deletion Mundialito/DAL/MundialitoDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
protected override void OnConfiguring(DbContextOptionsBuilder options) {
// options.UseSqlite("DataSource = identityDb.db; Cache=Shared");
bool sqlLite = appConfig.GetSection("App").GetValue("UseSqlLite", false);
if (sqlLite){
if (appConfig.GetSection("App").GetValue("UseSqlLite", false)){
options.UseSqlite(appConfig.GetConnectionString("App"));
} else {
options.UseSqlServer(appConfig.GetConnectionString("App"));
Expand Down

0 comments on commit e395e9e

Please sign in to comment.