Merge pull request #1061 from sbwalker/dev

set SiteState in HostedServiceBase for scheduled jobs
This commit is contained in:
Shaun Walker 2021-01-18 10:18:47 -05:00 committed by GitHub
commit 350d2cec96
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 85 additions and 233 deletions

View File

@ -1,141 +0,0 @@
@namespace Oqtane.Modules.Admin.Jobs
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IJobService JobService
@inject IStringLocalizer<Add> Localizer
<table class="table table-borderless">
<tr>
<td>
<Label For="name" HelpText="Enter the job name" ResourceKey="Name">Name: </Label>
</td>
<td>
<input id="name" class="form-control" @bind="@_name" />
</td>
</tr>
<tr>
<td>
<Label For="type" HelpText="Enter the job type" ResourceKey="Type">Type: </Label>
</td>
<td>
<input id="type" class="form-control" @bind="@_jobType" />
</td>
</tr>
<tr>
<td>
<Label For="enabled" HelpText="Select whether you want the job enabled or not" ResourceKey="Enabled">Enabled? </Label>
</td>
<td>
<select id="enabled" class="form-control" @bind="@_isEnabled">
<option value="True">@Localizer["Yes"]</option>
<option value="False">@Localizer["No"]</option>
</select>
</td>
</tr>
<tr>
<td>
<Label For="runs-every" HelpText="Select how often you want the job to run" ResourceKey="RunsEvery">Runs Every: </Label>
</td>
<td>
<input id="runs-every" class="form-control" @bind="@_interval" />
<select id="runs-every" class="form-control" @bind="@_frequency">
<option value="m">@Localizer["Minute(s)"]</option>
<option value="H">@Localizer["Hour(s)"]</option>
<option value="d">@Localizer["Day(s)"]</option>
<option value="M">@Localizer["Month(s)"]</option>
</select>
</td>
</tr>
<tr>
<td>
<Label For="starting" HelpText="What time do you want the job to start" ResourceKey="Starting">Starting: </Label>
</td>
<td>
<input id="starting" class="form-control" @bind="@_startDate" />
</td>
</tr>
<tr>
<td>
<Label For="ending" HelpText="When do you want the job to end" ResourceKey="Ending">Ending: </Label>
</td>
<td>
<input id="ending" class="form-control" @bind="@_endDate" />
</td>
</tr>
<tr>
<td>
<Label For="retention-log" HelpText="What items do you want in the retention log" ResourceKey="RetentionLog">Retention Log (Items): </Label>
</td>
<td>
<input id="retention-log" class="form-control" @bind="@_retentionHistory" />
</td>
</tr>
</table>
<button type="button" class="btn btn-success" @onclick="SaveJob">@Localizer["Save"]</button>
<NavLink class="btn btn-secondary" href="@NavigateUrl()">@Localizer["Cancel"]</NavLink>
@code {
private string _name = string.Empty;
private string _jobType = string.Empty;
private string _isEnabled = "True";
private string _interval = string.Empty;
private string _frequency = string.Empty;
private string _startDate = string.Empty;
private string _endDate = string.Empty;
private string _retentionHistory = "10";
public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;
private async Task SaveJob()
{
if (_name != string.Empty && !string.IsNullOrEmpty(_jobType) && _frequency != string.Empty && _interval != string.Empty && _retentionHistory != string.Empty)
{
var job = new Job();
job.Name = _name;
job.JobType = _jobType;
job.IsEnabled = Boolean.Parse(_isEnabled);
job.Frequency = _frequency;
job.Interval = int.Parse(_interval);
if (_startDate == string.Empty)
{
job.StartDate = null;
}
else
{
job.StartDate = DateTime.Parse(_startDate);
}
if (_endDate == string.Empty)
{
job.EndDate = null;
}
else
{
job.EndDate = DateTime.Parse(_endDate);
}
job.RetentionHistory = int.Parse(_retentionHistory);
job.IsStarted = false;
job.IsExecuting = false;
job.NextExecution = null;
try
{
job = await JobService.AddJobAsync(job);
await logger.LogInformation("Job Added {Job}", job);
NavigationManager.NavigateTo(NavigateUrl());
}
catch (Exception ex)
{
await logger.LogError(ex, "Error Adding Job {Job} {Error}", job, ex.Message);
AddModuleMessage(Localizer["Error Adding Job"], MessageType.Error);
}
}
else
{
AddModuleMessage(Localizer["You Must Provide The Job Name, Type, Frequency, and Retention"], MessageType.Warning);
}
}
}

View File

@ -15,10 +15,10 @@
</tr>
<tr>
<td>
<Label For="type" HelpText="Enter the job type" ResourceKey="Type">Type: </Label>
<Label For="type" HelpText="The fully qualified job type name" ResourceKey="Type">Type: </Label>
</td>
<td>
<input id="type" class="form-control" @bind="@_jobType" />
<input id="type" class="form-control" @bind="@_jobType" readonly />
</td>
</tr>
<tr>

View File

@ -9,7 +9,6 @@
}
else
{
<ActionLink Action="Add" Text="Add Job" ResourceKey="AddJob" />
<ActionLink Action="Log" Class="btn btn-secondary" Text="View Logs" ResourceKey="ViewJobs" />
<button type="button" class="btn btn-secondary" @onclick="(async () => await Refresh())">Refresh</button>
<br />

View File

@ -91,7 +91,15 @@ namespace Oqtane.Infrastructure
// execute the job
try
{
log.Notes = ExecuteJob(scope.ServiceProvider);
var notes = "";
var tenants = scope.ServiceProvider.GetRequiredService<ITenantRepository>();
var siteState = scope.ServiceProvider.GetRequiredService<SiteState>();
foreach (var tenant in tenants.GetTenants())
{
siteState.Alias = new Alias { TenantId = tenant.TenantId };
notes += ExecuteJob(scope.ServiceProvider);
}
log.Notes = notes;
log.Succeeded = true;
}
catch (Exception ex)

View File

@ -26,103 +26,89 @@ namespace Oqtane.Infrastructure
{
string log = "";
// iterate through tenants in this installation
List<int> tenants = new List<int>();
var aliasRepository = provider.GetRequiredService<IAliasRepository>();
List<Alias> aliases = aliasRepository.GetAliases().ToList();
foreach (Alias alias in aliases)
// get services
var siteRepository = provider.GetRequiredService<ISiteRepository>();
var settingRepository = provider.GetRequiredService<ISettingRepository>();
var notificationRepository = provider.GetRequiredService<INotificationRepository>();
// iterate through sites for this tenant
List<Site> sites = siteRepository.GetSites().ToList();
foreach (Site site in sites)
{
if (tenants.Contains(alias.TenantId)) continue;
tenants.Add(alias.TenantId);
log += "Processing Notifications For Site: " + site.Name + "<br />";
// use the SiteState to set the Alias explicitly so the tenant can be resolved
var siteState = provider.GetRequiredService<SiteState>();
siteState.Alias = alias;
// get services which require tenant resolution
var siteRepository = provider.GetRequiredService<ISiteRepository>();
var settingRepository = provider.GetRequiredService<ISettingRepository>();
var notificationRepository = provider.GetRequiredService<INotificationRepository>();
// iterate through sites for this tenant
List<Site> sites = siteRepository.GetSites().ToList();
foreach (Site site in sites)
// get site settings
List<Setting> sitesettings = settingRepository.GetSettings(EntityNames.Site, site.SiteId).ToList();
Dictionary<string, string> settings = GetSettings(sitesettings);
if (settings.ContainsKey("SMTPHost") && settings["SMTPHost"] != "" &&
settings.ContainsKey("SMTPPort") && settings["SMTPPort"] != "" &&
settings.ContainsKey("SMTPSSL") && settings["SMTPSSL"] != "" &&
settings.ContainsKey("SMTPSender") && settings["SMTPSender"] != "")
{
log += "Processing Notifications For Site: " + site.Name + "<br />";
// get site settings
List<Setting> sitesettings = settingRepository.GetSettings(EntityNames.Site, site.SiteId).ToList();
Dictionary<string, string> settings = GetSettings(sitesettings);
if (settings.ContainsKey("SMTPHost") && settings["SMTPHost"] != "" &&
settings.ContainsKey("SMTPPort") && settings["SMTPPort"] != "" &&
settings.ContainsKey("SMTPSSL") && settings["SMTPSSL"] != "" &&
settings.ContainsKey("SMTPSender") && settings["SMTPSender"] != "")
// construct SMTP Client
var client = new SmtpClient()
{
// construct SMTP Client
var client = new SmtpClient()
{
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = settings["SMTPHost"],
Port = int.Parse(settings["SMTPPort"]),
EnableSsl = bool.Parse(settings["SMTPSSL"])
};
if (settings["SMTPUsername"] != "" && settings["SMTPPassword"] != "")
{
client.Credentials = new NetworkCredential(settings["SMTPUsername"], settings["SMTPPassword"]);
}
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = settings["SMTPHost"],
Port = int.Parse(settings["SMTPPort"]),
EnableSsl = bool.Parse(settings["SMTPSSL"])
};
if (settings["SMTPUsername"] != "" && settings["SMTPPassword"] != "")
{
client.Credentials = new NetworkCredential(settings["SMTPUsername"], settings["SMTPPassword"]);
}
// iterate through notifications
int sent = 0;
List<Notification> notifications = notificationRepository.GetNotifications(site.SiteId, -1, -1).ToList();
foreach (Notification notification in notifications)
// iterate through notifications
int sent = 0;
List<Notification> notifications = notificationRepository.GetNotifications(site.SiteId, -1, -1).ToList();
foreach (Notification notification in notifications)
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(settings["SMTPSender"], site.Name);
mailMessage.Subject = notification.Subject;
if (notification.FromUserId != null)
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(settings["SMTPSender"], site.Name);
mailMessage.Subject = notification.Subject;
if (notification.FromUserId != null)
{
mailMessage.Body = "From: " + notification.FromDisplayName + "<" + notification.FromEmail + ">" + "\n";
}
else
{
mailMessage.Body = "From: " + site.Name + "\n";
}
mailMessage.Body += "Sent: " + notification.CreatedOn + "\n";
if (notification.ToUserId != null)
{
mailMessage.To.Add(new MailAddress(notification.ToEmail, notification.ToDisplayName));
mailMessage.Body += "To: " + notification.ToDisplayName + "<" + notification.ToEmail + ">" + "\n";
}
else
{
mailMessage.To.Add(new MailAddress(notification.ToEmail));
mailMessage.Body += "To: " + notification.ToEmail + "\n";
}
mailMessage.Body += "Subject: " + notification.Subject + "\n\n";
mailMessage.Body += notification.Body;
mailMessage.Body = "From: " + notification.FromDisplayName + "<" + notification.FromEmail + ">" + "\n";
}
else
{
mailMessage.Body = "From: " + site.Name + "\n";
}
mailMessage.Body += "Sent: " + notification.CreatedOn + "\n";
if (notification.ToUserId != null)
{
mailMessage.To.Add(new MailAddress(notification.ToEmail, notification.ToDisplayName));
mailMessage.Body += "To: " + notification.ToDisplayName + "<" + notification.ToEmail + ">" + "\n";
}
else
{
mailMessage.To.Add(new MailAddress(notification.ToEmail));
mailMessage.Body += "To: " + notification.ToEmail + "\n";
}
mailMessage.Body += "Subject: " + notification.Subject + "\n\n";
mailMessage.Body += notification.Body;
// send mail
try
{
client.Send(mailMessage);
sent = sent++;
notification.IsDelivered = true;
notification.DeliveredOn = DateTime.UtcNow;
notificationRepository.UpdateNotification(notification);
}
catch (Exception ex)
{
// error
log += ex.Message + "<br />";
}
// send mail
try
{
client.Send(mailMessage);
sent = sent++;
notification.IsDelivered = true;
notification.DeliveredOn = DateTime.UtcNow;
notificationRepository.UpdateNotification(notification);
}
catch (Exception ex)
{
// error
log += ex.Message + "<br />";
}
log += "Notifications Delivered: " + sent + "<br />";
}
else
{
log += "SMTP Not Configured Properly In Site Settings - Host, Port, SSL, And Sender Are All Required" + "<br />";
}
log += "Notifications Delivered: " + sent + "<br />";
}
else
{
log += "SMTP Not Configured Properly In Site Settings - Host, Port, SSL, And Sender Are All Required" + "<br />";
}
}