Switched to standard MonIn library

This commit is contained in:
Chase Tucker
2024-04-09 10:44:57 -07:00
parent 794b616293
commit 156dee0751
22 changed files with 539 additions and 345 deletions

View File

@ -23,21 +23,30 @@ public class ECNService : IECNService {
try {
_logger.LogInformation("Attempting to get all TECNs expired in the last day");
string today = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string yesterday = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
DateTime today = DateTime.Now.Date;
DateTime tomorrow = DateTime.Now.Date.AddDays(1);
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select ECNNumber, IsTECN, ExpirationDate, ExtensionDate, OriginatorID, Title ");
queryBuilder.Append($"from ECN where IsTECN = 1 and ");
queryBuilder.Append($"ExpirationDate between '{yesterday}' ");
queryBuilder.Append($"and '{today}'");
queryBuilder.Append("Cancelled = 0 and Deleted = 0 ");
queryBuilder.Append("and (CloseDate IS NULL or CloseDate = '');");
IEnumerable<ECN> expiredTecns = (await _dalService.QueryAsync<ECN>(queryBuilder.ToString()));
IEnumerable<ECN> activeTecns = await _dalService.QueryAsync<ECN>(queryBuilder.ToString());
_logger.LogInformation($"There are {activeTecns.Count()} active TECNs");
IEnumerable<ECN> expiredTecns = activeTecns.Where(e => ((e.ExpirationDate < tomorrow) && (e.ExpirationDate >= today)) ||
((e.ExtensionDate < tomorrow) && (e.ExtensionDate >= today)));
_logger.LogInformation($"There are {expiredTecns.Count()} TECNs with an expiration date or extension date today");
IEnumerable<ECN> expiredTecnsNotExtended = expiredTecns
.Where(e => e.ExtensionDate < DateTime.Now)
.Where(e => !(e.ExtensionDate >= tomorrow))
.ToList();
_logger.LogInformation($"There are {expiredTecnsNotExtended.Count()} TECNs expiring today");
return expiredTecnsNotExtended;
} catch (Exception ex) {
StringBuilder errMsgBuilder = new();
@ -52,21 +61,30 @@ public class ECNService : IECNService {
try {
_logger.LogInformation("Attempting to get all TECNs expiring in the next five days");
string today = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string fiveDaysFromToday = DateTime.Now.AddDays(5).ToString("yyyy-MM-dd HH:mm:ss");
DateTime tomorrow = DateTime.Now.AddDays(1).Date;
DateTime fiveDaysFromToday = DateTime.Now.AddDays(5).Date;
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select * from ECN ");
queryBuilder.Append($"where IsTECN = 1 and ");
queryBuilder.Append($"ExpirationDate between '{today}' ");
queryBuilder.Append($"and '{fiveDaysFromToday}';");
queryBuilder.Append("Cancelled = 0 and Deleted = 0 ");
queryBuilder.Append("and (CloseDate IS NULL or CloseDate = '');");
IEnumerable<ECN> expiringTecns = (await _dalService.QueryAsync<ECN>(queryBuilder.ToString()));
IEnumerable<ECN> activeTecns = (await _dalService.QueryAsync<ECN>(queryBuilder.ToString()));
_logger.LogInformation($"There are {activeTecns.Count()} active TECNs");
IEnumerable<ECN> expiringTecns = activeTecns.Where(e => ((e.ExpirationDate >= tomorrow) && (e.ExpirationDate <= fiveDaysFromToday)) ||
((e.ExtensionDate >= tomorrow) && (e.ExtensionDate <= fiveDaysFromToday)));
_logger.LogInformation($"There are {expiringTecns.Count()} TECNs with an expiration date or extension date in the next 5 days");
IEnumerable<ECN> expiringTecnsNotExtended = expiringTecns
.Where(e => e.ExtensionDate <= DateTime.Now.AddDays(5))
.Where(e => !(e.ExtensionDate > fiveDaysFromToday))
.ToList();
_logger.LogInformation($"There are {expiringTecnsNotExtended.Count()} TECNs expiring in the next five days");
return expiringTecnsNotExtended;
} catch (Exception ex) {
StringBuilder errMsgBuilder = new();

View File

@ -0,0 +1,58 @@
using Infineon.Monitoring.MonA;
namespace FabApprovalWorkerService.Services;
public interface IMonInClient {
void PostMetric(string metricName, double metricValue);
void PostStatus(string statusName, State state);
}
public class MonInClient : IMonInClient {
private readonly ILogger<MonInClient> _logger;
private readonly string _site;
private readonly string _resource;
public MonInClient(ILogger<MonInClient> logger) {
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
_site = Environment.GetEnvironmentVariable("MonInSite") ??
throw new ArgumentNullException("MonInSite environment variable not found");
_resource = Environment.GetEnvironmentVariable("FabApprovalWorkerServiceMonInResource") ??
throw new ArgumentNullException("FabApprovalWorkerServiceMonInResource environment variable not found");
}
public void PostMetric(string metricName, double metricValue) {
try {
_logger.LogInformation("Attempting to send MonIn metric request for resource {0} with name {1} and value {2}",
_resource,
metricName,
metricValue);
MonIn.GetInstance().SendPerformanceMessage(_site, _resource, metricName, metricValue);
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to send MonIn metric request for resource {0} with name {1} and value {2}. Exception: {3}",
_resource,
metricName,
metricValue,
ex.Message);
}
}
public void PostStatus(string statusName, State state) {
try {
_logger.LogInformation("Attempting to send MonIn status request for resource {0} with name {1} and value {2}",
_resource,
statusName,
state.ToString());
MonIn.GetInstance().SendStatus(_site, _resource, statusName, state);
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to send MonIn status request for resource {0} with name {1} and value {2}. Exception: {3}",
_resource,
statusName,
state.ToString(),
ex.Message);
}
}
}

View File

@ -1,181 +0,0 @@
using System.Text;
using System.Text.Json;
using FabApprovalWorkerService.Models;
using static System.Net.Mime.MediaTypeNames;
namespace FabApprovalWorkerService.Services;
public interface IMonInWorkerClient {
void PostAverage(string metricName, double metricValue);
void PostCount(string metricName, double metricValue);
void PostStatus(string statusName, StatusValue statusValue);
}
public class MonInWorkerClient : IMonInWorkerClient {
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _config;
private readonly ILogger<MonInWorkerClient> _logger;
private readonly string _baseUrl;
private readonly int _retryLimit = -1;
private readonly int _backoffInSeconds = -1;
private readonly string _resource;
public MonInWorkerClient(IHttpClientFactory httpClientFactory,
IConfiguration config,
ILogger<MonInWorkerClient> logger) {
_httpClientFactory = httpClientFactory;
if (_httpClientFactory is null) throw new ArgumentNullException("IHttpClientFactory not injected");
_config = config ??
throw new ArgumentNullException("IConfiguration not injected");
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
_baseUrl = Environment.GetEnvironmentVariable("MonInWorkerUrl") ??
throw new ArgumentNullException("MonInWorkerUrl environment variable not found");
if (!Int32.TryParse(Environment.GetEnvironmentVariable("MonInRetries"), out _retryLimit))
throw new ArgumentNullException("Valid MonInRetries environment variable not found");
if (!Int32.TryParse(Environment.GetEnvironmentVariable("MonInBackoffSeconds"), out _backoffInSeconds))
throw new ArgumentNullException("Valid MonInBackoffSeconds environment varialbe not found");
_resource = Environment.GetEnvironmentVariable("FabApprovalWorkerServiceMonInResource") ??
throw new ArgumentNullException("FabApprovalWorkerServiceMonInResource environment variable not found");
}
public async void PostStatus(string statusName, StatusValue statusValue) {
string url = _baseUrl + "status";
_logger.LogInformation("Attempting to send MonIn status request for resource {0} with name {1} and value {2} to url {3}",
_resource,
statusName,
statusValue.ToString(),
url);
try {
bool success = false;
int retries = _retryLimit;
while (!success && retries > 0) {
Task.Delay(TimeSpan.FromSeconds((_retryLimit - retries) * _backoffInSeconds)).Wait();
HttpClient httpClient = _httpClientFactory.CreateClient();
RawMonInStatusRequest statusRequest = new RawMonInStatusRequest() {
resource = _resource,
dateTime = DateTime.Now,
statusName = statusName,
statusValue = statusValue.ToString()
};
StringContent statusRequestJson = new StringContent(JsonSerializer.Serialize(statusRequest),
Encoding.UTF8,
Application.Json);
using HttpResponseMessage httpResponseMessage =
await httpClient.PostAsync(url, statusRequestJson);
success = httpResponseMessage.IsSuccessStatusCode;
retries--;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to send MonIn status request for resource {0} with name {1} and value {2} to url {3}. Exception: {4}",
_resource,
statusName,
statusValue.ToString(),
url,
ex.Message);
}
}
public async void PostCount(string metricName, double metricValue) {
string url = _baseUrl + "count";
_logger.LogInformation("Attempting to send MonIn count request for resource {0} with name {1} and value {2} to url {3}",
_resource,
metricName,
metricValue,
url);
try {
bool success = false;
int retries = _retryLimit;
while (!success && retries > 0) {
Task.Delay(TimeSpan.FromSeconds((_retryLimit - retries) * _backoffInSeconds)).Wait();
HttpClient httpClient = _httpClientFactory.CreateClient();
MonInMetricRequest metricRequest = new MonInMetricRequest() {
resource = _resource,
dateTime = DateTime.Now,
metricName = metricName,
metricValue = metricValue
};
StringContent metricRequestJson = new StringContent(JsonSerializer.Serialize(metricRequest),
Encoding.UTF8,
Application.Json);
using HttpResponseMessage httpResponseMessage =
await httpClient.PostAsync(url, metricRequestJson);
success = httpResponseMessage.IsSuccessStatusCode;
retries--;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to send MonIn count request for resource {0} with name {1} and value {2} to url {3}. Exception: {4}",
_resource,
metricName,
metricValue,
url,
ex.Message);
}
}
public async void PostAverage(string metricName, double metricValue) {
string url = _baseUrl + "average";
_logger.LogInformation("Attempting to send MonIn average request for resource {0} with name {1} and value {2} to url {3}",
_resource,
metricName,
metricValue,
url);
try {
bool success = false;
int retries = _retryLimit;
while (!success && retries > 0) {
Task.Delay(TimeSpan.FromSeconds((_retryLimit - retries) * _backoffInSeconds)).Wait();
HttpClient httpClient = _httpClientFactory.CreateClient();
MonInMetricRequest metricRequest = new MonInMetricRequest() {
resource = _resource,
dateTime = DateTime.Now,
metricName = metricName,
metricValue = metricValue
};
StringContent metricRequestJson = new StringContent(JsonSerializer.Serialize(metricRequest),
Encoding.UTF8,
Application.Json);
using HttpResponseMessage httpResponseMessage =
await httpClient.PostAsync(url, metricRequestJson);
success = httpResponseMessage.IsSuccessStatusCode;
retries--;
}
} catch (Exception ex) {
_logger.LogError("An exception occurred when attempting to send MonIn average request for resource {0} with name {1} and value {2} to url {3}. Exception: {4}",
_resource,
metricName,
metricValue,
url,
ex.Message);
}
}
}

View File

@ -6,6 +6,7 @@ namespace FabApprovalWorkerService.Services;
public interface ITrainingService {
Task<IEnumerable<int>> GetTrainingIdsForECN(int ecnNumber);
Task MarkTrainingAsComplete(int trainingId);
Task DeleteTrainingAssignment(int trainingId);
Task<IEnumerable<int>> GetTrainingAssignmentIdsForTraining(int trainingId);
Task DeleteDocAssignment(int trainingAssignmentId);
@ -30,7 +31,7 @@ public class TrainingService : ITrainingService {
StringBuilder queryBuilder = new();
queryBuilder.Append($"update TrainingDocAcks set Deleted = 1, ");
queryBuilder.Append($"DeletedDate = {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} ");
queryBuilder.Append($"DeletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' ");
queryBuilder.Append($"where TrainingAssignmentID = {trainingAssignmentId} and Reviewed = 0;");
await _dalService.ExecuteAsync(queryBuilder.ToString());
@ -51,7 +52,7 @@ public class TrainingService : ITrainingService {
StringBuilder queryBuilder = new();
queryBuilder.Append($"update TrainingAssignments set Deleted = 1, ");
queryBuilder.Append($"DeletedDate = {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} ");
queryBuilder.Append($"DeletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' ");
queryBuilder.Append($"where TrainingID = {trainingId} and status = 0;");
await _dalService.ExecuteAsync(queryBuilder.ToString());
@ -64,6 +65,27 @@ public class TrainingService : ITrainingService {
}
}
public async Task MarkTrainingAsComplete(int trainingId) {
if (trainingId <= 0) throw new ArgumentException($"Invalid training id: {trainingId}");
try {
_logger.LogInformation($"Attempting to mark training {trainingId} as complete");
StringBuilder queryBuilder = new();
queryBuilder.Append($"update Training set Status = 1, ");
queryBuilder.Append($"CompletedDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' ");
queryBuilder.Append($"where TrainingID = {trainingId};");
await _dalService.ExecuteAsync(queryBuilder.ToString());
} catch (Exception ex) {
StringBuilder errMsgBuilder = new();
errMsgBuilder.Append($"An exception occurred when attempting to mark training {trainingId} ");
errMsgBuilder.Append($"as complete. Exception: {ex.Message}");
_logger.LogError(errMsgBuilder.ToString());
throw;
}
}
public async Task<IEnumerable<int>> GetTrainingAssignmentIdsForTraining(int trainingId) {
if (trainingId <= 0) throw new ArgumentException($"Invalid trainingID: {trainingId}");

View File

@ -44,7 +44,7 @@ public class UserService : IUserService {
StringBuilder queryBuilder = new();
queryBuilder.Append("select * from Users where OOO = 1 and IsActive = 1 and ");
queryBuilder.Append($"OOOExpirationDate <= '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}';");
queryBuilder.Append($"OOOExpirationDate <= '{DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss")}';");
return (await _dalService.QueryAsync<User>(queryBuilder.ToString())).ToList();
} catch (Exception ex) {
@ -60,7 +60,7 @@ public class UserService : IUserService {
StringBuilder queryBuilder = new();
queryBuilder.Append("select * from OOOTemp where Processed = 0 and ");
queryBuilder.Append($"OOOStartDate <= '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}';");
queryBuilder.Append($"OOOStartDate <= '{DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss")}';");
return (await _dalService.QueryAsync<OOOTemp>(queryBuilder.ToString())).ToList();
} catch (Exception ex) {
@ -92,7 +92,7 @@ public class UserService : IUserService {
public async Task<bool> IsDelegatorAlreadyDelegatedTo(int userId) {
try {
_logger.LogInformation($"Attempting to determine if user {userId} is already OOO.");
_logger.LogInformation($"Attempting to determine if user {userId} is already a delegate.");
if (userId <= 0) {
_logger.LogInformation($"DelegatedTo is {userId}, which is not an active user Id");
@ -127,7 +127,7 @@ public class UserService : IUserService {
foreach (UserSubRole role in userSubRoles) {
queryBuilder.Clear();
queryBuilder.Append("insert into OOODelegatedRoles (UserID, DelegatedSubRoleID, InsertTimeStamp, Active) ");
queryBuilder.Append($"values ({userId}, {role.SubRoleID}, '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}', 1);");
queryBuilder.Append($"values ({userId}, {role.SubRoleID}, '{DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss")}', 1);");
await _dalService.ExecuteAsync(queryBuilder.ToString());
}
@ -196,23 +196,26 @@ public class UserService : IUserService {
if (userId <= 0)
throw new ArgumentException($"User Id {userId} is not a valid user Id");
if (delegatedUserId <= 0)
throw new ArgumentException($"Delegated user Id {delegatedUserId} is not a valid user Id");
if (delegatedUserId > 0) {
_logger.LogInformation($"User {userId} delegated sub roles to {delegatedUserId}");
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select SubRoleID from OOODelegatedRoles O inner join UserSubRole U ");
queryBuilder.Append("on O.DelegatedSubRoleID = U.UserSubRoleID ");
queryBuilder.Append($"where O.UserID = {userId} and Active = 1");
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select SubRoleID from OOODelegatedRoles O inner join UserSubRole U ");
queryBuilder.Append("on O.DelegatedSubRoleID = U.UserSubRoleID ");
queryBuilder.Append($"where O.UserID = {userId} and Active = 1");
List<int> userSubRoleIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
List<int> userSubRoleIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
foreach (int id in userSubRoleIds) {
queryBuilder.Clear();
queryBuilder.Append($"update UserSubRole set UserID = {userId}, Delegated = 0 ");
queryBuilder.Append($"where UserID = {delegatedUserId} and Delegated = 1 ");
queryBuilder.Append($"and SubRoleID in ({string.Join(',', userSubRoleIds)})");
foreach (int id in userSubRoleIds) {
queryBuilder.Clear();
queryBuilder.Append($"update UserSubRole set UserID = {userId}, Delegated = 0 ");
queryBuilder.Append($"where UserID = {delegatedUserId} and Delegated = 1 ");
queryBuilder.Append($"and SubRoleID in ({string.Join(',', userSubRoleIds)})");
await _dalService.ExecuteAsync(queryBuilder.ToString());
await _dalService.ExecuteAsync(queryBuilder.ToString());
}
} else {
_logger.LogInformation($"User {userId} had no delegated sub roles");
}
return true;
@ -256,25 +259,28 @@ public class UserService : IUserService {
if (userId <= 0)
throw new ArgumentException($"User Id {userId} is not a valid user Id");
if (delegatedUserId <= 0)
throw new ArgumentException($"Delegated user Id {delegatedUserId} is not a valid user Id");
if (delegatedUserId > 0) {
_logger.LogInformation($"User {userId} delegated approvals to {delegatedUserId}");
StringBuilder queryBuilder = new StringBuilder();
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("select SubRoleID from OOODelegatedRoles O inner join UserSubRole U ");
queryBuilder.Append("on O.DelegatedSubRoleID = U.UserSubRoleID ");
queryBuilder.Append($"where O.UserID = {userId} and Active = 1");
queryBuilder.Append("select SubRoleID from OOODelegatedRoles O inner join UserSubRole U ");
queryBuilder.Append("on O.DelegatedSubRoleID = U.UserSubRoleID ");
queryBuilder.Append($"where O.UserID = {userId} and Active = 1");
List<int> userSubRoleIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
List<int> userSubRoleIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
foreach (int id in userSubRoleIds) {
queryBuilder.Clear();
queryBuilder.Append($"update Approval set UserID = {userId}, Delegated = 0 ");
queryBuilder.Append($"where UserID = {delegatedUserId} and Delegated = 1 and ");
queryBuilder.Append($"(ItemStatus = {PENDING_ITEM_STATUS} or ItemStatus = {DENITED_ITEM_STATUS}) ");
queryBuilder.Append($"and SubRoleID in ({string.Join(',', userSubRoleIds)})");
foreach (int id in userSubRoleIds) {
queryBuilder.Clear();
queryBuilder.Append($"update Approval set UserID = {userId}, Delegated = 0 ");
queryBuilder.Append($"where UserID = {delegatedUserId} and Delegated = 1 and ");
queryBuilder.Append($"(ItemStatus = {PENDING_ITEM_STATUS} or ItemStatus = {DENITED_ITEM_STATUS}) ");
queryBuilder.Append($"and SubRoleID in ({string.Join(',', userSubRoleIds)})");
await _dalService.ExecuteAsync(queryBuilder.ToString());
await _dalService.ExecuteAsync(queryBuilder.ToString());
}
} else {
_logger.LogInformation($"User {userId} had not delegated approvals");
}
return true;
@ -332,7 +338,7 @@ public class UserService : IUserService {
_logger.LogInformation($"Attempting to set OOOTemp {oooTemp.ID} Processed to {oooTemp.Processed}");
string sql = $"update OOOTemp set Processed = {oooTemp.Processed} where ID = {oooTemp.ID}";
string sql = $"update OOOTemp set Processed = {Convert.ToInt32(oooTemp.Processed)} where ID = {oooTemp.ID}";
return (await _dalService.ExecuteAsync(sql)) > 0;
} catch (Exception ex) {

View File

@ -1,18 +1,20 @@
using FabApprovalWorkerService.Models;
using Infineon.Monitoring.MonA;
namespace FabApprovalWorkerService.Services;
public class WindowsService : BackgroundService {
private readonly ILogger<WindowsService> _logger;
private readonly IMonInWorkerClient _monInClient;
private readonly IMonInClient _monInClient;
public WindowsService(ILogger<WindowsService> logger,
IServiceProvider serviceProvider) {
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
using (IServiceScope scope = serviceProvider.CreateScope()) {
_monInClient = scope.ServiceProvider.GetService<IMonInWorkerClient>() ??
throw new ArgumentNullException("IMonInWorkerClient not injected");
_monInClient = scope.ServiceProvider.GetService<IMonInClient>() ??
throw new ArgumentNullException("IMonInClient not injected");
}
}
@ -21,18 +23,18 @@ public class WindowsService : BackgroundService {
try {
while (!stoppingToken.IsCancellationRequested) {
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
_monInClient.PostStatus("WindowsService", State.Ok);
_monInClient.PostStatus("WindowsService", StatusValue.Ok);
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
} catch (OperationCanceledException) {
_logger.LogError("The Windows service has been stopped");
_monInClient.PostStatus("WindowsService", StatusValue.Critical);
_monInClient.PostStatus("WindowsService", State.Critical);
} catch (Exception ex) {
_logger.LogError($"An exception occurred when running Windows Service. Exception: {ex.Message}");
_monInClient.PostStatus("WindowsService", StatusValue.Critical);
_monInClient.PostStatus("WindowsService", State.Critical);
Environment.Exit(1);
}