HelperEDADatabase

HelperEAFProgramData
HelperCompass
HelperInfinityQS
HelperSerial
HelperTCP
dotnet_analyzer_diagnostic
This commit is contained in:
Mike Phares 2024-04-16 10:32:55 -07:00
parent e0f591e987
commit 27ba309e88
37 changed files with 4956 additions and 80 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_when_type_is_apparent = false:warning
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 = non_public # IDE0060: Remove unused parameter
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.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.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.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.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.IDE0004.severity = warning # IDE0004: Cast is redundant.
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.IDE0031.severity = warning # Use null propagation (IDE0031)
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.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.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.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290)
dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified

7
.gitignore vendored
View File

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

72
.vscode/settings.json vendored
View File

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

10
.vscode/tasks.json vendored
View File

@ -72,9 +72,15 @@
"problemMatcher": "$msCompile"
},
{
"label": "File-Watcher AOT s V Helpers",
"label": "File-Folder-Helper AOT s V Helpers",
"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": []
}
]

View File

@ -1,19 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<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>
<ItemGroup>
<PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.4" />
<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" 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="3.21.140" />
<PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.4" />
<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>
</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()]);
}
}
}

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

@ -0,0 +1,453 @@
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)
{
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;
}
}
}
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
{
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);
}
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
}

118
Helpers/HelperCompass.cs Normal file
View File

@ -0,0 +1,118 @@
using File_Watcher.Models;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
namespace File_Watcher.Helpers;
internal static partial 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;
foreach (string file in files)
{
checkFile = Path.Combine(appSettings.CompassConfiguration.Destination, Path.GetFileName(file));
if (File.Exists(checkFile))
continue;
File.Copy(file, checkFile);
}
}
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}", files);
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,280 @@
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 });
XmlSerializer xmlSerializer = new(typeof(T), typeof(T).GetNestedTypes());
result = xmlSerializer.Deserialize(reader);
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);
json = JsonSerializer.Serialize(configuration, configuration.GetType(), jsonSerializerOptions);
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;
Array objectTypes = Enum.GetValues(typeof(ModuleInstanceTypeName));
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;
DateTime dateTime;
@ -102,7 +102,7 @@ internal static partial class HelperMetrologyFiles
CultureInfo cultureInfo = new("en-US");
Calendar calendar = cultureInfo.Calendar;
Sort(appSettings.MetrologyConfiguration, logger, calendar);
Delete(appSettings.MetrologyConfiguration, logger, calendar);
Delete(appSettings.MetrologyConfiguration, logger);
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

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

View File

@ -23,17 +23,16 @@ public class AppSettings
{
if (appSettings?.BuildNumber is null)
{
List<string> paths = [];
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);
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
@ -42,9 +41,15 @@ public class AppSettings
}
private static Models.AppSettings Get(AppSettings? appSettings,
Models.DriveConfiguration driveConfiguration,
Models.CompassConfiguration compassConfiguration,
Models.EAFLogConfiguration eafLogConfiguration,
Models.EAFProgramDataConfiguration eafProgramDataConfiguration,
Models.EDADatabaseConfiguration edaDatabaseConfiguration,
Models.MetrologyConfiguration metrologyConfiguration,
Models.SerialConfiguration serialConfiguration,
Models.StratusConfiguration stratusConfiguration,
Models.TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration,
Models.WaferCounterConfiguration waferCounterConfiguration)
{
Models.AppSettings result;
@ -57,8 +62,14 @@ public class AppSettings
if (appSettings.WatchDirectory is null) throw new NullReferenceException(nameof(WatchDirectory));
Verify(appSettings);
result = new(eafLogConfiguration,
eafProgramDataConfiguration,
edaDatabaseConfiguration,
compassConfiguration,
driveConfiguration,
metrologyConfiguration,
serialConfiguration,
stratusConfiguration,
transmissionControlProtocolConfiguration,
waferCounterConfiguration,
appSettings.BuildNumber,
appSettings.Company,
@ -70,10 +81,16 @@ public class AppSettings
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot,
Models.EAFLogConfiguration eafLogConfiguration,
Models.MetrologyConfiguration metrologyConfiguration,
Models.StratusConfiguration stratusConfiguration,
Models.WaferCounterConfiguration waferCounterConfiguration)
Models.CompassConfiguration compassConfiguration,
Models.DriveConfiguration driveConfiguration,
Models.EAFLogConfiguration eafLogConfiguration,
Models.EAFProgramDataConfiguration eafProgramDataConfiguration,
Models.EDADatabaseConfiguration edaDatabaseConfiguration,
Models.MetrologyConfiguration metrologyConfiguration,
Models.SerialConfiguration serialConfiguration,
Models.StratusConfiguration stratusConfiguration,
Models.TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration,
Models.WaferCounterConfiguration waferCounterConfiguration)
{
Models.AppSettings result;
#pragma warning disable IL3050, IL2026
@ -81,9 +98,15 @@ public class AppSettings
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, appSettings);
result = Get(appSettings,
driveConfiguration,
compassConfiguration,
eafLogConfiguration,
eafProgramDataConfiguration,
edaDatabaseConfiguration,
metrologyConfiguration,
serialConfiguration,
stratusConfiguration,
transmissionControlProtocolConfiguration,
waferCounterConfiguration);
return result;
}

View File

@ -0,0 +1,81 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class CompassConfiguration
{
public string? Destination { get; set; }
public int? HoursBack { get; set; }
public string? MonthPattern { get; set; }
public string? Pattern { get; set; }
public string? Source { get; set; }
public string? YearPattern { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderCompassConfigurationSourceGenerationContext.Default.CompassConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, CompassConfiguration? configuration)
{
if (configuration?.Destination is null)
{
List<string> paths = [];
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;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static void Verify(CompassConfiguration _)
{
}
private static Models.CompassConfiguration Get(CompassConfiguration? configuration)
{
Models.CompassConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
if (configuration.HoursBack is null) throw new NullReferenceException(nameof(configuration.HoursBack));
if (configuration.MonthPattern is null) throw new NullReferenceException(nameof(configuration.MonthPattern));
if (configuration.Pattern is null) throw new NullReferenceException(nameof(configuration.Pattern));
if (configuration.Source is null) throw new NullReferenceException(nameof(configuration.Source));
if (configuration.YearPattern is null) throw new NullReferenceException(nameof(configuration.YearPattern));
Verify(configuration);
result = new(configuration.Destination,
configuration.HoursBack.Value,
configuration.MonthPattern,
configuration.Pattern,
configuration.Source,
configuration.YearPattern);
return result;
}
public static Models.CompassConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.CompassConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.CompassConfiguration));
#pragma warning disable IL3050, IL2026
CompassConfiguration? configuration = configurationSection.Get<CompassConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(CompassConfiguration))]
internal partial class BinderCompassConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,78 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class DriveConfiguration
{
public string? Letter { get; set; }
public string? Password { get; set; }
public string? Share { get; set; }
public bool? Use { get; set; }
public string? User { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderDriveConfigurationSourceGenerationContext.Default.DriveConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, DriveConfiguration? driveConfiguration)
{
if (driveConfiguration?.Letter is null)
{
List<string> paths = [];
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;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static void Verify(DriveConfiguration _)
{
}
private static Models.DriveConfiguration Get(DriveConfiguration? driveConfiguration)
{
Models.DriveConfiguration result;
if (driveConfiguration?.Letter is null)
throw new NullReferenceException(nameof(Letter));
if (driveConfiguration?.Password is null)
throw new NullReferenceException(nameof(Password));
if (driveConfiguration?.Share is null)
throw new NullReferenceException(nameof(Share));
if (driveConfiguration?.Use is null)
throw new NullReferenceException(nameof(Use));
if (driveConfiguration?.User is null)
throw new NullReferenceException(nameof(User));
Verify(driveConfiguration);
result = new(driveConfiguration.Letter, driveConfiguration.Password, driveConfiguration.Share, driveConfiguration.Use.Value, driveConfiguration.User);
return result;
}
public static Models.DriveConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.DriveConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.DriveConfiguration));
#pragma warning disable IL3050, IL2026
DriveConfiguration? driveConfiguration = configurationSection.Get<DriveConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, driveConfiguration);
result = Get(driveConfiguration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(DriveConfiguration))]
internal partial class BinderDriveConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -18,17 +18,16 @@ public class EAFLogConfiguration
{
if (configuration?.SearchPattern is null)
{
List<string> paths = [];
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);
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}

View File

@ -0,0 +1,68 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class EAFProgramDataConfiguration
{
public string? Destination { get; set; }
public string? Source { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderEAFProgramDataConfigurationSourceGenerationContext.Default.EAFProgramDataConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, EAFProgramDataConfiguration? configuration)
{
if (configuration?.Destination is null)
{
List<string> paths = [];
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;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static void Verify(EAFProgramDataConfiguration _)
{
}
private static Models.EAFProgramDataConfiguration Get(EAFProgramDataConfiguration? configuration)
{
Models.EAFProgramDataConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
if (configuration.Source is null) throw new NullReferenceException(nameof(configuration.Source));
Verify(configuration);
result = new(configuration.Destination, configuration.Source);
return result;
}
public static Models.EAFProgramDataConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.EAFProgramDataConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.EAFProgramDataConfiguration));
#pragma warning disable IL3050, IL2026
EAFProgramDataConfiguration? configuration = configurationSection.Get<EAFProgramDataConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EAFProgramDataConfiguration))]
internal partial class BinderEAFProgramDataConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -0,0 +1,84 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class EDADatabaseConfiguration
{
public string? CSharpDateTimeFormat { get; set; }
public string? FileShare { get; set; }
public string? Name { get; set; }
public string? OracleDateTimeFormat { get; set; }
public string? Password { get; set; }
public string? TNS { get; set; }
public string? UserName { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderEDADatabaseConfigurationSourceGenerationContext.Default.EDADatabaseConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, EDADatabaseConfiguration? configuration)
{
if (configuration?.CSharpDateTimeFormat is null)
{
List<string> paths = [];
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;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static void Verify(EDADatabaseConfiguration _)
{
}
private static Models.EDADatabaseConfiguration Get(EDADatabaseConfiguration? configuration)
{
Models.EDADatabaseConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.CSharpDateTimeFormat is null) throw new NullReferenceException(nameof(configuration.CSharpDateTimeFormat));
if (configuration.FileShare is null) throw new NullReferenceException(nameof(configuration.FileShare));
if (configuration.Name is null) throw new NullReferenceException(nameof(configuration.Name));
if (configuration.OracleDateTimeFormat is null) throw new NullReferenceException(nameof(configuration.OracleDateTimeFormat));
if (configuration.Password is null) throw new NullReferenceException(nameof(configuration.Password));
if (configuration.TNS is null) throw new NullReferenceException(nameof(configuration.TNS));
if (configuration.UserName is null) throw new NullReferenceException(nameof(configuration.UserName));
Verify(configuration);
result = new(configuration.CSharpDateTimeFormat,
configuration.FileShare,
configuration.Name,
configuration.OracleDateTimeFormat,
configuration.Password,
configuration.TNS,
configuration.UserName);
return result;
}
public static Models.EDADatabaseConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.EDADatabaseConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.EDADatabaseConfiguration));
#pragma warning disable IL3050, IL2026
EDADatabaseConfiguration? configuration = configurationSection.Get<EDADatabaseConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EDADatabaseConfiguration))]
internal partial class BinderEDADatabaseConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -21,17 +21,16 @@ public class MetrologyConfiguration
{
if (configuration?.DirectoriesBack is null)
{
List<string> paths = [];
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);
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}

View File

@ -0,0 +1,74 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class SerialConfiguration
{
public string? Destination { get; set; }
public string? GhostPCLFileName { get; set; }
public string? LincPDFCFileName { get; set; }
public string? PortName { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderSerialConfigurationSourceGenerationContext.Default.SerialConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, SerialConfiguration? configuration)
{
if (configuration?.Destination is null)
{
List<string> paths = [];
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;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static void Verify(SerialConfiguration _)
{ }
private static Models.SerialConfiguration Get(SerialConfiguration? configuration)
{
Models.SerialConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
if (configuration.GhostPCLFileName is null) throw new NullReferenceException(nameof(configuration.GhostPCLFileName));
if (configuration.LincPDFCFileName is null) throw new NullReferenceException(nameof(configuration.LincPDFCFileName));
if (configuration.PortName is null) throw new NullReferenceException(nameof(configuration.PortName));
Verify(configuration);
result = new(configuration.Destination,
configuration.GhostPCLFileName,
configuration.LincPDFCFileName,
configuration.PortName);
return result;
}
public static Models.SerialConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.SerialConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.SerialConfiguration));
#pragma warning disable IL3050, IL2026
SerialConfiguration? configuration = configurationSection.Get<SerialConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(SerialConfiguration))]
internal partial class BinderSerialConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -20,17 +20,16 @@ public class StratusConfiguration
{
if (configuration?.Destination is null)
{
List<string> paths = [];
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);
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}

View File

@ -0,0 +1,89 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Models.Binder;
public class TransmissionControlProtocolConfiguration
{
public string? Destination { get; set; }
public string? GhostPCLFileName { get; set; }
public string? IPAddress { get; set; }
public int? Port { get; set; }
public bool? Server { get; set; }
public override string ToString()
{
string result = JsonSerializer.Serialize(this, BinderTransmissionControlProtocolConfigurationSourceGenerationContext.Default.TransmissionControlProtocolConfiguration);
return result;
}
private static void PreVerify(IConfigurationRoot configurationRoot, TransmissionControlProtocolConfiguration? configuration)
{
if (configuration?.Destination is null)
{
List<string> paths = [];
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;
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}
private static void Verify(TransmissionControlProtocolConfiguration _)
{
// if (transmissionControlProtocolConfiguration.IPAddresses is null) throw new NullReferenceException(nameof(transmissionControlProtocolConfiguration.IPAddresses));
// foreach (KeyValuePair<string, string[]> keyValuePair in transmissionControlProtocolConfiguration.IPAddresses)
// {
// if (string.IsNullOrEmpty(keyValuePair.Key))
// throw new Exception(nameof(IPAddresses));
// foreach (string value in keyValuePair.Value)
// {
// if (string.IsNullOrEmpty(value))
// throw new Exception(nameof(IPAddresses));
// }
// }
}
private static Models.TransmissionControlProtocolConfiguration Get(TransmissionControlProtocolConfiguration? configuration)
{
Models.TransmissionControlProtocolConfiguration result;
if (configuration is null) throw new NullReferenceException(nameof(configuration));
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
if (configuration.GhostPCLFileName is null) throw new NullReferenceException(nameof(configuration.GhostPCLFileName));
if (configuration.IPAddress is null) throw new NullReferenceException(nameof(configuration.IPAddress));
if (configuration.Port is null) throw new NullReferenceException(nameof(configuration.Port));
if (configuration.Server is null) throw new NullReferenceException(nameof(configuration.Server));
Verify(configuration);
result = new(configuration.Destination,
configuration.GhostPCLFileName,
configuration.IPAddress,
configuration.Port.Value,
configuration.Server.Value);
return result;
}
public static Models.TransmissionControlProtocolConfiguration Get(IConfigurationRoot configurationRoot)
{
Models.TransmissionControlProtocolConfiguration result;
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.TransmissionControlProtocolConfiguration));
#pragma warning disable IL3050, IL2026
TransmissionControlProtocolConfiguration? configuration = configurationSection.Get<TransmissionControlProtocolConfiguration>();
#pragma warning restore IL3050, IL2026
PreVerify(configurationRoot, configuration);
result = Get(configuration);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(TransmissionControlProtocolConfiguration))]
internal partial class BinderTransmissionControlProtocolConfigurationSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -19,17 +19,16 @@ public class WaferCounterConfiguration
{
if (configuration?.Destination is null)
{
List<string> paths = [];
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);
paths.Add(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}");
}
}

View File

@ -0,0 +1,26 @@
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 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,101 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace File_Watcher.Models;
public static class RijndaelEncryption
{
/// <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
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 disable
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
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
private static RijndaelManaged NewRijndaelManaged(string salt)
{
if (salt == null)
throw new ArgumentNullException(nameof(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

@ -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,27 @@ public class Program
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
#pragma warning restore IL3050
_ = webApplicationBuilder.Configuration.AddUserSecrets<Program>();
DriveConfiguration driveConfiguration = Models.Binder.DriveConfiguration.Get(webApplicationBuilder.Configuration);
EAFLogConfiguration eafLogConfiguration = Models.Binder.EAFLogConfiguration.Get(webApplicationBuilder.Configuration);
MetrologyConfiguration metrologyConfiguration = Models.Binder.MetrologyConfiguration.Get(webApplicationBuilder.Configuration);
EAFProgramDataConfiguration eafProgramDataConfiguration = Models.Binder.EAFProgramDataConfiguration.Get(webApplicationBuilder.Configuration);
EDADatabaseConfiguration edaDatabaseConfiguration = Models.Binder.EDADatabaseConfiguration.Get(webApplicationBuilder.Configuration);
SerialConfiguration serialConfiguration = Models.Binder.SerialConfiguration.Get(webApplicationBuilder.Configuration);
StratusConfiguration stratusConfiguration = Models.Binder.StratusConfiguration.Get(webApplicationBuilder.Configuration);
CompassConfiguration compassConfiguration = Models.Binder.CompassConfiguration.Get(webApplicationBuilder.Configuration);
MetrologyConfiguration metrologyConfiguration = Models.Binder.MetrologyConfiguration.Get(webApplicationBuilder.Configuration);
WaferCounterConfiguration waferCounterConfiguration = Models.Binder.WaferCounterConfiguration.Get(webApplicationBuilder.Configuration);
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration, eafLogConfiguration, metrologyConfiguration, stratusConfiguration, waferCounterConfiguration);
TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration = Models.Binder.TransmissionControlProtocolConfiguration.Get(webApplicationBuilder.Configuration);
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration,
compassConfiguration,
driveConfiguration,
eafLogConfiguration,
eafProgramDataConfiguration,
edaDatabaseConfiguration,
metrologyConfiguration,
serialConfiguration,
stratusConfiguration,
transmissionControlProtocolConfiguration,
waferCounterConfiguration);
if (string.IsNullOrEmpty(appSettings.Company))
throw new Exception("Company name must have a value!");
try

View File

@ -22,7 +22,7 @@ public partial class Worker : BackgroundService
_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"));
if (!Directory.Exists(_AppSettings.WatchDirectory))
@ -31,28 +31,42 @@ public partial class Worker : BackgroundService
{
_ = _AppSettings.Helper switch
{
nameof(Helpers.HelperEAFLog) => Helpers.HelperEAFLog.DeleteFiles(_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.HelperEAFLog) => Helpers.HelperEAFLog.DeleteFiles(_AppSettings, _Logger),
nameof(Helpers.HelperInfinityQS) => Helpers.HelperInfinityQS.RunMI(_AppSettings, _Logger),
nameof(Helpers.HelperEventLog) => Helpers.HelperEventLog.ClearEventLogs(_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.HelperEDADatabase) => Helpers.HelperEDADatabase.SaveDataCollectionPlans(_AppSettings, _Logger, cancellationToken),
_ => 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"));
}
private async Task Body(CancellationToken stoppingToken)
private async Task Body(CancellationToken cancellationToken)
{
if (!_IsWindowsService)
throw new EvaluateException("Set break point and skip!");
while (_IsWindowsService && !stoppingToken.IsCancellationRequested)
if (!_IsWindowsService)
{
Body();
await Task.Delay(_AppSettings.MillisecondsDelay, stoppingToken);
for (int i = 0; i < int.MaxValue; i++)
{
BodyInner(cancellationToken);
Thread.Sleep(500);
}
}
while (_IsWindowsService && !cancellationToken.IsCancellationRequested)
{
BodyInner(cancellationToken);
await Task.Delay(_AppSettings.MillisecondsDelay, cancellationToken);
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) =>
await Body(stoppingToken);
protected override async Task ExecuteAsync(CancellationToken cancellationToken) =>
await Body(cancellationToken);
}