remove appsettings

This commit is contained in:
2023-10-19 22:28:40 -07:00
parent 9a525b44cc
commit b985898ab2
19 changed files with 246 additions and 411 deletions

View File

@ -22,27 +22,17 @@
<DefineConstants>Linux</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CliWrap" Version="3.6.3" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="7.0.5" />
<PackageReference Include="CliWrap" Version="3.6.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="7.0.11" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.IO.Ports" Version="7.0.0" />
<PackageReference Include="System.Text.Json" Version="7.0.2" />
<PackageReference Include="System.Text.Json" Version="7.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\Barcode.Host.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="appsettings.Development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -5,7 +5,6 @@ using Barcode.Host.Shared.KeyboardMouse;
using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using Microsoft.AspNetCore.SignalR;
using Serilog.Context;
using System.Globalization;
namespace Barcode.Host.Server.HostedService;
@ -65,12 +64,9 @@ public class TimedHostedService : IHostedService, IAggregateInputReader, IDispos
public Task StartAsync(CancellationToken stoppingToken)
{
string? methodName = IMethodName.GetActualAsyncMethodName();
using (LogContext.PushProperty("MethodName", methodName))
{
_Logger.LogInformation($"Timed Hosted Service: {_AppSettings.BuildSourceVersion}:{Environment.ProcessId} running.");
if (!string.IsNullOrEmpty(_AppSettings.SerialPortName))
_SerialService.Open();
_Logger.LogInformation("Timed Hosted Service: {BuildSourceVersion}:{ProcessId} running.", _AppSettings.BuildSourceVersion, Environment.ProcessId);
if (!string.IsNullOrEmpty(_AppSettings.SerialPortName))
_SerialService.Open();
#if Linux
if (!_LinuxGroupManager.IsInInputGroup().WaitAsync(stoppingToken).Result)
{
@ -80,32 +76,29 @@ public class TimedHostedService : IHostedService, IAggregateInputReader, IDispos
_ = _LinuxGroupManager.RebootSystem(_AppSettings.RootPassword);
}
#endif
List<(EventCode, char)> collection = _LastScanService.IncludeEventCodes();
foreach ((EventCode eventCode, char @char) in collection)
_CharToEventCodes.Add(eventCode, @char);
int dueTime = 0;
foreach ((string _, Timer timer) in _Timers)
{
dueTime += 300;
_ = timer.Change(dueTime, Timeout.Infinite);
}
List<(EventCode, char)> collection = _LastScanService.IncludeEventCodes();
foreach ((EventCode eventCode, char @char) in collection)
_CharToEventCodes.Add(eventCode, @char);
int dueTime = 0;
foreach ((string _, Timer timer) in _Timers)
{
dueTime += 300;
_ = timer.Change(dueTime, Timeout.Infinite);
}
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken stoppingToken)
{
string? methodName = IMethodName.GetActualAsyncMethodName();
using (LogContext.PushProperty("MethodName", methodName))
_Logger.LogInformation("Timed Hosted Service: {BuildSourceVersion}:{ProcessId} is stopping.", _AppSettings.BuildSourceVersion, Environment.ProcessId);
for (short i = 0; i < short.MaxValue; i++)
{
_Logger.LogInformation($"Timed Hosted Service: {_AppSettings.BuildSourceVersion}:{Environment.ProcessId} is stopping.");
for (short i = 0; i < short.MaxValue; i++)
{
Thread.Sleep(500);
if (_ExecutionCount == 0)
break;
}
Thread.Sleep(500);
if (_ExecutionCount == 0)
break;
}
return Task.CompletedTask;
}

View File

@ -1,4 +1,5 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Barcode.Host.Server.Models;
@ -32,8 +33,14 @@ public record AppSettings(string BuildNumber,
public override string ToString()
{
string result = JsonSerializer.Serialize(this, new JsonSerializerOptions() { WriteIndented = true });
string result = JsonSerializer.Serialize(this, AppSettingsSourceGenerationContext.Default.AppSettings);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(AppSettings))]
internal partial class AppSettingsSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,2 @@
[*.cs]
csharp_preserve_single_line_statements = true

View File

@ -1,4 +1,3 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
namespace Barcode.Host.Server.Models.Binder;
@ -6,34 +5,32 @@ namespace Barcode.Host.Server.Models.Binder;
public class AppSettings
{
[Display(Name = "Build Number"), Required] public string? BuildNumber { get; set; }
[Display(Name = "Build Source Version"), Required] public string? BuildSourceVersion { get; set; }
[Display(Name = "Last Scan Service Clear After"), Required] public int? ClearLastScanServiceAfter { get; set; }
[Display(Name = "Company"), Required] public string? Company { get; set; }
[Display(Name = "Device Name Ends With"), Required] public string? DeviceNameEndsWith { get; set; }
[Display(Name = "Equipment Name"), Required] public string? EquipmentName { get; set; }
[Display(Name = "ExpectedScanLengthA"), Required] public int? ExpectedScanLengthA { get; set; }
[Display(Name = "ExpectedScanLengthB"), Required] public int? ExpectedScanLengthB { get; set; }
[Display(Name = "File Share"), Required] public string? FileShare { get; set; }
[Display(Name = "Is Development"), Required] public bool? IsDevelopment { get; set; }
[Display(Name = "Is Staging"), Required] public bool? IsStaging { get; set; }
[Display(Name = "Linux Device Path"), Required] public string? LinuxDevicePath { get; set; }
[Display(Name = "Mock Root"), Required] public string? MockRoot { get; set; }
[Display(Name = "MonA Resource"), Required] public string? MonAResource { get; set; }
[Display(Name = "MonA Site"), Required] public string? MonASite { get; set; }
[Display(Name = "Notify Minimum"), Required] public int? NotifyMinimum { get; set; }
[Display(Name = "OpenInsight Application Programming Interface"), Required] public string? OpenInsightApplicationProgrammingInterface { get; set; }
[Display(Name = "PostTo"), Required] public string? PostTo { get; set; }
[Display(Name = "Post to Every"), Required] public int? PostToEvery { get; set; }
[Display(Name = "RootPassword"), Required] public string? RootPassword { get; set; }
[Display(Name = "Serial Port Name"), Required] public string? SerialPortName { get; set; }
[Display(Name = "Share to Every"), Required] public int? ShareToEvery { get; set; }
[Display(Name = "ToolClass"), Required] public string? ToolClass { get; set; }
[Display(Name = "URLs"), Required] public string? URLs { get; set; }
[Display(Name = "Working Directory Name"), Required] public string? WorkingDirectoryName { get; set; }
[Display(Name = "WriteToSerialEvery"), Required] public int? WriteToSerialEvery { get; set; }
#nullable restore
public string? BuildNumber { get; set; }
public string? BuildSourceVersion { get; set; }
public int? ClearLastScanServiceAfter { get; set; }
public string? Company { get; set; }
public string? DeviceNameEndsWith { get; set; }
public string? EquipmentName { get; set; }
public int? ExpectedScanLengthA { get; set; }
public int? ExpectedScanLengthB { get; set; }
public string? FileShare { get; set; }
public bool? IsDevelopment { get; set; }
public bool? IsStaging { get; set; }
public string? LinuxDevicePath { get; set; }
public string? MockRoot { get; set; }
public string? MonAResource { get; set; }
public string? MonASite { get; set; }
public int? NotifyMinimum { get; set; }
public string? OpenInsightApplicationProgrammingInterface { get; set; }
public string? PostTo { get; set; }
public int? PostToEvery { get; set; }
public string? RootPassword { get; set; }
public string? SerialPortName { get; set; }
public int? ShareToEvery { get; set; }
public string? ToolClass { get; set; }
public string? URLs { get; set; }
public string? WorkingDirectoryName { get; set; }
public int? WriteToSerialEvery { get; set; }
public override string ToString()
{
@ -44,60 +41,33 @@ public class AppSettings
private static Models.AppSettings Get(AppSettings? appSettings)
{
Models.AppSettings result;
if (appSettings is null)
throw new NullReferenceException(nameof(appSettings));
if (appSettings.BuildNumber is null)
throw new NullReferenceException(nameof(BuildNumber));
if (appSettings.BuildSourceVersion is null)
throw new NullReferenceException(nameof(BuildSourceVersion));
if (appSettings.ClearLastScanServiceAfter is null)
throw new NullReferenceException(nameof(ClearLastScanServiceAfter));
if (appSettings.Company is null)
throw new NullReferenceException(nameof(Company));
if (appSettings.DeviceNameEndsWith is null)
throw new NullReferenceException(nameof(DeviceNameEndsWith));
if (appSettings.EquipmentName is null)
throw new NullReferenceException(nameof(EquipmentName));
if (appSettings.ExpectedScanLengthA is null)
throw new NullReferenceException(nameof(ExpectedScanLengthA));
if (appSettings.ExpectedScanLengthB is null)
throw new NullReferenceException(nameof(ExpectedScanLengthB));
if (appSettings.FileShare is null)
throw new NullReferenceException(nameof(FileShare));
if (appSettings.IsDevelopment is null)
throw new NullReferenceException(nameof(IsDevelopment));
if (appSettings.IsStaging is null)
throw new NullReferenceException(nameof(IsStaging));
if (appSettings.LinuxDevicePath is null)
throw new NullReferenceException(nameof(LinuxDevicePath));
if (appSettings.MockRoot is null)
throw new NullReferenceException(nameof(MockRoot));
if (appSettings.MonAResource is null)
throw new NullReferenceException(nameof(MonAResource));
if (appSettings.MonASite is null)
throw new NullReferenceException(nameof(MonASite));
if (appSettings.NotifyMinimum is null)
throw new NullReferenceException(nameof(NotifyMinimum));
if (appSettings.OpenInsightApplicationProgrammingInterface is null)
throw new NullReferenceException(nameof(OpenInsightApplicationProgrammingInterface));
if (appSettings.PostTo is null)
throw new NullReferenceException(nameof(PostTo));
if (appSettings.PostToEvery is null)
throw new NullReferenceException(nameof(PostToEvery));
if (appSettings.RootPassword is null)
throw new NullReferenceException(nameof(RootPassword));
if (appSettings.SerialPortName is null)
throw new NullReferenceException(nameof(SerialPortName));
if (appSettings.ShareToEvery is null)
throw new NullReferenceException(nameof(ShareToEvery));
if (appSettings.ToolClass is null)
throw new NullReferenceException(nameof(ToolClass));
if (appSettings.URLs is null)
throw new NullReferenceException(nameof(URLs));
if (appSettings.WorkingDirectoryName is null)
throw new NullReferenceException(nameof(WorkingDirectoryName));
if (appSettings.WriteToSerialEvery is null)
throw new NullReferenceException(nameof(WriteToSerialEvery));
if (appSettings is null) throw new NullReferenceException(nameof(appSettings));
if (appSettings.BuildNumber is null) throw new NullReferenceException(nameof(BuildNumber));
if (appSettings.BuildSourceVersion is null) throw new NullReferenceException(nameof(BuildSourceVersion));
if (appSettings.ClearLastScanServiceAfter is null) throw new NullReferenceException(nameof(ClearLastScanServiceAfter));
if (appSettings.Company is null) throw new NullReferenceException(nameof(Company));
if (appSettings.DeviceNameEndsWith is null) throw new NullReferenceException(nameof(DeviceNameEndsWith));
if (appSettings.EquipmentName is null) throw new NullReferenceException(nameof(EquipmentName));
if (appSettings.ExpectedScanLengthA is null) throw new NullReferenceException(nameof(ExpectedScanLengthA));
if (appSettings.ExpectedScanLengthB is null) throw new NullReferenceException(nameof(ExpectedScanLengthB));
if (appSettings.FileShare is null) throw new NullReferenceException(nameof(FileShare));
if (appSettings.IsDevelopment is null) throw new NullReferenceException(nameof(IsDevelopment));
if (appSettings.IsStaging is null) throw new NullReferenceException(nameof(IsStaging));
if (appSettings.LinuxDevicePath is null) throw new NullReferenceException(nameof(LinuxDevicePath));
if (appSettings.MockRoot is null) throw new NullReferenceException(nameof(MockRoot));
if (appSettings.MonAResource is null) throw new NullReferenceException(nameof(MonAResource));
if (appSettings.MonASite is null) throw new NullReferenceException(nameof(MonASite));
if (appSettings.NotifyMinimum is null) throw new NullReferenceException(nameof(NotifyMinimum));
if (appSettings.OpenInsightApplicationProgrammingInterface is null) throw new NullReferenceException(nameof(OpenInsightApplicationProgrammingInterface));
if (appSettings.PostTo is null) throw new NullReferenceException(nameof(PostTo));
if (appSettings.PostToEvery is null) throw new NullReferenceException(nameof(PostToEvery));
if (appSettings.RootPassword is null) throw new NullReferenceException(nameof(RootPassword));
if (appSettings.SerialPortName is null) throw new NullReferenceException(nameof(SerialPortName));
if (appSettings.ShareToEvery is null) throw new NullReferenceException(nameof(ShareToEvery));
if (appSettings.ToolClass is null) throw new NullReferenceException(nameof(ToolClass));
if (appSettings.URLs is null) throw new NullReferenceException(nameof(URLs));
if (appSettings.WorkingDirectoryName is null) throw new NullReferenceException(nameof(WorkingDirectoryName));
if (appSettings.WriteToSerialEvery is null) throw new NullReferenceException(nameof(WriteToSerialEvery));
result = new(
appSettings.BuildNumber,
appSettings.BuildSourceVersion,

View File

@ -1,6 +1,6 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Diagnostics;
namespace Barcode.Host.Server.Pages;
@ -19,5 +19,4 @@ public class ErrorModel : PageModel
public void OnGet() =>
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}

View File

@ -15,4 +15,4 @@ public class NotificationModel : PageModel
{
}
}
}

View File

@ -2,50 +2,21 @@
using Barcode.Host.Server.Hubs;
using Barcode.Host.Server.Models;
using Barcode.Host.Server.Services;
using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using Serilog;
using System.Reflection;
namespace Barcode.Host.Server;
public class Program
{
private static (string, WebApplicationOptions) Get(string[] args)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string? assemblyName = assembly.GetName()?.Name;
if (string.IsNullOrEmpty(assemblyName))
throw new Exception();
string baseAssemblyName = assemblyName.Split('.')[0];
string webRootPath = Path.Combine(AppContext.BaseDirectory.Split(baseAssemblyName)[0], baseAssemblyName, "wwwroot");
if (!Directory.Exists(webRootPath))
webRootPath = string.Empty;
WebApplicationOptions webApplicationOptions = new()
{
Args = args,
ContentRootPath = AppContext.BaseDirectory,
WebRootPath = webRootPath
};
return new(assemblyName, webApplicationOptions);
}
public static int Main(string[] args)
{
LoggerConfiguration loggerConfiguration = new();
(string assemblyName, _) = Get(args);
ILogger<Program>? logger = null;
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
_ = webApplicationBuilder.Configuration.AddUserSecrets<Program>();
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration);
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!");
string workingDirectory = IWorkingDirectory.GetWorkingDirectory(assemblyName, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, webApplicationBuilder.Configuration);
_ = SerilogHostBuilderExtensions.UseSerilog(webApplicationBuilder.Host);
Log.Logger = loggerConfiguration.CreateLogger();
Serilog.ILogger log = Log.ForContext<Program>();
if (string.IsNullOrEmpty(appSettings.Company))
throw new Exception("Company name must have a value!");
try
{
if (appSettings.IsStaging && appSettings.IsDevelopment)
@ -68,6 +39,7 @@ public class Program
_ = webApplicationBuilder.Services.AddHostedService<TimedHostedService>();
_ = webApplicationBuilder.Services.AddSwaggerGen();
WebApplication webApplication = webApplicationBuilder.Build();
logger = webApplication.Services.GetRequiredService<ILogger<Program>>();
if (appSettings.IsDevelopment)
{
_ = webApplication.UseSwagger();
@ -79,25 +51,23 @@ public class Program
_ = webApplication.UseExceptionHandler("/Error");
_ = webApplication.UseHsts();
}
_ = webApplication.Lifetime.ApplicationStopped.Register(Log.CloseAndFlush);
_ = webApplication.UseStaticFiles();
_ = webApplication.UseRouting();
_ = webApplication.UseAuthorization();
_ = webApplication.MapControllers();
_ = webApplication.MapRazorPages();
_ = webApplication.MapHub<NotificationHub>($"/{nameof(NotificationHub)}");
log.Information("Starting Web Application");
logger.LogInformation("Starting Web Application");
logger.LogCritical("{Company}", appSettings.Company);
webApplication.Run();
return 0;
}
catch (Exception ex)
{
log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
try
{ logger?.LogCritical(ex, "Host terminated unexpectedly"); }
catch (Exception) { }
throw;
}
}

View File

@ -1,13 +0,0 @@
{
"ExpectedScanLengthA": 6,
"ExpectedScanLengthB": 9,
"Logging": {
"LogLevel": {
"Log4netProvider": "Debug"
}
},
"IsDevelopment": true,
"Serilog": {
"MinimumLevel": "Debug"
}
}

View File

@ -1,74 +0,0 @@
{
"BuildNumber": "1",
"BuildSourceVersion": "1234567",
"Company": "Infineon Technologies Americas Corp.",
"ClearLastScanServiceAfter": 250,
"DeviceNameEndsWith": "Symbol Bar Code Scanner",
"EquipmentName": "",
"ExpectedScanLengthA": 8,
"ExpectedScanLengthB": 14,
"ExpectedScanLengthBExample": "1TO172125.1.11",
"FileShare": "",
"LinuxDevicePath": "/proc/bus/input/devices",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Log4netProvider": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"IsDevelopment": false,
"IsStaging": false,
"NotifyMinimum": 3,
"MockRoot": "",
"MonAResource": "OI_Metrology_Viewer_EC",
"MonASite": "auc",
"OpenInsightApplicationProgrammingInterface": "https://oi-prod-ec-api.mes.infineon.com/api/oiWizard",
"PostTo": "",
"PostToEvery": 1000,
"SerialPortName": "/dev/ttyUSB0",
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Debug",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}"
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "%workingDirectory% - Log/log-.txt",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}",
"rollingInterval": "Hour"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
],
"Properties": {
"Application": "Sample"
}
},
"ShareToEvery": 1000,
"RootPassword": "",
"ToolClass": "FTIR",
"URLs": "http://localhost:5003;",
"WorkingDirectoryName": "IFXApps",
"WriteToSerialEvery": 750
}