Compare commits

...

7 Commits

Author SHA1 Message Date
13b9731edf Refactor 2024-05-21 07:47:34 -07:00
e32a942fde Better format 2024-05-21 07:43:37 -07:00
26a28afe78 Removed nested objects from Microsoft User Secrets 2024-05-21 07:37:43 -07:00
878750b284 Made Nuget more generic
Moved and synced RijndaelEncryption
2024-04-28 10:46:01 -07:00
4eb70db231 HelperNuget 2024-04-18 09:11:39 -07:00
135f236b8c Trigger 2024-04-18 07:25:36 -07:00
27ba309e88 HelperEDADatabase
HelperEAFProgramData
HelperCompass
HelperInfinityQS
HelperSerial
HelperTCP
dotnet_analyzer_diagnostic
2024-04-16 10:32:55 -07:00
33 changed files with 4686 additions and 365 deletions

View File

@ -90,24 +90,46 @@ csharp_style_var_elsewhere = false:warning
csharp_style_var_for_built_in_types = false:warning csharp_style_var_for_built_in_types = false:warning
csharp_style_var_when_type_is_apparent = false:warning csharp_style_var_when_type_is_apparent = false:warning
csharp_using_directive_placement = outside_namespace csharp_using_directive_placement = outside_namespace
dotnet_analyzer_diagnostic.category-Design.severity = error
dotnet_analyzer_diagnostic.category-Documentation.severity = error
dotnet_analyzer_diagnostic.category-Globalization.severity = none
dotnet_analyzer_diagnostic.category-Interoperability.severity = error
dotnet_analyzer_diagnostic.category-Maintainability.severity = error
dotnet_analyzer_diagnostic.category-Naming.severity = none
dotnet_analyzer_diagnostic.category-Performance.severity = none
dotnet_analyzer_diagnostic.category-Reliability.severity = error
dotnet_analyzer_diagnostic.category-Security.severity = error
dotnet_analyzer_diagnostic.category-SingleFile.severity = error
dotnet_analyzer_diagnostic.category-Style.severity = error
dotnet_analyzer_diagnostic.category-Usage.severity = error
dotnet_code_quality_unused_parameters = all dotnet_code_quality_unused_parameters = all
dotnet_code_quality_unused_parameters = non_public # IDE0060: Remove unused parameter dotnet_code_quality_unused_parameters = non_public # IDE0060: Remove unused parameter
dotnet_code_quality.CAXXXX.api_surface = private, internal dotnet_code_quality.CAXXXX.api_surface = private, internal
dotnet_diagnostic.CA1825.severity = warning # CA1823: Avoid zero-length array allocations dotnet_diagnostic.CA1511.severity = warning # CA1511: Use 'ArgumentException.ThrowIfNullOrEmpty' instead of explicitly throwing a new exception instance
dotnet_diagnostic.CA1513.severity = warning # Use 'ObjectDisposedException.ThrowIf' instead of explicitly throwing a new exception instance
dotnet_diagnostic.CA1825.severity = warning # CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1829.severity = warning # CA1829: Use Length/Count property instead of Count() when available dotnet_diagnostic.CA1829.severity = warning # CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable
dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance
dotnet_diagnostic.CA1862.severity = warning # CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase'
dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead. dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead.
dotnet_diagnostic.CA2201.severity = none # CA2201: Exception type System.NullReferenceException is reserved by the runtime
dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])'
dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name
dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2"); dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2");
dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant. dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant.
dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary
dotnet_diagnostic.IDE0010.severity = none # Add missing cases to switch statement (IDE0010)
dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified
dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031) dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031)
dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed
dotnet_diagnostic.IDE0048.severity = none # Parentheses preferences (IDE0047 and IDE0048)
dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049) dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049)
dotnet_diagnostic.IDE0051.severity = error # Private member '' is unused [, ]
dotnet_diagnostic.IDE0058.severity = warning # IDE0058: Expression value is never used
dotnet_diagnostic.IDE0060.severity = warning # IDE0060: Remove unused parameter dotnet_diagnostic.IDE0060.severity = warning # IDE0060: Remove unused parameter
dotnet_diagnostic.IDE0074.severity = warning # IDE0074: Use compound assignment
dotnet_diagnostic.IDE0130.severity = none # Namespace does not match folder structure (IDE0130)
dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified
dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290) dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290)
dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified

7
.gitignore vendored
View File

@ -326,4 +326,9 @@ ASALocalRun/
*.nvuser *.nvuser
# MFractors (Xamarin productivity tool) working folder # MFractors (Xamarin productivity tool) working folder
.mfractor/ .mfractor/
*.all
*.pcl
*.pdf
*.raw

72
.vscode/settings.json vendored
View File

@ -1,37 +1,39 @@
{ {
"[markdown]": { "[markdown]": {
"editor.wordWrap": "off" "editor.wordWrap": "off"
}, },
"files.exclude": { "files.exclude": {
"**/.git": false, "**/.git": false,
"**/node_modules": true "**/node_modules": true
}, },
"files.watcherExclude": { "files.watcherExclude": {
"**/node_modules": true "**/node_modules": true
}, },
"cSpell.words": [ "cSpell.words": [
"ASPNETCORE", "ASPNETCORE",
"BIRT", "BIRT",
"CHIL", "CHIL",
"DEAT", "DEAT",
"endianness", "endianness",
"FAMC", "FAMC",
"FAMS", "FAMS",
"GIVN", "GIVN",
"HUSB", "HUSB",
"INDI", "INDI",
"Infineon", "Infineon",
"Kanban", "Kanban",
"kanbn", "kanbn",
"Kofax", "Kofax",
"NSFX", "NSFX",
"OBJE", "OBJE",
"onenote", "onenote",
"pged", "PDSF",
"Phares", "pged",
"Serilog", "Phares",
"SUBM", "Rijndael",
"SURN", "Serilog",
"SYSLIB" "SUBM",
] "SURN",
"SYSLIB"
]
} }

12
.vscode/tasks.json vendored
View File

@ -22,7 +22,7 @@
"-p", "-p",
"${workspaceFolder}/File-Watcher.csproj", "${workspaceFolder}/File-Watcher.csproj",
"set", "set",
"asdf", "_UserSecretsId",
"6516d19d6569" "6516d19d6569"
], ],
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
@ -72,9 +72,15 @@
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
}, },
{ {
"label": "File-Watcher AOT s V Helpers", "label": "File-Folder-Helper AOT s V Helpers",
"type": "shell", "type": "shell",
"command": "& L:/DevOps/Mesa_FI/File-Watcher/bin/Release/net8.0/win-x64/publish/File-Watcher.exe s V Helpers", "command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s V Helpers",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s X Sort",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s X 'L:/DevOps/Mesa_FI/File-Watcher' Day-Helper-2024-01-08 'L:/DevOps/Mesa_FI/File-Watcher/Helpers'",
"problemMatcher": [] "problemMatcher": []
} }
] ]

View File

@ -1,19 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk.Worker"> <Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup> <PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <RuntimeIdentifier>win-x64</RuntimeIdentifier>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<UserSecretsId>b6f34b8e-5026-41d4-9c28-6516d19d6569</UserSecretsId> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<UserSecretsIdBeforeOracle>b6f34b8e-5026-41d4-9c28-6516d19d6569</UserSecretsIdBeforeOracle>
<UserSecretsId>6062c774-99a9-4f4a-b42d-a9cb7fcbd8be</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.1" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.0" /> <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="23.4.0" />
<PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.5" />
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.3" />
</ItemGroup>
<ItemGroup>
<None Condition="'$(Configuration)' == 'Debug'" Include="\\mestsa003.infineon.com\EC_EAFRepository\Staging\DeploymentStorage\GhostPCL\gpcl6win64\gpcl6dll64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Condition="'$(Configuration)' == 'Debug'" Include="\\mestsa003.infineon.com\EC_EAFRepository\Staging\DeploymentStorage\GhostPCL\gpcl6win64\gpcl6win64.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Condition="'$(Configuration)' == 'Debug'" Include="\\mestsa003.infineon.com\EC_EAFRepository\Staging\DeploymentStorage\LincPDFC\v2.6.6.21\LincPDFC.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Condition="'$(Configuration)' == 'Release'" Include="\\mesfs.infineon.com\EC_EAFRepository\Staging\DeploymentStorage\GhostPCL\gpcl6win64\gpcl6dll64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Condition="'$(Configuration)' == 'Release'" Include="\\mesfs.infineon.com\EC_EAFRepository\Staging\DeploymentStorage\GhostPCL\gpcl6win64\gpcl6win64.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Condition="'$(Configuration)' == 'Release'" Include="\\mesfs.infineon.com\EC_EAFRepository\Staging\DeploymentStorage\LincPDFC\v2.6.6.21\LincPDFC.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>

178
Helpers/EDA/Common.cs Normal file
View File

@ -0,0 +1,178 @@
using System.Text;
namespace File_Watcher.Helpers.EDA;
[Serializable]
public class Common
{
public string? ConfigurationProductiveState { get; set; }
public string? ConfigurationState { get; set; }
public string? ContainerName { get; set; }
public ModuleInstanceTypeName? ObjectType { get; set; }
public string? UnitName { get; set; }
//
public string Filename { get; set; }
public string StartTimeFormat { get; set; }
public string[] StoragePaths { get; set; }
//
public List<string[]> GeneralTriggers { get; set; }
public List<string[]> LogisticsAttributes { get; set; }
public List<string[]> LogisticsColumns { get; set; }
public string LogisticsEquipmentAlias { get; set; }
public List<string?[]> LogisticsTriggers { get; set; }
public Dictionary<int, List<string[]>> LogisticsTriggersCallDefinitionAttributes { get; set; }
public Dictionary<int, string[]> LogisticsTriggersKeysKeyMapping { get; set; }
public List<string?[]> Parameters { get; set; }
public string ParametersAsCsv { get; set; }
public string Source { get; set; }
public List<string[]> StartTriggersDCP { get; set; }
public List<string[]> StopTriggersDCP { get; set; }
[Obsolete("Only for DeserializeObject")]
public Common()
{
Parameters = [];
ObjectType = null;
StoragePaths = [];
GeneralTriggers = [];
StopTriggersDCP = [];
LogisticsColumns = [];
Source = string.Empty;
StartTriggersDCP = [];
LogisticsTriggers = [];
Filename = string.Empty;
UnitName = string.Empty;
LogisticsAttributes = [];
ContainerName = string.Empty;
ParametersAsCsv = string.Empty;
StartTimeFormat = string.Empty;
ConfigurationState = string.Empty;
LogisticsTriggersKeysKeyMapping = [];
LogisticsEquipmentAlias = string.Empty;
ConfigurationProductiveState = string.Empty;
LogisticsTriggersCallDefinitionAttributes = [];
}
public Common(ModuleInstanceTypeName objectType, object unitName, object containerName, object configurationState, object configurationProductiveState)
{
Parameters = [];
StoragePaths = [];
GeneralTriggers = [];
StopTriggersDCP = [];
LogisticsColumns = [];
Source = string.Empty;
StartTriggersDCP = [];
LogisticsTriggers = [];
Filename = string.Empty;
ObjectType = objectType;
LogisticsAttributes = [];
ParametersAsCsv = string.Empty;
StartTimeFormat = string.Empty;
UnitName = unitName.ToString();
LogisticsTriggersKeysKeyMapping = [];
LogisticsEquipmentAlias = string.Empty;
ContainerName = containerName.ToString();
LogisticsTriggersCallDefinitionAttributes = [];
ConfigurationState = configurationState.ToString();
ConfigurationProductiveState = configurationProductiveState.ToString();
}
public void Update(PDSFConfiguration configuration)
{
if (configuration.Settings.StoragePaths is null)
StoragePaths = [];
else
StoragePaths = configuration.Settings.StoragePaths;
StartTimeFormat = configuration.Settings.StartTimeFormat;
Filename = configuration.Settings.Filename;
//
Source = configuration.DataCollection.Source;
LogisticsEquipmentAlias = configuration.DataCollection.Logistics.EquipmentAlias;
//if (LogisticsEquipmentAlias == "R47-PLC")
//{ }
foreach (PDSFConfigurationDataCollectionLogisticsAttribute item in from l in configuration.DataCollection.Logistics.Attributes orderby l.Use descending, l.Order select l)
LogisticsAttributes.Add([item.Use.ToString(), item.Order.ToString("000"), item.Key, item.Placeholder]);
foreach (PDSFConfigurationDataCollectionLogisticsColumn item in configuration.DataCollection.Logistics.Columns)
LogisticsColumns.Add([item.ID.ToString(), item.Prefix]);
foreach (PDSFConfigurationDataCollectionParameter1 item in from l in configuration.DataCollection.VirtualParameters orderby l.Use descending, l.Order select l)
{
if (item?.Conditions is null)
continue;
if (string.IsNullOrEmpty(item.Alias) && !string.IsNullOrEmpty(item.Conditions.ConditionModel?.Name))
{
if (item.Use)
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
else
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, string.Empty, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
}
else
{
if (item.Use)
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
else
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, string.Empty, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
}
}
foreach (PDSFConfigurationDataCollectionParameter item in from l in configuration.DataCollection.Parameters orderby l.Use descending, l.Order select l)
{
if (string.IsNullOrEmpty(item.Alias) && !string.IsNullOrEmpty(item.Conditions?.ConditionModel?.Name))
{
if (item.Use)
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
else
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, string.Empty, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
}
else
{
if (item is null)
continue;
if (item.Use)
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
else
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, string.Empty, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
}
}
Parameters = (from l in Parameters orderby l[0] descending, l[1] select l).ToList();
StringBuilder text = new();
//text.AppendLine("\"AliasName\";\"Condition\";\"EventId\";\"ExceptionId\";\"Formula\";\"HardwareId\";\"OrderId\";\"ParameterName\";\"Remark\";\"ReportName\";\"SourceId\";\"Use\"");
//"Test";"";"";"";"";"";"1";"MICROSCOPE01/MET08MESMICROSCOPE/Test";"";"MICROSCOPE01/MET08MESMICROSCOPE/FileRead";"";"True""
_ = text.AppendLine("\"Use\";\"OrderId\";\"ReportName\";\"ParameterName\";\"AliasName\";\"HardwareId\";\"Remark\";\"Formula\"");
foreach (string?[] parameter in Parameters)
{
for (int i = 0; i < 7; i++)
_ = text.Append('"').Append(parameter[i]).Append("\";");
_ = text.Remove(text.Length - 1, 1);
_ = text.AppendLine();
}
ParametersAsCsv = text.ToString();
foreach (PDSFConfigurationDataCollectionGeneralTriggers item in configuration.DataCollection.GeneralTriggers)
{
foreach (PDSFConfigurationDataCollectionGeneralTriggersVariableModel gv in item.GlobalVariables)
GeneralTriggers.Add([item.Name, gv.Name, gv.ParameterName, gv.Formula]);
}
{
PDSFConfigurationDataCollectionStartTriggersDCP item = configuration.DataCollection.StartTriggers.DCP;
if (item is not null)
StartTriggersDCP.Add([item.Name, item.Rule, item.ResolveGlobalVariableBeforeTrigger.ToString()]);
}
if (configuration.DataCollection.Logistics.Triggers.UpdateTrigger is not null)
{
foreach (PDSFConfigurationDataCollectionLogisticsTriggersUpdateTriggerLogisticRequest item in configuration.DataCollection.Logistics.Triggers.UpdateTrigger.LogisticRequest)
{
LogisticsTriggers.Add([item.Name.ToString(), item.LogisticsColumn.Fixed.ToString(), item.Rule, item.Keys.Scenario, item.Keys.DefaultJobIndex.ToString(), item.Keys.DefaultCarrierIndex.ToString(), item.Keys.DefaultSlotIndex.ToString(), item.DataPool.ToString()]);
if (item.Keys.KeyMapping is not null)
LogisticsTriggersKeysKeyMapping.Add(item.Name, [item.Keys.KeyMapping.KeyName, item.Keys.KeyMapping.ParameterName, item.Keys.KeyMapping.Formula]);
LogisticsTriggersCallDefinitionAttributes.Add(item.Name, []);
foreach (PDSFConfigurationDataCollectionLogisticsTriggersUpdateTriggerLogisticRequestCallDefinitionLogisticCallDefinitionAttribute att in item.CallDefinition.Attributes)
LogisticsTriggersCallDefinitionAttributes[item.Name].Add([att.LogisticsKey, att.Source, att.MappedParameterName, att.Formula]);
}
}
{
PDSFConfigurationDataCollectionStopTriggersDCP item = configuration.DataCollection.StopTriggers.DCP;
if (item is not null)
StopTriggersDCP.Add([item.Name, item.Rule, item.ResolveGlobalVariableBeforeTrigger.ToString(), item.ResetGlobalVariablesAfterTrigger.ToString()]);
}
}
}

457
Helpers/EDA/DCP.cs Normal file
View File

@ -0,0 +1,457 @@
using System.Dynamic;
using System.Text;
using System.Text.Json;
namespace File_Watcher.Helpers.EDA;
public class DCP
{
internal static string GetEdaObjectToHtml(string edaObjectFile, Common common)
{
StringBuilder result = new();
string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
_ = result.AppendLine("<!DOCTYPE html>");
_ = result.AppendLine("<html lang=\"en\">");
_ = result.AppendLine("<head>");
_ = result.AppendLine("<style>table, th, td{border:1px solid black;} td{padding:2px}</style>");
_ = result.Append("<title>").Append(title).AppendLine("</title>");
_ = result.AppendLine("</head>");
_ = result.AppendLine("<body>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Unit Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Container Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Configuration State").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Configuration Productive State").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("LogisticsEquipmentAlias").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("StoragePath(s)").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("StartTimeFormat").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Filename").AppendLine("</th>");
_ = result.AppendLine("</tr>");
_ = result.AppendLine("<tr>");
_ = result.Append("<td nowrap>").Append(common.UnitName).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.ContainerName).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.ConfigurationState).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.ConfigurationProductiveState).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.LogisticsEquipmentAlias).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.Source).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(string.Join("</br >", common.StoragePaths)).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.StartTimeFormat).AppendLine("</td>");
_ = result.Append("<td nowrap>").Append(common.Filename).AppendLine("</td>");
_ = result.AppendLine("</tr>");
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Key").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Placeholder").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string[] item in common.LogisticsAttributes)
{
if (item.Length > 2 && !item[2].StartsWith("Z_"))
{
_ = result.AppendLine("<tr>");
foreach (string value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("ID").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Prefix").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string[] item in common.LogisticsColumns)
{
_ = result.AppendLine("<tr>");
foreach (string value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("FullName").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Alias").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("HardWareId").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Description").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Virtual").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Column#").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string?[] item in common.Parameters)
{
_ = result.AppendLine("<tr>");
foreach (string? value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Parent Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string[] item in common.GeneralTriggers)
{
_ = result.AppendLine("<tr>");
foreach (string value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string[] item in common.StartTriggersDCP)
{
_ = result.AppendLine("<tr>");
foreach (string value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Fixed").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Scenario").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("DefaultJobIndex").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("DefaultCarrierIndex").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("DefaultSlotIndex").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("DataPool").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string?[] item in common.LogisticsTriggers)
{
if (item is null)
continue;
_ = result.AppendLine("<tr>");
foreach (string? value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("<td>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("KeyName").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (KeyValuePair<int, string[]> keyValuePair in common.LogisticsTriggersKeysKeyMapping)
{
_ = result.AppendLine("<tr>");
foreach (string value in keyValuePair.Value)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("</td>");
_ = result.AppendLine("<td>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("LogisticsKey").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("MappedParameterName").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (KeyValuePair<int, List<string[]>> keyValuePair in common.LogisticsTriggersCallDefinitionAttributes)
{
foreach (string[] values in keyValuePair.Value)
{
if (values.Length > 0 && !values[0].StartsWith("Z_"))
{
_ = result.AppendLine("<tr>");
foreach (string value in values)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
}
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("<table>");
_ = result.AppendLine("<tr>");
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
_ = result.Append("<th nowrap>").Append("ResetGlobalVariablesAfterTrigger").AppendLine("</th>");
_ = result.AppendLine("</tr>");
foreach (string[] item in common.StopTriggersDCP)
{
_ = result.AppendLine("<tr>");
foreach (string value in item)
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
_ = result.AppendLine("</tr>");
}
_ = result.AppendLine("</table>");
_ = result.AppendLine("<hr>");
_ = result.AppendLine("</body>");
_ = result.AppendLine("</html>");
return result.ToString();
}
private static string? ReplaceNull(object @object)
{
if (@object is null)
return string.Empty;
else
return @object.ToString();
}
private static void TextResolveEntry(StringBuilder result, dynamic expandoObject, int level, string super, int? i, bool group)
{
level += 1;
foreach (dynamic entry in expandoObject)
{
#pragma warning disable IL2026, IL3050
if (entry.Value is ExpandoObject)
TextResolveEntry(result, entry.Value, level, string.Concat(super, " : ", entry.Key), i, group);
else
{
if (entry.Value is not ICollection<object>)
{
if (i is null)
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("--->").AppendLine(ReplaceNull(entry.Value));
else
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value));
}
else
{
if (!group)
{
for (i = 0; i.Value < entry.Value.Count; i++)
{
if (entry.Value[i.Value] is ExpandoObject)
TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
else
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
}
}
else
{
for (i = 0; i.Value < entry.Value.Count; i++)
{
if (entry.Value[i.Value] is not ExpandoObject)
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
}
for (i = 0; i.Value < entry.Value.Count; i++)
{
if (entry.Value[i.Value] is ExpandoObject)
TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
}
}
i = null;
}
}
#pragma warning restore IL2026, IL3050
}
level -= 1;
if (level == 0)
{ }
}
internal static string GetText(string edaObjectFile, Common common, string json)
{
StringBuilder result = new();
if (result.Length > 0) //Skipping because System.Text.Json changed the way Expando works
{
#pragma warning disable IL2026, IL3050
string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
dynamic? expandoObject = JsonSerializer.Deserialize<ExpandoObject>(json);
_ = result.AppendLine(title);
_ = result.AppendLine("Loop -> \"Normal\"");
_ = result.AppendLine(edaObjectFile);
_ = result.AppendLine();
TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: false);
_ = result.AppendLine();
_ = result.AppendLine();
_ = result.AppendLine();
_ = result.AppendLine(title);
_ = result.AppendLine("Loop -> \"Grouped\"");
_ = result.AppendLine(edaObjectFile);
_ = result.AppendLine();
TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: true);
#pragma warning restore IL2026, IL3050
}
return result.ToString();
}
internal static string GetEdaObjectToDMSGridFormat(string edaObjectFile, Common common, bool useAlias)
{
StringBuilder result = new();
if (string.IsNullOrEmpty(edaObjectFile))
{ }
string? value;
string[] segments;
int? recordStart = null;
bool hasRecordStart = false;
string name = string.Concat(common.LogisticsEquipmentAlias, "_", common.ContainerName);
_ = result.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
_ = result.Append("<Format Name=\"").Append(name).Append("\">").AppendLine();
_ = result.AppendLine(" <General RecordStart=\"\" RecordLength=\"0\" ReadCommand=\"\" DecimalSeparator=\".\">");
_ = result.AppendLine(" <RecordTerminator>&lt;13&gt;&lt;10&gt;</RecordTerminator>");
_ = result.AppendLine(" <ColumnSeparator>&lt;9&gt;</ColumnSeparator>");
_ = result.AppendLine(" </General>");
_ = result.AppendLine(" <Fields>");
for (int i = 0; i < common.Parameters.Count; i++)
{
if (common.Parameters[i][3] == "RECORD_START")
{
hasRecordStart = true;
break;
}
}
for (int i = 0; i < common.Parameters.Count; i++)
{
if (recordStart is null && common.Parameters[i][3] == "RECORD_START")
recordStart = i;
if ((!hasRecordStart || (hasRecordStart && recordStart.HasValue)) && common.Parameters[i][0] == "True")
{
if (useAlias && !string.IsNullOrEmpty(common.Parameters[i][3]))
{
value = common.Parameters[i][3];
value ??= string.Empty;
name = value.Replace("'", string.Empty);
}
else
{
value = common.Parameters[i][2];
value ??= string.Empty;
segments = value.Split('/');
name = segments[^1];
}
_ = result.Append(" <Field Name=\"").Append(name).Append("\" ColumnNumber=\"").Append(i + common.LogisticsColumns.Count + 2).Append("\" StartPosition=\"\" Length=\"\" DataType=\"Text\" NullReplacement=\"\" />").AppendLine();
}
}
_ = result.AppendLine(" </Fields>");
_ = result.AppendLine(" <Conditions>");
_ = result.AppendLine(" <Column />");
_ = result.AppendLine(" <Row>");
_ = result.AppendLine(" <Condition>");
_ = result.AppendLine(" <SkipHeaderCount>7</SkipHeaderCount>");
_ = result.AppendLine(" <SkipRowFilter>0</SkipRowFilter>");
_ = result.AppendLine(" <SkipRowValue>");
_ = result.AppendLine(" </SkipRowValue>");
_ = result.AppendLine(" </Condition>");
_ = result.AppendLine(" </Row>");
_ = result.AppendLine(" </Conditions>");
_ = result.AppendLine("</Format>");
return result.ToString();
}
internal static string GetEdaObjectToAPCParameter(string edaObjectFile, Common common)
{
StringBuilder result = new();
if (string.IsNullOrEmpty(edaObjectFile))
{ }
string? value;
string parameter;
string[] segments;
string parameterSub35;
_ = result.AppendLine("ExportFileVersion=1.0.6");
_ = result.AppendLine("ExportFromTabsheet=Para");
_ = result.AppendLine("FieldName\tLongName\tMatchMode\tEquipment\tName\tPdsfNameConvCol\tPdsfNameDataType\tType\tChamberInfo\tUnifiedPara\tDateFormat\tUsername\tId\tWorkcenterId\tSite\tArea\tWorkcenter\tValidFrom\tValidTo");
_ = result.AppendLine("TIME_PREV_DIFF\tTIME_PREV_DIFF\tEXACT\t*\tTIME_PREV_DIFF\t\tNUMERIC\tRUN\t\tTIME_PREV_DIFF\t\tPHARES\t95069\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
_ = result.AppendLine("TIME\tTIME\tEXACT\t*\tTIME\t\tNUMERIC\tRUN\t\tTIME\t\tPHARES\t95070\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
for (int i = 0; i < common.Parameters.Count; i++)
{
if (common.Parameters[i][0] == "True")
{
value = common.Parameters[i][2];
value ??= string.Empty;
segments = value.Split('/');
parameter = segments[^1];
if (parameter.Length < 35)
parameterSub35 = parameter;
else
parameterSub35 = parameter[..35];
_ = result.Append(parameterSub35).Append("\tDIVERSE\tEXACT\t*\t").Append(parameterSub35).AppendLine("\t\tNUMERIC\tRUN\t\t\t\tPHARES\t9000000012\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
}
}
_ = result.AppendLine();
_ = result.AppendLine();
_ = result.AppendLine();
for (int i = 0; i < common.Parameters.Count; i++)
{
if (common.Parameters[i][0] == "True")
{
value = common.Parameters[i][2];
value ??= string.Empty;
segments = value.Split('/');
parameter = segments[^1];
_ = result.Append(parameter).Append("\tDIVERSE\tEXACT\t*\t").Append(parameter).AppendLine("\t\tNUMERIC\tRUN\t\t\t\tPHARES\t9000000012\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
}
}
return result.ToString();
}
internal static string GetEdaObjectToAPCRunKeyNumber(string edaObjectFile, Common common)
{
StringBuilder result = new();
if (string.IsNullOrEmpty(edaObjectFile))
{ }
string? value;
string parameter;
string[] segments;
string parameterSub21;
string parameterSub35;
_ = result.AppendLine("ExportFileVersion=1.0.6");
_ = result.AppendLine("ExportFromTabsheet=Run-Keynumbers");
_ = result.AppendLine("FeatureName\tShortName\tChamber\tComments\tVarMode\tPara\tExclude0\tTrigOn1\tTrigOn2\tTrigOn3\tTrigOff1\tTrigOff2\tTrigOff3\tTrigDelay\tTrigNorm\tTrigNvl\tTrigTrg\tAddCondOn\tActive\tFilter1\tFilter2\tFilter3\tFilter4\tUnit\tId\tWorkcenterId\tSite\tArea\tWorkcenter\tUsername\tValidFrom\tValidTo");
for (int i = 0; i < common.Parameters.Count; i++)
{
if (common.Parameters[i][0] == "True")
{
value = common.Parameters[i][2];
value ??= string.Empty;
segments = value.Split('/');
parameter = segments[^1];
if (parameter.Length < 35)
parameterSub35 = parameter;
else
parameterSub35 = parameter[..35];
if (parameter.Length < 21)
parameterSub21 = parameter;
else
parameterSub21 = parameter[..21];
_ = result.Append(parameterSub21).Append("_MIN\t").Append(parameterSub21).Append("_MIN\t\t\tMIN\t").Append(parameterSub35).AppendLine("\t0\tTIME\t=\tRUNSTART\tTIME\t=\tRUNEND\t\t\t\t\t\t1\t\t\t\t\t\t-1\t-1\t\t\t\tECPHARES\t5/2/2017 2:44 PM");
}
}
_ = result.AppendLine();
_ = result.AppendLine();
_ = result.AppendLine();
for (int i = 0; i < common.Parameters.Count; i++)
{
if (common.Parameters[i][0] == "True")
{
value = common.Parameters[i][2];
value ??= string.Empty;
segments = value.Split('/');
parameter = segments[^1];
_ = result.Append(parameter).Append("_MIN\t").Append(parameter).Append("_MIN\t\t\tMIN\t").Append(parameter).AppendLine("\t0\tTIME\t=\tRUNSTART\tTIME\t=\tRUNEND\t\t\t\t\t\t1\t\t\t\t\t\t-1\t-1\t\t\t\tECPHARES\t5/2/2017 2:44 PM");
}
}
return result.ToString();
}
}

2502
Helpers/EDA/EDA - A.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,6 @@
namespace File_Watcher.Helpers.EDA;
public enum ModuleInstanceTypeName
{
Pdsf
}

123
Helpers/HelperCompass.cs Normal file
View File

@ -0,0 +1,123 @@
using File_Watcher.Models;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
namespace File_Watcher.Helpers;
internal class HelperCompass
{
private static bool _FirstRun = true;
private static void MapDrives(AppSettings appSettings, ILogger<Worker> logger)
{
Process? process;
string arguments;
string decrypted;
string? pathRoot;
string[] segments;
string standardError;
string standardOutput;
string fileName = "net";
StringBuilder stringBuilder = new();
if (appSettings.DriveConfiguration.Use is not null && appSettings.DriveConfiguration.Use.Value)
{
pathRoot = Path.GetPathRoot(appSettings.DriveConfiguration.Share);
if (!string.IsNullOrEmpty(pathRoot) && !Directory.Exists(pathRoot))
{
if (string.IsNullOrEmpty(appSettings.DriveConfiguration.Password))
decrypted = string.Empty;
else
decrypted = RijndaelEncryption.Decrypt(appSettings.DriveConfiguration.Password, appSettings.Company);
arguments = $"use {appSettings.DriveConfiguration.Letter}: \"{appSettings.DriveConfiguration.Share}\" /p:yes /user:{appSettings.DriveConfiguration.User} {decrypted}";
_ = stringBuilder.Clear();
segments = arguments.Split(' ');
for (int j = 0; j < segments.Length - 1; j++)
_ = stringBuilder.Append(segments[j]).Append(' ');
logger.LogInformation("// {output}", stringBuilder);
ProcessStartInfo processStartInfo = new(fileName, arguments)
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
};
try
{
process = Process.Start(processStartInfo);
if (process is not null)
{
for (int j = 1; j < 45; j++)
{
_ = process.WaitForExit(1000);
if (process.HasExited)
break;
}
if (!process.HasExited)
logger.LogError("// Never exited!");
else
{
standardError = process.StandardError.ReadToEnd();
standardOutput = process.StandardOutput.ReadToEnd();
logger.LogInformation("// {error}{line}{line}// {output}", standardError, Environment.NewLine, Environment.NewLine, standardOutput);
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error:");
}
}
}
}
private static ReadOnlyCollection<string> GetFiles(AppSettings appSettings, string directory)
{
ReadOnlyCollection<string> results;
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
results = new(Directory.GetFiles(directory, appSettings.CompassConfiguration.Pattern, SearchOption.TopDirectoryOnly));
return results;
}
private static void CopyFiles(AppSettings appSettings, ReadOnlyCollection<string> files)
{
string checkFile;
string triggerFile;
foreach (string file in files)
{
checkFile = Path.Combine(appSettings.CompassConfiguration.Destination, Path.GetFileName(file));
triggerFile = $"{checkFile}{appSettings.CompassConfiguration.TriggerAppendage}";
if (File.Exists(checkFile))
continue;
if (File.Exists(triggerFile))
continue;
File.Copy(file, checkFile);
File.WriteAllText(triggerFile, string.Empty);
}
}
internal static bool CopyFile(AppSettings appSettings, ILogger<Worker> logger)
{
if (_FirstRun)
{
_FirstRun = false;
MapDrives(appSettings, logger);
logger.LogCritical("MapDrives Done");
}
string directory;
ReadOnlyCollection<string> files;
DateTime[] dateTimes = [DateTime.Now, DateTime.Now.AddHours(-appSettings.CompassConfiguration.HoursBack)];
foreach (DateTime dateTime in dateTimes)
{
directory = Path.Combine(appSettings.CompassConfiguration.Source, dateTime.ToString(appSettings.CompassConfiguration.YearPattern), dateTime.ToString(appSettings.CompassConfiguration.MonthPattern));
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
files = GetFiles(appSettings, directory);
logger.LogDebug("Found {Files} file(s)", files.Count);
CopyFiles(appSettings, files);
}
return true;
}
}

View File

@ -0,0 +1,37 @@
using File_Watcher.Models;
namespace File_Watcher.Helpers;
internal static partial class HelperEAFProgramData
{
internal static bool MoveFiles(AppSettings appSettings, ILogger<Worker> logger)
{
string checkFile;
string checkDirectory;
string source = Path.GetFullPath(appSettings.EAFProgramDataConfiguration.Source);
string[] files = Directory.GetFiles(source, "*", SearchOption.AllDirectories);
logger.LogInformation("After {MillisecondsDelay} with search pattern '{SearchPattern}' found {files}", appSettings.MillisecondsDelay, appSettings.EAFLogConfiguration.SearchPattern, files.Length);
foreach (string file in files)
{
Thread.Sleep(500);
checkFile = file.Replace(source, appSettings.EAFProgramDataConfiguration.Destination);
if (checkFile == file)
throw new NotSupportedException("Replace failed!");
checkDirectory = Path.GetDirectoryName(checkFile) ?? throw new NotSupportedException();
try
{
if (!Directory.Exists(checkDirectory))
_ = Directory.CreateDirectory(checkDirectory);
if (File.Exists(checkFile))
continue;
File.Move(file, checkFile);
Thread.Sleep(500);
}
catch (Exception ex)
{ logger.LogInformation(ex, "Inner loop error!"); }
}
return true;
}
}

View File

@ -0,0 +1,286 @@
using File_Watcher.Helpers.EDA;
using File_Watcher.Models;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
namespace File_Watcher.Helpers;
internal static partial class HelperEDADatabase
{
private static Calendar? _Calendar;
private static string? _EDADataCollectionPlansLastRun;
[GeneratedRegex("[a-zA-Z0-9]{1,}")]
private static partial Regex RegexAZ09();
private static Stream ToStream(string @this)
{
MemoryStream? stream = new();
StreamWriter? writer = new(stream);
writer.Write(@this);
writer.Flush();
stream.Position = 0;
return stream;
}
private static T? ParseXML<T>(string @this, bool throwExceptions) where T : class
{
object? result = null;
try
{
Stream stream = ToStream(@this.Trim());
XmlReader? reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
#pragma warning disable IL2026, IL2090
XmlSerializer xmlSerializer = new(typeof(T), typeof(T).GetNestedTypes());
result = xmlSerializer.Deserialize(reader);
#pragma warning restore IL2026, IL2090
stream.Dispose();
}
catch (Exception)
{
if (throwExceptions)
throw;
}
return result as T;
}
private static void EvaluateRows(string workingDirectory, Dictionary<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> rows, CancellationToken cancellationToken)
{ // cSpell:disable
// int moduleinstancetypename = 0;
int unitname = 1;
// int modulename = 2;
int containername = 3;
int configurationstate = 4;
int configurationproductivestate = 5;
// int containermodifiername = 6;
int containermodifieddate = 7;
int containerconfiguration = 8;
int configurationmodifieddate = 9;
// cSpell:enable
string csv;
string? xml;
string json;
string text;
string html;
Common common;
string emptyAPC;
string fileName;
string? modifiedDate;
string edaObjectFile;
string goldDirectory;
string replace = "$$$";
string edaObjectDirectory;
DateTime lastModifiedDate;
string objectTypeDirectory;
DateTime containerModifiedDate;
PDSFConfiguration? configuration;
DateTime configurationModifiedDate;
JsonSerializerOptions jsonSerializerOptions = new() { WriteIndented = true };
foreach (KeyValuePair<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> databaseElement in rows)
{
if (cancellationToken.IsCancellationRequested)
break;
emptyAPC = string.Concat(workingDirectory, @"\", databaseElement.Key, @"\EmptyAPC.xlsx");
foreach (KeyValuePair<ModuleInstanceTypeName, List<List<object>>> tableNameElement in databaseElement.Value)
{
if (cancellationToken.IsCancellationRequested)
break;
objectTypeDirectory = string.Concat(workingDirectory, @"\", databaseElement.Key, @"\", tableNameElement.Key);
foreach (List<object> rowItem in tableNameElement.Value)
{ // cSpell:disable
if (cancellationToken.IsCancellationRequested)
break;
// foreach (var item in rowItem)
// Print(item.ToString());
// if (!rowItem[containername].ToString().Contains("Plan_Pdsf_Health_Cp2Mg"))
// if (!rowItem[unitname].ToString().Contains("HGCV1") || !rowItem[containername].ToString().Contains("Plan_Pdsf"))
// continue;
modifiedDate = rowItem[containermodifieddate].ToString();
if (string.IsNullOrEmpty(modifiedDate))
continue;
containerModifiedDate = DateTime.Parse(modifiedDate);
modifiedDate = rowItem[configurationmodifieddate].ToString();
if (string.IsNullOrEmpty(modifiedDate))
continue;
configurationModifiedDate = DateTime.Parse(modifiedDate);
if (containerModifiedDate < configurationModifiedDate)
lastModifiedDate = configurationModifiedDate;
else
lastModifiedDate = containerModifiedDate;
goldDirectory = string.Concat(objectTypeDirectory, @"\", rowItem[unitname], @"\", rowItem[containername], @"\Gold");
if (!Directory.Exists(goldDirectory))
_ = Directory.CreateDirectory(goldDirectory);
edaObjectDirectory = string.Concat(objectTypeDirectory, @"\", rowItem[unitname], @"\", rowItem[containername], @"\", rowItem[configurationstate], @"\", rowItem[configurationproductivestate], @"\", lastModifiedDate.ToString("yyyy-MM-dd_"), new TimeSpan(lastModifiedDate.Ticks - new DateTime(lastModifiedDate.Year, lastModifiedDate.Month, lastModifiedDate.Day).Ticks).TotalSeconds);
if (!Directory.Exists(edaObjectDirectory))
_ = Directory.CreateDirectory(edaObjectDirectory);
edaObjectFile = string.Concat(edaObjectDirectory, @"\", rowItem[unitname], " ", rowItem[containername], " - ", replace, " - ", rowItem[configurationstate].ToString(), " ", rowItem[configurationproductivestate].ToString());
xml = rowItem[containerconfiguration].ToString();
if (string.IsNullOrEmpty(xml))
continue;
fileName = string.Concat(edaObjectFile.Replace(replace, "Raw"), ".xml");
File.WriteAllText(fileName, xml);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
common = new Common(ModuleInstanceTypeName.Pdsf, rowItem[unitname], rowItem[containername], rowItem[configurationstate], rowItem[configurationproductivestate]);
configuration = ParseXML<PDSFConfiguration>(xml, throwExceptions: true);
if (configuration is null)
continue;
// cSpell:enable
common.Update(configuration);
#pragma warning disable IL2026, IL3050
json = JsonSerializer.Serialize(configuration, configuration.GetType(), jsonSerializerOptions);
#pragma warning restore IL2026, IL3050
if (common?.UnitName is null)
continue;
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".csv");
File.WriteAllText(fileName, common.ParametersAsCsv);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".json");
File.WriteAllText(fileName, json);
text = DCP.GetText(edaObjectFile, common, json);
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".txt");
File.WriteAllText(fileName, text);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
html = DCP.GetEdaObjectToHtml(edaObjectFile, common);
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".html");
File.WriteAllText(fileName, html);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
xml = DCP.GetEdaObjectToDMSGridFormat(edaObjectFile, common, useAlias: false);
fileName = string.Concat(edaObjectFile.Replace(replace, "DMSGridFormat"), ".xml");
File.WriteAllText(fileName, xml);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
xml = DCP.GetEdaObjectToDMSGridFormat(edaObjectFile, common, useAlias: true);
fileName = string.Concat(edaObjectFile.Replace(replace, "DMSGridFormat - Alias"), ".xml");
File.WriteAllText(fileName, xml);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
csv = DCP.GetEdaObjectToAPCParameter(edaObjectFile, common);
fileName = string.Concat(edaObjectFile.Replace(replace, "APCParameter"), ".csv");
File.WriteAllText(fileName, csv);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
csv = DCP.GetEdaObjectToAPCRunKeyNumber(edaObjectFile, common);
fileName = string.Concat(edaObjectFile.Replace(replace, "APCRunKeyNumber"), ".csv");
File.WriteAllText(fileName, csv);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
fileName = string.Concat(edaObjectFile.Replace(replace, "APC"), ".xlsx");
if (File.Exists(emptyAPC) && !File.Exists(fileName))
{
File.Copy(emptyAPC, fileName);
try
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
catch (Exception) { }
}
if (common.StoragePaths.Length == 0)
continue;
foreach (string? storagePath in common.StoragePaths)
{
if (string.IsNullOrEmpty(storagePath) || !Directory.Exists(Path.GetPathRoot(storagePath)))
continue;
if (Directory.Exists(storagePath))
continue;
_ = Directory.CreateDirectory(storagePath);
}
}
try
{ Directory.SetLastWriteTime(objectTypeDirectory, DateTime.Now); }
catch (Exception) { }
}
}
}
private static void DataCollectionPlans(AppSettings appSettings, ILogger<Worker> logger, Calendar calendar, CancellationToken cancellationToken)
{
int fieldCount;
object @object;
string? @string;
List<object> row;
StringBuilder sql = new();
string objectTypeDirectory;
#pragma warning disable IL3050
Array objectTypes = Enum.GetValues(typeof(ModuleInstanceTypeName));
#pragma warning restore IL3050
Dictionary<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> rows = [];
string decrypted = RijndaelEncryption.Decrypt(appSettings.EDADatabaseConfiguration.Password, appSettings.Company);
string connectionString = $"Data Source={appSettings.EDADatabaseConfiguration.TNS}; User Id={appSettings.EDADatabaseConfiguration.UserName}; Password={decrypted};";
rows.Add(appSettings.EDADatabaseConfiguration.Name, []);
foreach (ModuleInstanceTypeName objectType in objectTypes)
{
if (cancellationToken.IsCancellationRequested)
break;
if (string.IsNullOrEmpty(_EDADataCollectionPlansLastRun))
{
objectTypeDirectory = Path.Combine(appSettings.EDADatabaseConfiguration.FileShare, appSettings.EDADatabaseConfiguration.Name, objectType.ToString());
if (!Directory.Exists(objectTypeDirectory))
_ = Directory.CreateDirectory(objectTypeDirectory);
else
_EDADataCollectionPlansLastRun = new DirectoryInfo(objectTypeDirectory).LastWriteTime.ToString(appSettings.EDADatabaseConfiguration.CSharpDateTimeFormat);
}
if (!rows[appSettings.EDADatabaseConfiguration.Name].ContainsKey(objectType))
rows[appSettings.EDADatabaseConfiguration.Name].Add(objectType, []);
using (Oracle.ManagedDataAccess.Client.OracleConnection oracleConnection = new(connectionString))
{
_ = sql.Clear();
oracleConnection.Open(); // cSpell:disable
_ = sql.Append(" select v.moduleinstancetypename, v.unitname, ").
Append(" v.modulename, v.containername, v.configurationstate, ").
Append(" v.configurationproductivestate, v.containermodifiername, ").
Append(" v.containermodifieddate, v.containerconfiguration, v.configurationmodifieddate ").
Append(" from veditconfiguration v ").
Append(" where v.moduleinstancetypename = '").Append(objectType.ToString()).Append("' ");
// Append(" and v.containerversion in ('4.80', '4.111') ");
if (!string.IsNullOrEmpty(_EDADataCollectionPlansLastRun))
_ = sql.Append(" and greatest(v.containermodifieddate, v.configurationmodifieddate) >= to_date('").Append(_EDADataCollectionPlansLastRun).Append("', '").Append(appSettings.EDADatabaseConfiguration.OracleDateTimeFormat).Append("') ");
logger.LogDebug(sql.ToString());
using Oracle.ManagedDataAccess.Client.OracleCommand oracleCommand = new(sql.ToString(), oracleConnection); // cSpell:enable
using Oracle.ManagedDataAccess.Client.OracleDataReader oracleDataReader = oracleCommand.ExecuteReader();
fieldCount = oracleDataReader.FieldCount;
while (oracleDataReader.Read())
{
if (cancellationToken.IsCancellationRequested)
break;
row = [];
for (int c = 0; c < fieldCount; c++)
{
@object = oracleDataReader.GetValue(c);
row.Add(@object);
if (@object is null)
continue;
@string = @object.ToString();
// if (@string.Length < 128)
// _Logger.LogDebug(@string);
}
rows[appSettings.EDADatabaseConfiguration.Name][objectType].Add(row);
}
};
}
if (rows.Count != 0)
EvaluateRows(appSettings.EDADatabaseConfiguration.FileShare, rows, cancellationToken);
}
internal static bool SaveDataCollectionPlans(AppSettings appSettings, ILogger<Worker> logger, CancellationToken cancellationToken)
{
_Calendar ??= new CultureInfo("en-US").Calendar;
DataCollectionPlans(appSettings, logger, _Calendar, cancellationToken);
return true;
}
}

View File

@ -0,0 +1,27 @@
using File_Watcher.Models;
using System.Diagnostics;
namespace File_Watcher.Helpers;
internal static partial class HelperInfinityQS
{
internal static bool RunMI(AppSettings appSettings, ILogger<Worker> logger)
{
#pragma warning disable CA1416
logger.LogInformation(appSettings.Company);
ProcessStartInfo processStartInfo = new("iispcmi.exe")
{
Domain = "Infineon",
UseShellExecute = false,
UserName = "ecfisysadmin",
PasswordInClearText = "j(1(P%xB=g}3w9db",
WorkingDirectory = "C:/Program Files (x86)/InfinityQS International/ProFicient/Applications"
};
Process process = Process.Start(processStartInfo) ?? throw new NullReferenceException(nameof(Process));
process.WaitForExit();
#pragma warning restore CA1416
return true;
}
}

View File

@ -62,7 +62,7 @@ internal static partial class HelperMetrologyFiles
} }
} }
private static void Delete(MetrologyConfiguration metrologyConfiguration, ILogger<Worker> logger, Calendar calendar) private static void Delete(MetrologyConfiguration metrologyConfiguration, ILogger<Worker> logger)
{ {
string directory; string directory;
DateTime dateTime; DateTime dateTime;
@ -102,7 +102,7 @@ internal static partial class HelperMetrologyFiles
CultureInfo cultureInfo = new("en-US"); CultureInfo cultureInfo = new("en-US");
Calendar calendar = cultureInfo.Calendar; Calendar calendar = cultureInfo.Calendar;
Sort(appSettings.MetrologyConfiguration, logger, calendar); Sort(appSettings.MetrologyConfiguration, logger, calendar);
Delete(appSettings.MetrologyConfiguration, logger, calendar); Delete(appSettings.MetrologyConfiguration, logger);
return true; return true;
} }

153
Helpers/HelperNuget.cs Normal file
View File

@ -0,0 +1,153 @@
using File_Watcher.Models;
using System.IO.Compression;
namespace File_Watcher.Helpers;
internal class HelperNuget
{
private static DateTimeOffset? GetDateTimeOffset(string keyFileExtension, FileInfo fileInfo, FileInfo extractKeyFileInfo)
{
DateTimeOffset? dateTimeOffset = null;
using ZipArchive zip = ZipFile.Open(fileInfo.FullName, ZipArchiveMode.Read);
foreach (ZipArchiveEntry zipArchiveEntry in zip.Entries)
{
if (!zipArchiveEntry.Name.EndsWith(keyFileExtension))
continue;
dateTimeOffset = zipArchiveEntry.LastWriteTime;
if (fileInfo.FullName[0] != '\\')
{
zipArchiveEntry.ExtractToFile(extractKeyFileInfo.FullName);
File.SetCreationTime(extractKeyFileInfo.FullName, fileInfo.CreationTime);
File.SetLastWriteTime(extractKeyFileInfo.FullName, dateTimeOffset.Value.LocalDateTime);
}
break;
}
return dateTimeOffset;
}
private static void SetLastWriteTimes(ILogger<Worker> logger, NugetConfiguration nugetConfiguration, FileInfo fileInfo, DateTimeOffset dateTimeOffset)
{
try
{
string[] files;
if (fileInfo.LastWriteTime != dateTimeOffset.LocalDateTime)
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.LocalDateTime);
if (!string.IsNullOrEmpty(nugetConfiguration.KeyFileExtensionB))
{
if (fileInfo.DirectoryName is null)
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
files = Directory.GetFiles(fileInfo.DirectoryName, nugetConfiguration.KeyFileExtensionB, SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
fileInfo = new(file);
if (fileInfo.LastWriteTime != dateTimeOffset.LocalDateTime)
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.LocalDateTime);
}
}
if (!string.IsNullOrEmpty(nugetConfiguration.KeyFileExtensionC))
{
if (fileInfo.DirectoryName is null)
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
files = Directory.GetFiles(fileInfo.DirectoryName, nugetConfiguration.KeyFileExtensionC, SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
fileInfo = new(file);
if (fileInfo.LastWriteTime != dateTimeOffset.LocalDateTime)
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.LocalDateTime);
}
}
}
catch (Exception)
{
string checkFile;
logger.LogInformation("<{fileInfo.FullName}> is invalid!", fileInfo.FullName);
checkFile = string.Concat(fileInfo.FullName, ".err");
for (int e = 0; e < short.MaxValue; e++)
{
if (!File.Exists(checkFile))
break;
checkFile = string.Concat(checkFile, e);
}
try
{ File.Move(fileInfo.FullName, checkFile); }
catch (Exception) { logger.LogInformation("<{fileInfo.FullName}> couldn't be moved!", fileInfo.FullName); }
}
}
private static void ExtractKeyFileAndSetDateFromZipEntry(ILogger<Worker> logger, NugetConfiguration nugetConfiguration, string[] zipFiles)
{
string[] files;
FileInfo fileInfo;
string? lowerName;
FileInfo extractKeyFileInfo;
foreach (string zipFile in zipFiles)
{
fileInfo = new(zipFile);
if (fileInfo.DirectoryName is null)
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
lowerName = !nugetConfiguration.RenameToLower ? null : Path.Combine(fileInfo.DirectoryName, fileInfo.Name.ToLower());
if (nugetConfiguration.RenameToLower && lowerName is not null && lowerName != fileInfo.FullName)
{
files = Directory.GetFiles(fileInfo.DirectoryName, $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}*", SearchOption.TopDirectoryOnly);
foreach (string file in files)
File.Move(file, Path.Combine(fileInfo.DirectoryName, Path.GetFileName(file).ToLower()));
fileInfo = new(lowerName);
if (fileInfo.DirectoryName is null)
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
}
extractKeyFileInfo = new(Path.Combine(fileInfo.DirectoryName, $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}{nugetConfiguration.KeyFileExtension}"));
if (extractKeyFileInfo.Exists)
{
if (extractKeyFileInfo.CreationTime.ToString("yyyy-MM-dd") == fileInfo.CreationTime.ToString("yyyy-MM-dd") && extractKeyFileInfo.LastWriteTime.ToString("yyyy-MM-dd") == fileInfo.LastWriteTime.ToString("yyyy-MM-dd"))
continue;
File.Delete(extractKeyFileInfo.FullName);
}
DateTimeOffset? dateTimeOffset = GetDateTimeOffset(nugetConfiguration.KeyFileExtension, fileInfo, extractKeyFileInfo);
if (dateTimeOffset is null)
continue;
SetLastWriteTimes(logger, nugetConfiguration, fileInfo, dateTimeOffset.Value);
}
}
private static int CopyFiles(NugetConfiguration nugetConfiguration, string[] files)
{
int results = 0;
FileInfo fileInfo;
FileInfo checkFileInfo;
foreach (string file in files)
{
fileInfo = new(file);
checkFileInfo = new(Path.Combine(nugetConfiguration.Destination, fileInfo.Name));
if (!checkFileInfo.Exists || fileInfo.LastWriteTime != checkFileInfo.LastWriteTime || fileInfo.Length != checkFileInfo.Length)
{
File.Copy(fileInfo.FullName, checkFileInfo.FullName, overwrite: true);
results++;
}
if (string.IsNullOrEmpty(nugetConfiguration.KeyFileExtension))
continue;
fileInfo = new(Path.ChangeExtension(file, nugetConfiguration.KeyFileExtension));
checkFileInfo = new(Path.Combine(nugetConfiguration.Destination, Path.ChangeExtension(fileInfo.Name, nugetConfiguration.KeyFileExtension)));
if (!checkFileInfo.Exists || fileInfo.LastWriteTime != checkFileInfo.LastWriteTime || fileInfo.Length != checkFileInfo.Length)
File.Copy(fileInfo.FullName, checkFileInfo.FullName, overwrite: true);
}
return results;
}
internal static bool Sync(AppSettings appSettings, ILogger<Worker> logger)
{
NugetConfiguration nugetConfiguration = appSettings.NugetConfiguration;
if (!Directory.Exists(nugetConfiguration.Source))
_ = Directory.CreateDirectory(nugetConfiguration.Source);
if (!Directory.Exists(nugetConfiguration.Destination))
_ = Directory.CreateDirectory(nugetConfiguration.Destination);
string[] files = Directory.GetFiles(nugetConfiguration.Source, nugetConfiguration.SearchPattern, SearchOption.AllDirectories);
logger.LogInformation("Found {Files} file(s)", files.Length);
ExtractKeyFileAndSetDateFromZipEntry(logger, nugetConfiguration, files);
logger.LogInformation("{Files} file(s) verified", files.Length);
int filesCopied = CopyFiles(nugetConfiguration, files);
logger.LogInformation("Copied {FilesCopied} file(s)", filesCopied);
return true;
}
}

281
Helpers/HelperSerial.cs Normal file
View File

@ -0,0 +1,281 @@
using File_Watcher.Models;
using System.Diagnostics;
using System.IO.Ports;
namespace File_Watcher.Helpers;
internal static partial class HelperSerial
{
private record Record(List<byte> Data,
string Destination,
ILogger<Worker> Logger,
CancellationToken CancellationToken);
private static Record? _Record;
private static SerialPort? _SerialPort;
private static void PCLToPDF(string fullPath)
{
string ghostPCLFileName = Path.Combine(AppContext.BaseDirectory, "gpcl6win64.exe");
if (!File.Exists(ghostPCLFileName))
throw new Exception("Ghost PCL FileName doesn't Exist!");
string lincPDFCFileName = Path.Combine(AppContext.BaseDirectory, "LincPDFC.exe");
if (!File.Exists(lincPDFCFileName))
throw new Exception("Linc PDFC FileName doesn't Exist!");
string pdfFile;
string fileName;
string arguments;
for (int i = 1; i < 3; i++)
{
if (i == 1)
{
fileName = ghostPCLFileName;
pdfFile = $"{fullPath}-ghost.pdf";
arguments = $"-dSAFER -dBATCH -dNOPAUSE -sOutputFile=\"{pdfFile}\" -sDEVICE=pdfwrite \"{fullPath}\"";
// arguments = $"-dSAFER -dBATCH -dNOPAUSE -dFIXEDMEDIA -dFitPage -dAutoRotatePages=/All -dDEVICEWIDTHPOINTS=792 -dDEVICEHEIGHTPOINTS=612 -sOutputFile=\"{pdfFile}\" -sDEVICE=pdfwrite \"{fullPath}\"";
}
else if (i == 2)
{
fileName = lincPDFCFileName;
pdfFile = $"{fullPath}-linc.pdf";
arguments = $"-i \"{fullPath}\" -o \"{pdfFile}\"";
}
else
throw new Exception();
Process process = Process.Start(fileName, arguments);
long breakAfter = DateTime.Now.AddSeconds(30).Ticks;
for (short j = 0; j < short.MaxValue; j++)
{
if (process.HasExited || process.WaitForExit(500) || DateTime.Now.Ticks > breakAfter)
break;
}
if (!File.Exists(pdfFile))
throw new Exception("PDF file wasn't created");
}
}
private static List<byte> GetBytes(List<byte> bytes)
{
List<byte> results = [];
foreach (byte @byte in bytes)
results.Add(@byte);
return results;
}
private static void SerialPortWrite(string destination, DateTime dateTime, List<byte> bytes, string v, bool convert)
{
if (_SerialPort is null)
throw new NullReferenceException(nameof(_SerialPort));
string directory = Path.Combine(destination, _SerialPort.PortName);
if (!Directory.Exists(destination))
_ = Directory.CreateDirectory(destination);
string fileName = Path.Combine(directory, $"{_SerialPort.PortName}-{v}-{dateTime:yyyyMMddHHmmssfff}.pcl");
File.WriteAllBytes(fileName, bytes.ToArray());
if (convert)
PCLToPDF(fileName);
}
private static int? SearchBytes(byte[] haystack, byte[] needle)
{
int? result = null;
int k;
int len = needle.Length;
int limit = haystack.Length - len;
for (int i = 0; i <= limit; i++)
{
k = 0;
for (; k < len; k++)
{
if (needle[k] != haystack[i + k])
break;
}
if (k == len)
{
result = i;
break;
}
}
return result;
}
private static bool Contains()
{
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
bool result;
// char endOfLine = '\u001b';
// lock (_Record)
// result = _Record.Data.Contains(Convert.ToByte(endOfLine));
// if (!result)
// {
// }
int? index = null;
// byte[] pageDelimiter =
// {
// Convert.ToByte(27),
// Convert.ToByte(69)
// };
lock (_Record)
{
byte[] bytes = _Record.Data.ToArray();
// index = Array.IndexOf(bytes, pageDelimiter);
// if (index == -1)
// {
// }
byte[] documentDelimiter =
[
Convert.ToByte(32),
Convert.ToByte(83),
Convert.ToByte(116),
Convert.ToByte(97),
Convert.ToByte(116),
Convert.ToByte(105),
Convert.ToByte(115),
Convert.ToByte(116),
Convert.ToByte(105),
Convert.ToByte(99),
Convert.ToByte(115),
Convert.ToByte(58)
];
index = SearchBytes(bytes, documentDelimiter);
}
result = index is not null;
return result;
}
private static void PinChanged(object sender, SerialPinChangedEventArgs serialPinChangedEventArgs)
{
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
try
{ _Record.Logger.LogDebug($"EventType = {serialPinChangedEventArgs.EventType}"); }
catch (Exception exception) { _Record.Logger.LogError(exception, "Error"); }
}
private static void DataReceived(object? sender, SerialDataReceivedEventArgs dataReceivedEventArgs)
{
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
if (_SerialPort is null)
throw new NullReferenceException(nameof(_SerialPort));
DateTime dateTime = DateTime.Now;
try
{
_Record.Logger.LogDebug($"EventType = {dataReceivedEventArgs.EventType}");
List<byte>? bytes;
lock (_Record)
{
byte[] buffer = new byte[_SerialPort.BytesToRead];
int count = _SerialPort.Read(buffer, 0, buffer.Length);
if (count == 0)
bytes = null;
else
{
_Record.Data.AddRange(buffer.Take(count));
bytes = dataReceivedEventArgs.EventType != SerialData.Eof ? null : GetBytes(_Record.Data);
}
}
if (bytes is not null)
SerialPortWrite(_Record.Destination, dateTime, bytes, nameof(SerialData.Eof), convert: false);
}
catch (Exception exception)
{
string fileName = Path.Combine(_Record.Destination, _SerialPort.PortName, $"{dateTime:yyyyMMddHHmmssfff}.err");
File.WriteAllLines(fileName, [exception.Message, Environment.NewLine, Environment.NewLine, string.Concat(exception.StackTrace)]);
}
}
private static void ErrorReceived(object sender, SerialErrorReceivedEventArgs serialErrorReceivedEventArgs)
{
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
try
{ _Record.Logger.LogDebug($"EventType = {serialErrorReceivedEventArgs.EventType}"); }
catch (Exception exception) { _Record.Logger.LogError(exception, "Error"); }
}
private static void SerialPortWriteConditionally(SerialConfiguration serialConfiguration, ILogger<Worker> logger)
{
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
DateTime dateTime = DateTime.Now;
logger.LogDebug($"Worker:Process:SerialPort running at: {dateTime} serial port {serialConfiguration.PortName} status with Length = {_Record.Data.Count}.");
bool contains = Contains();
if (contains)
{
List<byte> bytes;
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
lock (_Record)
{
bytes = GetBytes(_Record.Data);
_Record.Data.Clear();
}
SerialPortWrite(_Record.Destination, dateTime, bytes, nameof(Contains), convert: true);
}
}
private static void SerialPortClose()
{
if (_SerialPort is not null)
{
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
lock (_Record)
{
_SerialPort.Close();
int length = _Record is null ? 0 : _Record.Data.Count;
if (_Record is null)
throw new NullReferenceException(nameof(_Record));
_Record.Logger.LogDebug($"Serial port {_SerialPort.PortName} closed with Length = {length}.");
}
}
}
internal static bool ReadWrite(AppSettings appSettings, ILogger<Worker> logger, CancellationToken cancellationToken)
{
_Record ??= new([], appSettings.SerialConfiguration.Destination, logger, cancellationToken);
if (_SerialPort is null)
{
string ghostPCLFileName = Path.Combine(AppContext.BaseDirectory, appSettings.SerialConfiguration.GhostPCLFileName);
if (!File.Exists(ghostPCLFileName))
throw new Exception("Ghost PCL FileName doesn't Exist!");
string lincPDFCFileName = Path.Combine(AppContext.BaseDirectory, appSettings.SerialConfiguration.LincPDFCFileName);
if (!File.Exists(lincPDFCFileName))
throw new Exception("Linc PDFC FileName doesn't Exist!");
_SerialPort = new SerialPort
{
PortName = appSettings.SerialConfiguration.PortName,
// BaudRate = 9600,
BaudRate = 115200,
DataBits = 8,
Parity = Parity.None,
StopBits = StopBits.One,
// Handshake = Handshake.None,
Handshake = Handshake.RequestToSend,
// DtrEnable = true,
// RtsEnable = true,
ReadTimeout = 5000
};
string[] portNames = SerialPort.GetPortNames();
string[] matchPortNames = (from l in portNames where l == appSettings.SerialConfiguration.PortName select l).ToArray();
if (matchPortNames.Length == 0)
throw new Exception($"Didn't find matching COM port! {string.Join(Environment.NewLine, portNames)}");
if (matchPortNames.Length != 1)
throw new Exception($"Matching count is more than one! {string.Join(Environment.NewLine, portNames)}");
_SerialPort.Open();
_SerialPort.DiscardInBuffer();
_SerialPort.DiscardOutBuffer();
logger.LogDebug("Waiting for data.");
_SerialPort.PinChanged += PinChanged;
_SerialPort.DataReceived += DataReceived;
_SerialPort.ErrorReceived += ErrorReceived;
}
SerialPortWriteConditionally(appSettings.SerialConfiguration, logger);
if (cancellationToken.IsCancellationRequested)
SerialPortClose();
return true;
}
}

157
Helpers/HelperTCP.cs Normal file
View File

@ -0,0 +1,157 @@
using File_Watcher.Models;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
namespace File_Watcher.Helpers;
internal static partial class HelperTCP
{
private record Record(BinaryReader BinaryReader,
BinaryWriter BinaryWriter,
NetworkStream NetworkStream);
private static long _LastWrite;
private static Record? _Record;
private static TcpListener? _TcpListener;
private static readonly object _Lock = new();
private static void OnAccept(IAsyncResult asyncResult)
{
if (_TcpListener is null)
throw new NullReferenceException(nameof(_TcpListener));
lock (_Lock)
{
TcpClient tcpClient = _TcpListener.EndAcceptTcpClient(asyncResult);
NetworkStream networkStream = tcpClient.GetStream();
_Record = new(new(networkStream), new(networkStream), networkStream);
}
}
private static string ConvertSourceFileToPdf(string ghostPCLFileName, string reportFullPath)
{
string result = Path.ChangeExtension(reportFullPath, ".pdf");
if (!File.Exists(result))
{
//string arguments = string.Concat("-i \"", sourceFile, "\" -o \"", result, "\"");
string arguments = string.Concat("-dSAFER -dBATCH -dNOPAUSE -sOutputFile=\"", result, "\" -sDEVICE=pdfwrite \"", reportFullPath, "\"");
//Process process = Process.Start(configData.LincPDFCFileName, arguments);
Process process = Process.Start(ghostPCLFileName, arguments);
_ = process.WaitForExit(30000);
if (!File.Exists(result))
throw new Exception("PDF file wasn't created");
}
return result;
}
private static void BeginAcceptTcpClient()
{
if (_TcpListener is null)
throw new NullReferenceException(nameof(_TcpListener));
_ = _TcpListener.BeginAcceptTcpClient(OnAccept, null);
}
private static void ReadFiles(TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration)
{
List<byte> bytes = [];
// byte nullByte = Convert.ToByte('\0');
string[] files = Directory.GetFiles(transmissionControlProtocolConfiguration.Destination, $"{transmissionControlProtocolConfiguration.IPAddress}-*.raw", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
foreach (byte @byte in File.ReadAllBytes(file))
{
// if (@byte.Equals(nullByte))
// continue;
bytes.Add(@byte);
}
}
if (bytes.Count > 0)
{
string bytesFile = Path.Combine(transmissionControlProtocolConfiguration.Destination, $"{transmissionControlProtocolConfiguration.IPAddress}-{DateTime.Now.Ticks}.pcl");
File.WriteAllBytes(bytesFile, bytes.ToArray());
string ghostPCLFileName = Path.Combine(AppContext.BaseDirectory, "gpcl6win64.exe");
if (!File.Exists(ghostPCLFileName))
throw new Exception("Ghost PCL FileName doesn't Exist!");
string sourceFileNamePdf = ConvertSourceFileToPdf(ghostPCLFileName, bytesFile);
if (string.IsNullOrEmpty(sourceFileNamePdf))
throw new Exception("Ghost PCL FileName doesn't Exist!");
}
}
private static void CreateClient(AppSettings appSettings, ILogger<Worker> logger)
{
logger.LogDebug(appSettings.TransmissionControlProtocolConfiguration.IPAddress);
TcpClient tcpClient = new(appSettings.TransmissionControlProtocolConfiguration.IPAddress, appSettings.TransmissionControlProtocolConfiguration.Port);
NetworkStream networkStream = tcpClient.GetStream();
_Record = new(new(networkStream), new(networkStream), networkStream);
}
private static void CreateTcpListener(AppSettings appSettings)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
_TcpListener = new(ipAddress, appSettings.TransmissionControlProtocolConfiguration.Port);
_TcpListener.Start();
BeginAcceptTcpClient();
}
private static void NetworkStreamCanRead(TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration, NetworkStream networkStream)
{
List<byte> results = [];
byte[] bytes = new byte[1024];
string directory = Path.Combine(transmissionControlProtocolConfiguration.Destination, transmissionControlProtocolConfiguration.IPAddress);
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
do
{
int count = networkStream.Read(bytes, 0, bytes.Length);
if (count > 0)
results.AddRange(bytes.Take(count));
}
while (networkStream.DataAvailable);
if (results.Count > 0)
File.WriteAllBytes(string.Concat(directory, $"-{DateTime.Now.Ticks}{directory[^1]}.raw"), results.ToArray());
}
internal static bool ReadWrite(AppSettings appSettings, ILogger<Worker> logger)
{
lock (_Lock)
{
if (!appSettings.TransmissionControlProtocolConfiguration.Server)
ReadFiles(appSettings.TransmissionControlProtocolConfiguration);
if (!appSettings.TransmissionControlProtocolConfiguration.Server && _Record is not null)
{
TimeSpan timeSpan = new(DateTime.Now.Ticks - _LastWrite);
if (_LastWrite == 0 || timeSpan.TotalMinutes > 1)
{
try
{
_Record.NetworkStream.WriteByte(Convert.ToByte('\0'));
_LastWrite = DateTime.Now.Ticks;
}
catch (Exception)
{ }
}
}
if (!appSettings.TransmissionControlProtocolConfiguration.Server && (_Record?.NetworkStream is null || !_Record.NetworkStream.Socket.Connected))
CreateClient(appSettings, logger);
else if (appSettings.TransmissionControlProtocolConfiguration.Server && _TcpListener is null)
CreateTcpListener(appSettings);
if (_Record?.NetworkStream is not null && _Record.NetworkStream.CanRead && _Record.NetworkStream.DataAvailable)
NetworkStreamCanRead(appSettings.TransmissionControlProtocolConfiguration, _Record.NetworkStream);
if (appSettings.TransmissionControlProtocolConfiguration.Server && _TcpListener is not null && _Record?.NetworkStream is not null && _Record.NetworkStream.CanWrite)
{
try
{
_Record.BinaryWriter.Write("json");
}
catch (Exception)
{
BeginAcceptTcpClient();
}
}
}
return true;
}
}

View File

@ -0,0 +1,100 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace File_Watcher.Helpers;
public static class RijndaelEncryption
{ // cSpell:disable
/// <summary>
/// Change the input key GUID when you use this code in your own program.
/// Keep this input key very safe and prevent someone from decoding it some way!!
/// Generated 2021-08-10
/// </summary>
internal const string _InputKey = "970CCEF6-4307-4F6A-9AC8-377DADB889BD";
/// <summary>
/// Encrypt the given text and give the byte array back as a BASE64 string
/// </summary>
/// <param name="text">The text to encrypt</param>
/// <param name="salt">The password salt</param>
/// <returns>The encrypted text</returns>
public static string Encrypt(string text, string salt)
{
string result;
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
#pragma warning disable SYSLIB0022
RijndaelManaged aesAlg = NewRijndaelManaged(salt);
#pragma warning restore
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
MemoryStream msEncrypt = new();
using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write))
using (StreamWriter swEncrypt = new(csEncrypt))
swEncrypt.Write(text);
result = Convert.ToBase64String(msEncrypt.ToArray());
return result;
}
/// <summary>
/// Checks if a string is base64 encoded
/// </summary>
/// <param name="base64String">The base64 encoded string</param>
/// <returns></returns>
public static bool IsBase64String(string base64String)
{
bool result;
base64String = base64String.Trim();
#pragma warning restore
result = (base64String.Length % 4 == 0) && Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
#pragma warning restore
return result;
}
/// <summary>
/// Decrypts the given text
/// </summary>
/// <param name="cipherText">The encrypted BASE64 text</param>
/// <param name="salt">The password salt</param>
/// <returns>De gedecrypte text</returns>
public static string Decrypt(string cipherText, string salt)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException(nameof(cipherText));
if (!IsBase64String(cipherText))
throw new Exception("The cipherText input parameter is not base64 encoded");
string text;
#pragma warning disable SYSLIB0022
RijndaelManaged aesAlg = NewRijndaelManaged(salt);
#pragma warning restore
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
byte[] cipher = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new(cipher))
{
using CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read);
using StreamReader srDecrypt = new(csDecrypt);
text = srDecrypt.ReadToEnd();
}
return text;
}
/// <summary>
/// Create a new RijndaelManaged class and initialize it
/// </summary>
/// <param name="salt">The password salt</param>
/// <returns></returns>
#pragma warning disable SYSLIB0022, SYSLIB0041, CA5379
private static RijndaelManaged NewRijndaelManaged(string salt)
{
ArgumentNullException.ThrowIfNull(salt);
byte[] saltBytes = Encoding.ASCII.GetBytes(salt);
Rfc2898DeriveBytes key = new(_InputKey, saltBytes);
RijndaelManaged aesAlg = new();
#pragma warning restore
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
return aesAlg;
}
}

View File

@ -4,8 +4,15 @@ using System.Text.Json.Serialization;
namespace File_Watcher.Models; namespace File_Watcher.Models;
public record AppSettings(EAFLogConfiguration EAFLogConfiguration, public record AppSettings(EAFLogConfiguration EAFLogConfiguration,
EAFProgramDataConfiguration EAFProgramDataConfiguration,
EDADatabaseConfiguration EDADatabaseConfiguration,
CompassConfiguration CompassConfiguration,
DriveConfiguration DriveConfiguration,
NugetConfiguration NugetConfiguration,
MetrologyConfiguration MetrologyConfiguration, MetrologyConfiguration MetrologyConfiguration,
SerialConfiguration SerialConfiguration,
StratusConfiguration StratusConfiguration, StratusConfiguration StratusConfiguration,
TransmissionControlProtocolConfiguration TransmissionControlProtocolConfiguration,
WaferCounterConfiguration WaferCounterConfiguration, WaferCounterConfiguration WaferCounterConfiguration,
string BuildNumber, string BuildNumber,
string Company, string Company,

View File

@ -7,6 +7,9 @@ public class AppSettings
{ {
public string? BuildNumber { get; set; } public string? BuildNumber { get; set; }
public string[]? ConfigurationDirectoryNames { get; set; }
public int? ConfigurationSpecialFolder { get; set; }
public string? ConfigurationFileName { get; set; }
public string? Company { get; set; } public string? Company { get; set; }
public string? GitCommitSeven { get; set; } public string? GitCommitSeven { get; set; }
public string? Helper { get; set; } public string? Helper { get; set; }
@ -23,17 +26,16 @@ public class AppSettings
{ {
if (appSettings?.BuildNumber is null) if (appSettings?.BuildNumber is null)
{ {
List<string> paths = [];
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers) foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
{ {
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider) if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue; continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider) if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue; continue;
if (!physicalFileProvider.Root.Contains("UserSecrets")) paths.Add(physicalFileProvider.Root);
continue;
throw new NotSupportedException(physicalFileProvider.Root);
} }
throw new NotSupportedException("Not Found!"); throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
} }
} }
@ -42,10 +44,17 @@ public class AppSettings
} }
private static Models.AppSettings Get(AppSettings? appSettings, private static Models.AppSettings Get(AppSettings? appSettings,
Models.EAFLogConfiguration eafLogConfiguration, DriveConfiguration driveConfiguration,
Models.MetrologyConfiguration metrologyConfiguration, CompassConfiguration compassConfiguration,
Models.StratusConfiguration stratusConfiguration, EAFLogConfiguration eafLogConfiguration,
Models.WaferCounterConfiguration waferCounterConfiguration) EAFProgramDataConfiguration eafProgramDataConfiguration,
EDADatabaseConfiguration edaDatabaseConfiguration,
NugetConfiguration nugetConfiguration,
MetrologyConfiguration metrologyConfiguration,
SerialConfiguration serialConfiguration,
StratusConfiguration stratusConfiguration,
TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration,
WaferCounterConfiguration waferCounterConfiguration)
{ {
Models.AppSettings result; Models.AppSettings result;
if (appSettings is null) throw new NullReferenceException(nameof(appSettings)); if (appSettings is null) throw new NullReferenceException(nameof(appSettings));
@ -57,8 +66,15 @@ public class AppSettings
if (appSettings.WatchDirectory is null) throw new NullReferenceException(nameof(WatchDirectory)); if (appSettings.WatchDirectory is null) throw new NullReferenceException(nameof(WatchDirectory));
Verify(appSettings); Verify(appSettings);
result = new(eafLogConfiguration, result = new(eafLogConfiguration,
eafProgramDataConfiguration,
edaDatabaseConfiguration,
compassConfiguration,
driveConfiguration,
nugetConfiguration,
metrologyConfiguration, metrologyConfiguration,
serialConfiguration,
stratusConfiguration, stratusConfiguration,
transmissionControlProtocolConfiguration,
waferCounterConfiguration, waferCounterConfiguration,
appSettings.BuildNumber, appSettings.BuildNumber,
appSettings.Company, appSettings.Company,
@ -69,22 +85,53 @@ public class AppSettings
return result; return result;
} }
public static Models.AppSettings Get(IConfigurationRoot configurationRoot, private static Models.AppSettings Get(AppSettings? appSettings)
Models.EAFLogConfiguration eafLogConfiguration, {
Models.MetrologyConfiguration metrologyConfiguration, Models.AppSettings? results;
Models.StratusConfiguration stratusConfiguration, string? json;
Models.WaferCounterConfiguration waferCounterConfiguration) if (appSettings is null || appSettings.ConfigurationFileName is null)
throw new NotSupportedException($"{nameof(appSettings.ConfigurationFileName)} must be set!");
string jsonFile = Path.Combine(AppContext.BaseDirectory, appSettings.ConfigurationFileName);
if (File.Exists(jsonFile))
json = File.ReadAllText(jsonFile);
else
{
json = null;
string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
List<string> collection = [applicationData];
if (appSettings?.ConfigurationDirectoryNames is not null)
collection.AddRange(appSettings.ConfigurationDirectoryNames);
if (appSettings?.ConfigurationFileName is not null)
collection.Add(appSettings.ConfigurationFileName);
jsonFile = Path.Combine(collection.ToArray());
}
if (string.IsNullOrEmpty(json) && File.Exists(jsonFile))
json = File.ReadAllText(jsonFile);
results = (string.IsNullOrEmpty(json) ? null : results = JsonSerializer.Deserialize(json, AppSettingsSourceGenerationContext.Default.AppSettings)) ??
throw new NullReferenceException(nameof(Models.AppSettings));
results = Get(appSettings,
results.DriveConfiguration,
results.CompassConfiguration,
results.EAFLogConfiguration,
results.EAFProgramDataConfiguration,
results.EDADatabaseConfiguration,
results.NugetConfiguration,
results.MetrologyConfiguration,
results.SerialConfiguration,
results.StratusConfiguration,
results.TransmissionControlProtocolConfiguration,
results.WaferCounterConfiguration);
return results;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{ {
Models.AppSettings result; Models.AppSettings result;
#pragma warning disable IL3050, IL2026 #pragma warning disable IL3050, IL2026
AppSettings? appSettings = configurationRoot.Get<AppSettings>(); AppSettings? appSettings = configurationRoot.Get<AppSettings>();
#pragma warning restore IL3050, IL2026 #pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, appSettings); PreVerify(configurationRoot, appSettings);
result = Get(appSettings, result = Get(appSettings);
eafLogConfiguration,
metrologyConfiguration,
stratusConfiguration,
waferCounterConfiguration);
return result; return result;
} }

View File

@ -1,67 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class EAFLogConfiguration
{
public string? SearchPattern { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderEAFLogConfigurationSourceGenerationContext.Default.EAFLogConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, EAFLogConfiguration? configuration)
{
if (configuration?.SearchPattern is null)
{
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
{
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue;
if (!physicalFileProvider.Root.Contains("UserSecrets"))
continue;
throw new NotSupportedException(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
}
}
private static void Verify(EAFLogConfiguration _)
{
}
private static Models.EAFLogConfiguration Get(EAFLogConfiguration? configuration)
{
Models.EAFLogConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.SearchPattern is null) throw new NullReferenceException(nameof(configuration.SearchPattern));
Verify(configuration);
result = new(configuration.SearchPattern);
return result;
}
public static Models.EAFLogConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.EAFLogConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.EAFLogConfiguration));
#pragma warning disable IL3050, IL2026
EAFLogConfiguration? configuration = configurationSection.Get<EAFLogConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EAFLogConfiguration))]
internal partial class BinderEAFLogConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -1,76 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class MetrologyConfiguration
{
public int? DirectoriesBack { get; set; }
public int? DeleteOlderThanWeeks { get; set; }
public string[]? HardcodedValues { get; set; }
public string[]? SourceDirectories { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderMetrologyConfigurationSourceGenerationContext.Default.MetrologyConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, MetrologyConfiguration? configuration)
{
if (configuration?.DirectoriesBack is null)
{
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
{
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue;
if (!physicalFileProvider.Root.Contains("UserSecrets"))
continue;
throw new NotSupportedException(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
}
}
private static void Verify(MetrologyConfiguration _)
{
}
private static Models.MetrologyConfiguration Get(MetrologyConfiguration? configuration)
{
Models.MetrologyConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.DirectoriesBack is null) throw new NullReferenceException(nameof(configuration.DirectoriesBack));
if (configuration.DeleteOlderThanWeeks is null) throw new NullReferenceException(nameof(configuration.DeleteOlderThanWeeks));
if (configuration.HardcodedValues is null) throw new NullReferenceException(nameof(configuration.HardcodedValues));
if (configuration.SourceDirectories is null) throw new NullReferenceException(nameof(configuration.SourceDirectories));
Verify(configuration);
result = new(configuration.DirectoriesBack.Value,
configuration.DeleteOlderThanWeeks.Value,
configuration.HardcodedValues,
configuration.SourceDirectories);
return result;
}
public static Models.MetrologyConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.MetrologyConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.MetrologyConfiguration));
#pragma warning disable IL3050, IL2026
MetrologyConfiguration? configuration = configurationSection.Get<MetrologyConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(MetrologyConfiguration))]
internal partial class BinderMetrologyConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -1,73 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class StratusConfiguration
{
public string? Destination { get; set; }
public string? FileDelimiterPattern { get; set; }
public string? WatchFile { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderStratusConfigurationSourceGenerationContext.Default.StratusConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, StratusConfiguration? configuration)
{
if (configuration?.Destination is null)
{
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
{
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue;
if (!physicalFileProvider.Root.Contains("UserSecrets"))
continue;
throw new NotSupportedException(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
}
}
private static void Verify(StratusConfiguration _)
{
}
private static Models.StratusConfiguration Get(StratusConfiguration? configuration)
{
Models.StratusConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
if (configuration.FileDelimiterPattern is null) throw new NullReferenceException(nameof(configuration.FileDelimiterPattern));
if (configuration.WatchFile is null) throw new NullReferenceException(nameof(configuration.WatchFile));
Verify(configuration);
result = new(configuration.Destination,
configuration.FileDelimiterPattern,
configuration.WatchFile);
return result;
}
public static Models.StratusConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.StratusConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.StratusConfiguration));
#pragma warning disable IL3050, IL2026
StratusConfiguration? configuration = configurationSection.Get<StratusConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(StratusConfiguration))]
internal partial class BinderStratusConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -1,70 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class WaferCounterConfiguration
{
public string? Destination { get; set; }
public bool? MatchPath { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderWaferCounterConfigurationSourceGenerationContext.Default.WaferCounterConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, WaferCounterConfiguration? configuration)
{
if (configuration?.Destination is null)
{
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
{
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
continue;
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
continue;
if (!physicalFileProvider.Root.Contains("UserSecrets"))
continue;
throw new NotSupportedException(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
}
}
private static void Verify(WaferCounterConfiguration _)
{
}
private static Models.WaferCounterConfiguration Get(WaferCounterConfiguration? configuration)
{
Models.WaferCounterConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
if (configuration.MatchPath is null) throw new NullReferenceException(nameof(configuration.MatchPath));
Verify(configuration);
result = new(configuration.Destination,
configuration.MatchPath.Value);
return result;
}
public static Models.WaferCounterConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.WaferCounterConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.WaferCounterConfiguration));
#pragma warning disable IL3050, IL2026
WaferCounterConfiguration? configuration = configurationSection.Get<WaferCounterConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(WaferCounterConfiguration))]
internal partial class BinderWaferCounterConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record CompassConfiguration(string Destination,
int HoursBack,
string MonthPattern,
string Pattern,
string Source,
string TriggerAppendage,
string YearPattern)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, CompassConfigurationSourceGenerationContext.Default.CompassConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(CompassConfiguration))]
internal partial class CompassConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,25 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record DriveConfiguration(string Letter,
string Password,
string Share,
bool? Use,
string User)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, DriveConfigurationSourceGenerationContext.Default.DriveConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(DriveConfiguration))]
internal partial class DriveConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,21 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record EAFProgramDataConfiguration(string Destination, string Source)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, EAFProgramDataConfigurationSourceGenerationContext.Default.EAFProgramDataConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EAFProgramDataConfiguration))]
internal partial class EAFProgramDataConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record EDADatabaseConfiguration(string CSharpDateTimeFormat,
string FileShare,
string Name,
string OracleDateTimeFormat,
string Password,
string TNS,
string UserName)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, EDADatabaseConfigurationSourceGenerationContext.Default.EDADatabaseConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EDADatabaseConfiguration))]
internal partial class EDADatabaseConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record NugetConfiguration(string Destination,
string KeyFileExtension,
string KeyFileExtensionB,
string KeyFileExtensionC,
bool RenameToLower,
string SearchPattern,
string Source)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, NugetConfigurationSourceGenerationContext.Default.NugetConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(NugetConfiguration))]
internal partial class NugetConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,24 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record SerialConfiguration(string Destination,
string GhostPCLFileName,
string LincPDFCFileName,
string PortName)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, SerialConfigurationSourceGenerationContext.Default.SerialConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(SerialConfiguration))]
internal partial class SerialConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,25 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models;
public record TransmissionControlProtocolConfiguration(string Destination,
string GhostPCLFileName,
string IPAddress,
int Port,
bool Server)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, TransmissionControlProtocolConfigurationSourceGenerationContext.Default.TransmissionControlProtocolConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(TransmissionControlProtocolConfiguration))]
internal partial class TransmissionControlProtocolConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -14,11 +14,7 @@ public class Program
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args); WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
#pragma warning restore IL3050 #pragma warning restore IL3050
_ = webApplicationBuilder.Configuration.AddUserSecrets<Program>(); _ = webApplicationBuilder.Configuration.AddUserSecrets<Program>();
EAFLogConfiguration eafLogConfiguration = Models.Binder.EAFLogConfiguration.Get(webApplicationBuilder.Configuration); AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration);
MetrologyConfiguration metrologyConfiguration = Models.Binder.MetrologyConfiguration.Get(webApplicationBuilder.Configuration);
StratusConfiguration stratusConfiguration = Models.Binder.StratusConfiguration.Get(webApplicationBuilder.Configuration);
WaferCounterConfiguration waferCounterConfiguration = Models.Binder.WaferCounterConfiguration.Get(webApplicationBuilder.Configuration);
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration, eafLogConfiguration, metrologyConfiguration, stratusConfiguration, waferCounterConfiguration);
if (string.IsNullOrEmpty(appSettings.Company)) if (string.IsNullOrEmpty(appSettings.Company))
throw new Exception("Company name must have a value!"); throw new Exception("Company name must have a value!");
try try

View File

@ -22,7 +22,7 @@ public partial class Worker : BackgroundService
_IsWindowsService = collection.Contains(nameof(WindowsServiceLifetime)); _IsWindowsService = collection.Contains(nameof(WindowsServiceLifetime));
} }
private void Body() private void BodyInner(CancellationToken cancellationToken)
{ {
_Logger.LogInformation("A) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt")); _Logger.LogInformation("A) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt"));
if (!Directory.Exists(_AppSettings.WatchDirectory)) if (!Directory.Exists(_AppSettings.WatchDirectory))
@ -31,28 +31,43 @@ public partial class Worker : BackgroundService
{ {
_ = _AppSettings.Helper switch _ = _AppSettings.Helper switch
{ {
nameof(Helpers.HelperEAFLog) => Helpers.HelperEAFLog.DeleteFiles(_AppSettings, _Logger), nameof(Helpers.HelperNuget) => Helpers.HelperNuget.Sync(_AppSettings, _Logger),
nameof(Helpers.HelperTCP) => Helpers.HelperTCP.ReadWrite(_AppSettings, _Logger),
nameof(Helpers.HelperCompass) => Helpers.HelperCompass.CopyFile(_AppSettings, _Logger),
nameof(Helpers.HelperStratus) => Helpers.HelperStratus.MoveFile(_AppSettings, _Logger), nameof(Helpers.HelperStratus) => Helpers.HelperStratus.MoveFile(_AppSettings, _Logger),
nameof(Helpers.HelperEAFLog) => Helpers.HelperEAFLog.DeleteFiles(_AppSettings, _Logger),
nameof(Helpers.HelperInfinityQS) => Helpers.HelperInfinityQS.RunMI(_AppSettings, _Logger),
nameof(Helpers.HelperEventLog) => Helpers.HelperEventLog.ClearEventLogs(_AppSettings, _Logger), nameof(Helpers.HelperEventLog) => Helpers.HelperEventLog.ClearEventLogs(_AppSettings, _Logger),
nameof(Helpers.HelperWaferCounter) => Helpers.HelperWaferCounter.MoveFile(_AppSettings, _Logger), nameof(Helpers.HelperWaferCounter) => Helpers.HelperWaferCounter.MoveFile(_AppSettings, _Logger),
nameof(Helpers.HelperEAFProgramData) => Helpers.HelperEAFProgramData.MoveFiles(_AppSettings, _Logger),
nameof(Helpers.HelperSerial) => Helpers.HelperSerial.ReadWrite(_AppSettings, _Logger, cancellationToken),
nameof(Helpers.HelperMetrologyFiles) => Helpers.HelperMetrologyFiles.SortAndDelete(_AppSettings, _Logger), nameof(Helpers.HelperMetrologyFiles) => Helpers.HelperMetrologyFiles.SortAndDelete(_AppSettings, _Logger),
nameof(Helpers.HelperEDADatabase) => Helpers.HelperEDADatabase.SaveDataCollectionPlans(_AppSettings, _Logger, cancellationToken),
_ => throw new NotSupportedException() _ => throw new NotSupportedException()
}; };
} }
_Logger.LogInformation("B) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt")); _Logger.LogInformation("B) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt"));
} }
private async Task Body(CancellationToken stoppingToken) private async Task Body(CancellationToken cancellationToken)
{ {
if (!_IsWindowsService) if (!_IsWindowsService)
throw new EvaluateException("Set break point and skip!"); throw new EvaluateException($"Set break point and skip to run {_AppSettings.Helper}!");
while (_IsWindowsService && !stoppingToken.IsCancellationRequested) if (!_IsWindowsService)
{ {
Body(); for (int i = 0; i < int.MaxValue; i++)
await Task.Delay(_AppSettings.MillisecondsDelay, stoppingToken); {
BodyInner(cancellationToken);
Thread.Sleep(500);
}
}
while (_IsWindowsService && !cancellationToken.IsCancellationRequested)
{
BodyInner(cancellationToken);
await Task.Delay(_AppSettings.MillisecondsDelay, cancellationToken);
} }
} }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) => protected override async Task ExecuteAsync(CancellationToken cancellationToken) =>
await Body(stoppingToken); await Body(cancellationToken);
} }