From c01cec1e039e69038574f8a7feb4fabc4760db05 Mon Sep 17 00:00:00 2001 From: "roi.ezra" Date: Sun, 19 May 2024 18:35:51 +0300 Subject: [PATCH] added not working function --- .vscode/tasks.json | 78 ++++++- MailSender/.gitignore | 264 ++++++++++++++++++++++ MailSender/Notify.cs | 95 ++++++++ MailSender/Program.cs | 13 ++ MailSender/Properties/launchSettings.json | 9 + MailSender/host.json | 12 + MailSender/readme.md | 11 + Mundialito/appsettings.Development.json | 2 +- MundialitoV2.sln | 6 + local.settings.json | 7 + 10 files changed, 494 insertions(+), 3 deletions(-) create mode 100644 MailSender/.gitignore create mode 100644 MailSender/Notify.cs create mode 100644 MailSender/Program.cs create mode 100644 MailSender/Properties/launchSettings.json create mode 100644 MailSender/host.json create mode 100644 MailSender/readme.md create mode 100644 local.settings.json diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 31c32bd..2bf4e8a 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -9,9 +9,7 @@ "type": "shell", "args": [ "build", - // Ask dotnet build to generate full paths for file names. "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel "/consoleloggerparameters:NoSummary" ], "group": "build", @@ -19,6 +17,82 @@ "reveal": "silent" }, "problemMatcher": "$msCompile" + }, + { + "label": "clean (functions)", + "command": "dotnet", + "args": [ + "clean", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/MailSender" + } + }, + { + "label": "build (functions)", + "command": "dotnet", + "args": [ + "build", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "dependsOn": "clean (functions)", + "group": { + "kind": "build", + "isDefault": true + }, + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/MailSender" + } + }, + { + "label": "clean release (functions)", + "command": "dotnet", + "args": [ + "clean", + "--configuration", + "Release", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/MailSender" + } + }, + { + "label": "publish (functions)", + "command": "dotnet", + "args": [ + "publish", + "--configuration", + "Release", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "dependsOn": "clean release (functions)", + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/MailSender" + } + }, + { + "type": "func", + "dependsOn": "build (functions)", + "options": { + "cwd": "${workspaceFolder}/MailSender/bin/Debug/net8.0" + }, + "command": "host start", + "isBackground": true, + "problemMatcher": "$func-dotnet-watch" } ] } \ No newline at end of file diff --git a/MailSender/.gitignore b/MailSender/.gitignore new file mode 100644 index 0000000..ff5b00c --- /dev/null +++ b/MailSender/.gitignore @@ -0,0 +1,264 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# Azure Functions localsettings file +local.settings.json + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc \ No newline at end of file diff --git a/MailSender/Notify.cs b/MailSender/Notify.cs new file mode 100644 index 0000000..9bdd0c5 --- /dev/null +++ b/MailSender/Notify.cs @@ -0,0 +1,95 @@ +using System; +using System.Net.Mail; +using Microsoft.Azure.Functions.Worker; +using Microsoft.Extensions.Logging; +using Mundialito.DAL.Accounts; +using Mundialito.DAL.Games; + +namespace Mundialito.Function +{ + public class Notify + { + private readonly ILogger _logger; + + public Notify(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } + + [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}"); + } + } + + private static void SendNotifications(Game game, TextWriter 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 usersToNotify = Program.GetUsersToNotify(game); + log.WriteLine(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.WriteLine("***** End of Notification sending *****"); + } + + private static void SendNotification(MundialitoUser user, Game game, TextWriter log) + { + try + { + string sendGridUsername = ConfigurationManager.AppSettings["SendGridUserName"]; + string sendGridPassword = ConfigurationManager.AppSettings["SendGridPassword"]; + string linkAddress = ConfigurationManager.AppSettings["LinkAddress"]; + string fromAddress = ConfigurationManager.AppSettings["fromAddress"]; + MailMessage message = new MailMessage(); + message.To.Add(new MailAddress(user.Email, user.FirstName + " " + user.LastName)); + message.From = new MailAddress(fromAddress, ConfigurationManager.AppSettings["ApplicationName"]); + 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 = "

Please submit your bet as soon as possible. Click here for the Bets Center

"; + 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); + if (ex.InnerException != null) + { + log.WriteLine("Innber excpetion: " + ex.InnerException.Message); + } + + } + } + + private static List GetUsersToNotify(Game game) + { + IEnumerable source = new UsersRepository().AllUsers(); + Dictionary gameBets = Enumerable.ToDictionary(new BetsRepository().GetGameBets(game.GameId), (Func)(bet => bet.UserId), (Func)(bet => bet)); + return Enumerable.ToList(Enumerable.Where(source, (Func)(user => !gameBets.ContainsKey(user.Id)))); + } + + private static List GetOpenGames(TextWriter log) + { + List list1 = Enumerable.ToList(new GamesRepository().Get(null, null, "")); + log.WriteLine(string.Format("Got {0} games from database", list1.Count)); + List list2 = Enumerable.ToList(Enumerable.Where((IEnumerable)Enumerable.OrderBy((IEnumerable)list1, (Func)(game => game.Date)), (Func)(game => game.IsOpen()))); + log.WriteLine(string.Format("{0} games still can be notified", list2.Count)); + return list2; + } + + } +} diff --git a/MailSender/Program.cs b/MailSender/Program.cs new file mode 100644 index 0000000..9389455 --- /dev/null +++ b/MailSender/Program.cs @@ -0,0 +1,13 @@ +using Microsoft.Azure.Functions.Worker; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; + +var host = new HostBuilder() + .ConfigureFunctionsWebApplication() + .ConfigureServices(services => { + services.AddApplicationInsightsTelemetryWorkerService(); + services.ConfigureFunctionsApplicationInsights(); + }) + .Build(); + +host.Run(); diff --git a/MailSender/Properties/launchSettings.json b/MailSender/Properties/launchSettings.json new file mode 100644 index 0000000..293a702 --- /dev/null +++ b/MailSender/Properties/launchSettings.json @@ -0,0 +1,9 @@ +{ + "profiles": { + "MailSender": { + "commandName": "Project", + "commandLineArgs": "--port 7182", + "launchBrowser": false + } + } +} \ No newline at end of file diff --git a/MailSender/host.json b/MailSender/host.json new file mode 100644 index 0000000..ee5cf5f --- /dev/null +++ b/MailSender/host.json @@ -0,0 +1,12 @@ +{ + "version": "2.0", + "logging": { + "applicationInsights": { + "samplingSettings": { + "isEnabled": true, + "excludedTypes": "Request" + }, + "enableLiveMetricsFilters": true + } + } +} \ No newline at end of file diff --git a/MailSender/readme.md b/MailSender/readme.md new file mode 100644 index 0000000..0b247b5 --- /dev/null +++ b/MailSender/readme.md @@ -0,0 +1,11 @@ +# TimerTrigger - C# + +The `TimerTrigger` makes it incredibly easy to have your functions executed on a schedule. This sample demonstrates a simple use case of calling your function every 5 minutes. + +## How it works + +For a `TimerTrigger` to work, you provide a schedule in the form of a [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression)(See the link for full details). A cron expression is a string with 6 separate expressions which represent a given schedule via patterns. The pattern we use to represent every 5 minutes is `0 */5 * * * *`. This, in plain text, means: "When seconds is equal to 0, minutes is divisible by 5, for any hour, day of the month, month, day of the week, or year". + +## Learn more + + Documentation \ No newline at end of file diff --git a/Mundialito/appsettings.Development.json b/Mundialito/appsettings.Development.json index 5f313fd..9996556 100644 --- a/Mundialito/appsettings.Development.json +++ b/Mundialito/appsettings.Development.json @@ -6,7 +6,7 @@ } }, "App": { - "UseSqlLite": false, + "UseSqlLite": true, "AdminEmail": "ezraroi@gmail.com", "PrivateKeyProtection": true, "TournamentStartDate": "18/04/2024", diff --git a/MundialitoV2.sln b/MundialitoV2.sln index b45e521..e105c2b 100644 --- a/MundialitoV2.sln +++ b/MundialitoV2.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mundialito", "Mundialito\Mundialito.csproj", "{1EAC3FB4-59B6-4D84-A3C0-1CF78D68F6BA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MailSender", "MailSender\MailSender.csproj", "{0861B3F2-C55A-445D-AD70-45F031494F2A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -18,5 +20,9 @@ Global {1EAC3FB4-59B6-4D84-A3C0-1CF78D68F6BA}.Debug|Any CPU.Build.0 = Debug|Any CPU {1EAC3FB4-59B6-4D84-A3C0-1CF78D68F6BA}.Release|Any CPU.ActiveCfg = Release|Any CPU {1EAC3FB4-59B6-4D84-A3C0-1CF78D68F6BA}.Release|Any CPU.Build.0 = Release|Any CPU + {0861B3F2-C55A-445D-AD70-45F031494F2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0861B3F2-C55A-445D-AD70-45F031494F2A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0861B3F2-C55A-445D-AD70-45F031494F2A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0861B3F2-C55A-445D-AD70-45F031494F2A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/local.settings.json b/local.settings.json new file mode 100644 index 0000000..223451c --- /dev/null +++ b/local.settings.json @@ -0,0 +1,7 @@ +{ + "IsEncrypted": false, + "Values": { + "AzureWebJobsStorage": "", + "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated" + } +} \ No newline at end of file