Compare commits
18 Commits
e0f591e987
...
master
Author | SHA1 | Date | |
---|---|---|---|
31b5a4925b | |||
4e6504af7e | |||
84d1b07301 | |||
5cd2500983 | |||
9fff0541ae | |||
61008fd9cf | |||
4219a9f3a4 | |||
db19697d73 | |||
c831ad2ab9 | |||
38340090be | |||
e6442fff9f | |||
13b9731edf | |||
e32a942fde | |||
26a28afe78 | |||
878750b284 | |||
4eb70db231 | |||
135f236b8c | |||
27ba309e88 |
@ -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
7
.gitignore
vendored
@ -327,3 +327,10 @@ ASALocalRun/
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
*.all
|
||||
*.pcl
|
||||
*.pdf
|
||||
*.raw
|
||||
|
||||
.vscode/.UserSecrets/secrets.json
|
||||
|
5
.vscode/mklink.md
vendored
Normal file
5
.vscode/mklink.md
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
# mklink
|
||||
|
||||
```bash Wed Jul 24 2024 08:28:01 GMT-0700 (Mountain Standard Time)
|
||||
mklink /J "L:\DevOps\Mesa_FI\File-Watcher\.vscode\.UserSecrets" "C:\Users\phares\AppData\Roaming\Microsoft\UserSecrets\6062c774-99a9-4f4a-b42d-a9cb7fcbd8be"
|
||||
```
|
14
.vscode/settings.json
vendored
14
.vscode/settings.json
vendored
@ -12,23 +12,37 @@
|
||||
"cSpell.words": [
|
||||
"ASPNETCORE",
|
||||
"BIRT",
|
||||
"Camstar",
|
||||
"CHIL",
|
||||
"DEAT",
|
||||
"DEVICEHEIGHTPOINTS",
|
||||
"DEVICEWIDTHPOINTS",
|
||||
"endianness",
|
||||
"Exif",
|
||||
"FAMC",
|
||||
"FAMS",
|
||||
"FIXEDMEDIA",
|
||||
"GIVN",
|
||||
"gpcl",
|
||||
"Hmmssfff",
|
||||
"HUSB",
|
||||
"INDI",
|
||||
"Infineon",
|
||||
"Kanban",
|
||||
"kanbn",
|
||||
"Kofax",
|
||||
"linc",
|
||||
"Linc",
|
||||
"NOPAUSE",
|
||||
"NSFX",
|
||||
"OBJE",
|
||||
"onenote",
|
||||
"PDFC",
|
||||
"pdfwrite",
|
||||
"PDSF",
|
||||
"pged",
|
||||
"Phares",
|
||||
"Rijndael",
|
||||
"Serilog",
|
||||
"SUBM",
|
||||
"SURN",
|
||||
|
24
.vscode/tasks.json
vendored
24
.vscode/tasks.json
vendored
@ -22,7 +22,7 @@
|
||||
"-p",
|
||||
"${workspaceFolder}/File-Watcher.csproj",
|
||||
"set",
|
||||
"asdf",
|
||||
"_UserSecretsId",
|
||||
"6516d19d6569"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
@ -54,6 +54,16 @@
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "Format-Whitespaces",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"format",
|
||||
"whitespace"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "Publish AOT",
|
||||
"command": "dotnet",
|
||||
@ -72,9 +82,17 @@
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "File-Watcher AOT s V Helpers",
|
||||
"label": "File-Folder-Helper AOT s X Day-Helper-2025-03-20",
|
||||
"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",
|
||||
"args": [
|
||||
"s",
|
||||
"X",
|
||||
"L:/DevOps/Mesa_FI/File-Watcher",
|
||||
"Day-Helper-2025-03-20",
|
||||
"false",
|
||||
"4"
|
||||
],
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
|
@ -1,19 +1,32 @@
|
||||
<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.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="CliWrap" Version="3.8.2" />
|
||||
<PackageReference Include="DiscUtils.Iso9660" Version="0.16.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.14" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="8.0.1" />
|
||||
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="23.7.0" />
|
||||
<PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.14" />
|
||||
<PackageReference Include="ShellProgressBar" Version="5.2.0" />
|
||||
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="8.0.14" />
|
||||
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
|
||||
<PackageReference Include="System.Text.Json" Version="9.0.3" />
|
||||
<PackageReference Include="Phares.AA.Shared" Version="8.0.114.12235" />
|
||||
<PackageReference Include="Phares.AA.Metadata" Version="8.0.114.12235" />
|
||||
</ItemGroup>
|
||||
</Project>
|
45
File-Watcher.yaml
Normal file
45
File-Watcher.yaml
Normal file
@ -0,0 +1,45 @@
|
||||
trigger:
|
||||
branches:
|
||||
include:
|
||||
- main
|
||||
pool:
|
||||
name: eaf
|
||||
demands: eaf-ems-pc
|
||||
variables:
|
||||
buildConfiguration: "Release"
|
||||
ASPNETCORE_ENVIRONMENT: "Production"
|
||||
jobs:
|
||||
- job: BuildTestPublish
|
||||
steps:
|
||||
- script: |
|
||||
echo repo: $(Build.Repository.Name)
|
||||
echo buildId: $(Build.BuildId)
|
||||
echo build configuration: $(BuildConfiguration)
|
||||
displayName: "Echo Check"
|
||||
|
||||
- task: DotNetCoreCLI@2
|
||||
displayName: "dotnet build"
|
||||
inputs:
|
||||
command: "build"
|
||||
configuration: $(BuildConfiguration)
|
||||
|
||||
- task: DotNetCoreCLI@2
|
||||
displayName: "dotnet test"
|
||||
inputs:
|
||||
command: "test"
|
||||
arguments: "-c $(BuildConfiguration)"
|
||||
publishTestResults: true
|
||||
projects: MesaProveInTests
|
||||
|
||||
- task: DotNetCoreCLI@2
|
||||
displayName: "dotnet publish"
|
||||
inputs:
|
||||
command: "publish"
|
||||
publishWebProjects: true
|
||||
arguments: "-c $(BuildConfiguration) -o $(Build.ArtifactStagingDirectory) -r win-x64 /p:EnvironmentName=$(ASPNETCORE_ENVIRONMENT)"
|
||||
|
||||
- task: CopyFiles@2
|
||||
displayName: "Copy Files"
|
||||
inputs:
|
||||
SourceFolder: "$(Build.ArtifactStagingDirectory)"
|
||||
TargetFolder: 'D:\$(Build.Repository.Name)\$(Build.BuildId)\$(BuildConfiguration)'
|
363
Helpers/DeterministicHashCodeHelper.cs
Normal file
363
Helpers/DeterministicHashCodeHelper.cs
Normal file
@ -0,0 +1,363 @@
|
||||
using CliWrap;
|
||||
using File_Watcher.Models;
|
||||
using ShellProgressBar;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO.Compression;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using View_by_Distance.Metadata.Models;
|
||||
using View_by_Distance.Metadata.Models.Stateless;
|
||||
using View_by_Distance.Shared.Models;
|
||||
using View_by_Distance.Shared.Models.Stateless;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class DeterministicHashCodeHelper
|
||||
{
|
||||
|
||||
private class Windows : IWindows, IDisposable
|
||||
{
|
||||
|
||||
private ProgressBar? _ProgressBar;
|
||||
private readonly ProgressBarOptions _ProgressBarOptions;
|
||||
|
||||
public int CurrentTick { get; internal set; }
|
||||
|
||||
public Windows() =>
|
||||
_ProgressBarOptions = new() { ProgressCharacter = '─', ProgressBarOnBottom = true, DisableBottomPercentage = true };
|
||||
|
||||
DeterministicHashCode IWindows.GetDeterministicHashCode(HttpClient httpClient, Uri uri) =>
|
||||
GetDeterministicHashCode(httpClient, uri);
|
||||
|
||||
DeterministicHashCode IWindows.GetDeterministicHashCode(HttpClient? httpClient, FilePath filePath)
|
||||
{
|
||||
DeterministicHashCode result;
|
||||
if (httpClient is not null)
|
||||
result = GetDeterministicHashCode(httpClient, new Uri(filePath.FullName));
|
||||
else
|
||||
{
|
||||
Stream stream = File.OpenRead(filePath.FullName);
|
||||
result = GetDeterministicHashCode(stream);
|
||||
stream.Dispose();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static DeterministicHashCode GetDeterministicHashCode(HttpClient httpClient, Uri uri)
|
||||
{
|
||||
DeterministicHashCode result;
|
||||
Stream stream = GetStream(httpClient, uri);
|
||||
result = GetDeterministicHashCode(stream);
|
||||
stream.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Stream GetStream(HttpClient httpClient, Uri uri)
|
||||
{
|
||||
Stream result;
|
||||
Task<Stream> task = httpClient.GetStreamAsync(uri);
|
||||
task.Wait();
|
||||
result = task.Result;
|
||||
return result;
|
||||
}
|
||||
|
||||
private static DeterministicHashCode GetDeterministicHashCode(Stream stream)
|
||||
{
|
||||
DeterministicHashCode result;
|
||||
int? id;
|
||||
int? width;
|
||||
int? height;
|
||||
try
|
||||
{
|
||||
#pragma warning disable CA1416
|
||||
using Image image = Image.FromStream(stream);
|
||||
width = image.Width;
|
||||
height = image.Height;
|
||||
using Bitmap bitmap = new(image);
|
||||
Rectangle rectangle = new(0, 0, image.Width, image.Height);
|
||||
BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, bitmap.PixelFormat);
|
||||
IntPtr intPtr = bitmapData.Scan0;
|
||||
int length = bitmapData.Stride * bitmap.Height;
|
||||
byte[] bytes = new byte[length];
|
||||
Marshal.Copy(intPtr, bytes, 0, length);
|
||||
bitmap.UnlockBits(bitmapData);
|
||||
#pragma warning restore CA1416
|
||||
id = IId.GetDeterministicHashCode(bytes);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
id = null;
|
||||
width = null;
|
||||
height = null;
|
||||
}
|
||||
result = new(height, id, width);
|
||||
return result;
|
||||
}
|
||||
|
||||
void IWindows.Tick() =>
|
||||
_ProgressBar?.Tick();
|
||||
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
_ProgressBar?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
void IWindows.ConstructProgressBar(int maxTicks, string message)
|
||||
{
|
||||
_ProgressBar?.Dispose();
|
||||
_ProgressBar = new(maxTicks, message, _ProgressBarOptions);
|
||||
}
|
||||
|
||||
ReadOnlyCollection<string> IWindows.ConvertAndGetFastForwardMovingPictureExpertsGroupFiles(ResultSettings resultSettings, HttpClient? httpClient, FilePath filePath)
|
||||
{
|
||||
List<string> results = [];
|
||||
bool isValidVideoFormatExtensions = resultSettings.ValidVideoFormatExtensions.Contains(filePath.ExtensionLowered);
|
||||
if (isValidVideoFormatExtensions)
|
||||
{
|
||||
bool check;
|
||||
if (httpClient is not null)
|
||||
DownloadFile(httpClient, filePath);
|
||||
try
|
||||
{
|
||||
CommandTask<CommandResult> commandTask = Cli.Wrap("L:/Git/ffmpeg-2024-10-02-git-358fdf3083-full_build/bin/ffmpeg.exe")
|
||||
.WithArguments(["-i", filePath.FullName, "-vf", "select=eq(n\\,0)", "-q:v", "1", $"{filePath.Name}-%4d.jpg"])
|
||||
.WithWorkingDirectory(filePath.DirectoryFullPath)
|
||||
.ExecuteAsync();
|
||||
commandTask.Task.Wait();
|
||||
check = true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
check = false;
|
||||
}
|
||||
if (check)
|
||||
{
|
||||
results.AddRange(Directory.GetFiles(filePath.DirectoryFullPath, $"{filePath.Name}-*.jpg", SearchOption.TopDirectoryOnly));
|
||||
if (results.Count == 0)
|
||||
throw new Exception();
|
||||
File.SetCreationTime(results[0], new(filePath.CreationTicks));
|
||||
File.SetLastWriteTime(results[0], new(filePath.LastWriteTicks));
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
return results.AsReadOnly();
|
||||
}
|
||||
|
||||
private static void DownloadFile(HttpClient httpClient, FilePath filePath)
|
||||
{
|
||||
FileStream fileStream = new(filePath.FullName, FileMode.Truncate);
|
||||
Task<HttpResponseMessage> httpResponseMessage = httpClient.GetAsync(filePath.FullName);
|
||||
httpResponseMessage.Wait();
|
||||
Task task = httpResponseMessage.Result.Content.CopyToAsync(fileStream);
|
||||
task.Wait();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal static bool WindowsWork(AppSettings appSettings, ILogger<Worker>? logger)
|
||||
{
|
||||
string json;
|
||||
string jsonFile;
|
||||
string sourceDirectory;
|
||||
List<string> check = [];
|
||||
string archiveEntryFile;
|
||||
long ticks = DateTime.Now.Ticks;
|
||||
ReadOnlyCollection<FirstPass> collection;
|
||||
string rootDirectory = Path.GetFullPath(appSettings.ResultSettings.RootDirectory);
|
||||
if (!Directory.Exists(rootDirectory))
|
||||
_ = Directory.CreateDirectory(rootDirectory);
|
||||
string[] zipFiles = Directory.GetFiles(rootDirectory, "*.zip", SearchOption.TopDirectoryOnly);
|
||||
if (zipFiles.Length > 0)
|
||||
_ = IPath.DeleteEmptyDirectories(rootDirectory);
|
||||
foreach (string zipFile in zipFiles)
|
||||
{
|
||||
check.Clear();
|
||||
sourceDirectory = zipFile[..^4];
|
||||
jsonFile = $"{sourceDirectory}.json";
|
||||
if (Directory.Exists(sourceDirectory) || File.Exists(jsonFile))
|
||||
continue;
|
||||
_ = Directory.CreateDirectory(sourceDirectory);
|
||||
using ZipArchive zip = ZipFile.Open(zipFile, ZipArchiveMode.Read);
|
||||
foreach (ZipArchiveEntry zipArchiveEntry in zip.Entries)
|
||||
{
|
||||
check.Add(zipArchiveEntry.Name);
|
||||
archiveEntryFile = Path.Combine(sourceDirectory, zipArchiveEntry.Name);
|
||||
zipArchiveEntry.ExtractToFile(archiveEntryFile);
|
||||
}
|
||||
collection = WindowsWork(logger, appSettings, ticks, sourceDirectory);
|
||||
if (check.Count == collection.Count)
|
||||
{
|
||||
json = JsonSerializer.Serialize(collection.ToList(), FirstPassCollectionSourceGenerationContext.Default.ListFirstPass);
|
||||
File.WriteAllText(jsonFile, json);
|
||||
}
|
||||
Directory.Delete(sourceDirectory, recursive: true);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<FirstPass> WindowsWork(ILogger<Worker>? logger, AppSettings appSettings, long ticks, string sourceDirectory)
|
||||
{
|
||||
ReadOnlyCollection<FirstPass> results;
|
||||
Windows windows = new();
|
||||
IWindows windowsInterface = windows;
|
||||
logger?.LogInformation("{Ticks} {RootDirectory}", ticks, sourceDirectory);
|
||||
A_Metadata metadata = new(appSettings.ResultSettings, appSettings.MetadataSettings);
|
||||
int appSettingsMaxDegreeOfParallelism = appSettings.DeterministicHashCodeConfiguration.MaxDegreeOfParallelism;
|
||||
ReadOnlyCollection<string> files = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories).AsReadOnly();
|
||||
if (files.Count > 0)
|
||||
_ = IPath.DeleteEmptyDirectories(sourceDirectory);
|
||||
int filesCount = appSettingsMaxDegreeOfParallelism == 1 ? files.Count : 123000;
|
||||
windowsInterface.ConstructProgressBar(filesCount, "EnumerateFiles load");
|
||||
if (appSettingsMaxDegreeOfParallelism == 1)
|
||||
results = WindowsSynchronousWork(logger, appSettings, windowsInterface, files, metadata);
|
||||
else
|
||||
results = WindowsAsynchronousWork(appSettings, windows, files, metadata, appSettingsMaxDegreeOfParallelism);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<FirstPass> WindowsSynchronousWork(ILogger<Worker>? logger, AppSettings appSettings, IWindows windows, IEnumerable<string> files, A_Metadata metadata)
|
||||
{
|
||||
List<FirstPass> results = [];
|
||||
int index = -1;
|
||||
ReadOnlyDictionary<string, List<FileHolder>> keyValuePairs = IMetadata.GetKeyValuePairs(files);
|
||||
foreach (KeyValuePair<string, List<FileHolder>> keyValuePair in keyValuePairs)
|
||||
{
|
||||
if (keyValuePair.Value.Count > 2)
|
||||
throw new NotSupportedException("Too many sidecar files!");
|
||||
index = WindowsSynchronousWork(logger, appSettings, windows, metadata, results, index, keyValuePair);
|
||||
}
|
||||
return results.AsReadOnly();
|
||||
}
|
||||
|
||||
private static int WindowsSynchronousWork(ILogger<Worker>? logger, AppSettings appSettings, IWindows windows, A_Metadata metadata, List<FirstPass> results, int index, KeyValuePair<string, List<FileHolder>> keyValuePair)
|
||||
{
|
||||
int result = index + 1;
|
||||
windows.Tick();
|
||||
FilePath filePath;
|
||||
FirstPass firstPass;
|
||||
string directoryName;
|
||||
ExifDirectory exifDirectory;
|
||||
HttpClient? httpClient = null;
|
||||
List<FileHolder> sidecarFiles;
|
||||
DeterministicHashCode deterministicHashCode;
|
||||
bool fastForwardMovingPictureExpertsGroupUsed;
|
||||
MinimumYearAndPathCombined minimumYearAndPathCombined;
|
||||
FilePath? fastForwardMovingPictureExpertsGroupFilePath;
|
||||
ReadOnlyCollection<string>? fastForwardMovingPictureExpertsGroupFiles;
|
||||
foreach (FileHolder fileHolder in keyValuePair.Value)
|
||||
{
|
||||
if (appSettings.DeterministicHashCodeConfiguration.SidecarExtensions.Contains(fileHolder.ExtensionLowered))
|
||||
continue;
|
||||
if (appSettings.ResultSettings.IgnoreExtensions.Contains(fileHolder.ExtensionLowered))
|
||||
continue;
|
||||
filePath = FilePath.Get(appSettings.ResultSettings, appSettings.MetadataSettings, fileHolder, result);
|
||||
if (filePath.Id is not null && (filePath.IsIntelligentIdFormat || filePath.SortOrder is not null))
|
||||
continue;
|
||||
if (filePath.Id is not null)
|
||||
{
|
||||
fastForwardMovingPictureExpertsGroupFiles = null;
|
||||
deterministicHashCode = new(null, filePath.Id, null);
|
||||
directoryName = Path.GetFileName(filePath.DirectoryFullPath);
|
||||
if (directoryName.EndsWith(filePath.Id.Value.ToString()))
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
fastForwardMovingPictureExpertsGroupFiles = windows.ConvertAndGetFastForwardMovingPictureExpertsGroupFiles(appSettings.ResultSettings, httpClient, filePath);
|
||||
fastForwardMovingPictureExpertsGroupFilePath = fastForwardMovingPictureExpertsGroupFiles.Count == 0 ? null : FilePath.Get(appSettings.ResultSettings, appSettings.MetadataSettings, FileHolder.Get(fastForwardMovingPictureExpertsGroupFiles[0]), result);
|
||||
deterministicHashCode = fastForwardMovingPictureExpertsGroupFilePath is null ? windows.GetDeterministicHashCode(httpClient, filePath) : windows.GetDeterministicHashCode(httpClient, fastForwardMovingPictureExpertsGroupFilePath);
|
||||
}
|
||||
sidecarFiles = [];
|
||||
filePath = FilePath.Get(filePath, deterministicHashCode);
|
||||
for (int i = 0; i < keyValuePair.Value.Count; i++)
|
||||
{
|
||||
if (keyValuePair.Value[i].ExtensionLowered == fileHolder.ExtensionLowered)
|
||||
continue;
|
||||
sidecarFiles.Add(keyValuePair.Value[i]);
|
||||
}
|
||||
try
|
||||
{ (minimumYearAndPathCombined, exifDirectory) = metadata.GetMetadataCollection(appSettings.ResultSettings, appSettings.MetadataSettings, httpClient, filePath); }
|
||||
catch (Exception)
|
||||
{
|
||||
logger?.LogWarning("<{filePath}>", filePath.FullName);
|
||||
continue;
|
||||
}
|
||||
fastForwardMovingPictureExpertsGroupUsed = fastForwardMovingPictureExpertsGroupFiles is not null && fastForwardMovingPictureExpertsGroupFiles.Count > 0;
|
||||
if (fastForwardMovingPictureExpertsGroupUsed && fastForwardMovingPictureExpertsGroupFiles is not null)
|
||||
{
|
||||
foreach (string fastForwardMovingPictureExpertsGroupFile in fastForwardMovingPictureExpertsGroupFiles)
|
||||
File.Delete(fastForwardMovingPictureExpertsGroupFile);
|
||||
}
|
||||
if (!fastForwardMovingPictureExpertsGroupUsed && appSettings.ResultSettings.ValidVideoFormatExtensions.Contains(filePath.ExtensionLowered))
|
||||
fastForwardMovingPictureExpertsGroupUsed = true;
|
||||
firstPass = new(exifDirectory, fastForwardMovingPictureExpertsGroupUsed, minimumYearAndPathCombined, sidecarFiles.ToArray());
|
||||
results.Add(firstPass);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<FirstPass> WindowsAsynchronousWork(AppSettings appSettings, Windows windows, ReadOnlyCollection<string> files, A_Metadata metadata, int appSettingsMaxDegreeOfParallelism)
|
||||
{
|
||||
List<FirstPass> results = [];
|
||||
FirstPass firstPass;
|
||||
List<string> distinct = [];
|
||||
List<MetadataGroup> metadataGroups = [];
|
||||
ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = appSettingsMaxDegreeOfParallelism };
|
||||
files.AsParallel().ForAll(IMetadata.SetExifDirectoryCollection(windows, appSettings.ResultSettings, appSettings.MetadataSettings, metadata, distinct, metadataGroups));
|
||||
if (windows?.CurrentTick != results.Count)
|
||||
throw new NotSupportedException();
|
||||
foreach (MetadataGroup metadataGroup in metadataGroups)
|
||||
{
|
||||
if (metadataGroup.FastForwardMovingPictureExpertsGroupUsed || !appSettings.ResultSettings.ValidVideoFormatExtensions.Contains(metadataGroup.FilePath.ExtensionLowered))
|
||||
firstPass = new(metadataGroup.ExifDirectory, metadataGroup.FastForwardMovingPictureExpertsGroupUsed, metadataGroup.MinimumYearAndPathCombined, metadataGroup.SidecarFiles.ToArray());
|
||||
else
|
||||
firstPass = new(metadataGroup.ExifDirectory, FastForwardMovingPictureExpertsGroupUsed: true, metadataGroup.MinimumYearAndPathCombined, metadataGroup.SidecarFiles.ToArray());
|
||||
results.Add(firstPass);
|
||||
}
|
||||
return results.AsReadOnly();
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<NginxFileSystem>? GetRecursiveCollection(HttpClient httpClient, string host, string page)
|
||||
{
|
||||
List<NginxFileSystem>? results;
|
||||
Uri uri = new($"http://{host}/{page}");
|
||||
string format = NginxFileSystem.GetFormat();
|
||||
TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local;
|
||||
Task<HttpResponseMessage> taskHttpResponseMessage = httpClient.GetAsync(uri);
|
||||
taskHttpResponseMessage.Wait();
|
||||
if (!taskHttpResponseMessage.Result.IsSuccessStatusCode)
|
||||
results = null;
|
||||
else
|
||||
{
|
||||
Task<string> taskString = taskHttpResponseMessage.Result.Content.ReadAsStringAsync();
|
||||
taskString.Wait();
|
||||
NginxFileSystem[]? nginxFileSystems = JsonSerializer.Deserialize(taskString.Result, NginxFileSystemCollectionSourceGenerationContext.Default.NginxFileSystemArray);
|
||||
if (nginxFileSystems is null)
|
||||
results = null;
|
||||
else
|
||||
{
|
||||
results = [];
|
||||
NginxFileSystem nginxFileSystem;
|
||||
ReadOnlyCollection<NginxFileSystem>? directory;
|
||||
for (int i = 0; i < nginxFileSystems.Length; i++)
|
||||
{
|
||||
nginxFileSystem = NginxFileSystem.Get(format, timeZoneInfo, uri, nginxFileSystems[i]);
|
||||
if (nginxFileSystem.Type == "file")
|
||||
results.Add(nginxFileSystem);
|
||||
else
|
||||
{
|
||||
directory = GetRecursiveCollection(httpClient, host, $"{page}/{nginxFileSystem.Name}");
|
||||
if (directory is null)
|
||||
continue;
|
||||
results.AddRange(directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return results?.AsReadOnly();
|
||||
}
|
||||
|
||||
}
|
178
Helpers/EDA/Common.cs
Normal file
178
Helpers/EDA/Common.cs
Normal file
@ -0,0 +1,178 @@
|
||||
using System.Text;
|
||||
|
||||
namespace File_Watcher.Helpers.EDA;
|
||||
|
||||
[Serializable]
|
||||
public class Common
|
||||
{
|
||||
|
||||
public string? ConfigurationProductiveState { get; set; }
|
||||
public string? ConfigurationState { get; set; }
|
||||
public string? ContainerName { get; set; }
|
||||
public ModuleInstanceTypeName? ObjectType { get; set; }
|
||||
public string? UnitName { get; set; }
|
||||
//
|
||||
public string Filename { get; set; }
|
||||
public string StartTimeFormat { get; set; }
|
||||
public string[] StoragePaths { get; set; }
|
||||
//
|
||||
public List<string[]> GeneralTriggers { get; set; }
|
||||
public List<string[]> LogisticsAttributes { get; set; }
|
||||
public List<string[]> LogisticsColumns { get; set; }
|
||||
public string LogisticsEquipmentAlias { get; set; }
|
||||
public List<string?[]> LogisticsTriggers { get; set; }
|
||||
public Dictionary<int, List<string[]>> LogisticsTriggersCallDefinitionAttributes { get; set; }
|
||||
public Dictionary<int, string[]> LogisticsTriggersKeysKeyMapping { get; set; }
|
||||
public List<string?[]> Parameters { get; set; }
|
||||
public string ParametersAsCsv { get; set; }
|
||||
public string Source { get; set; }
|
||||
public List<string[]> StartTriggersDCP { get; set; }
|
||||
public List<string[]> StopTriggersDCP { get; set; }
|
||||
|
||||
[Obsolete("Only for DeserializeObject")]
|
||||
public Common()
|
||||
{
|
||||
Parameters = [];
|
||||
ObjectType = null;
|
||||
StoragePaths = [];
|
||||
GeneralTriggers = [];
|
||||
StopTriggersDCP = [];
|
||||
LogisticsColumns = [];
|
||||
Source = string.Empty;
|
||||
StartTriggersDCP = [];
|
||||
LogisticsTriggers = [];
|
||||
Filename = string.Empty;
|
||||
UnitName = string.Empty;
|
||||
LogisticsAttributes = [];
|
||||
ContainerName = string.Empty;
|
||||
ParametersAsCsv = string.Empty;
|
||||
StartTimeFormat = string.Empty;
|
||||
ConfigurationState = string.Empty;
|
||||
LogisticsTriggersKeysKeyMapping = [];
|
||||
LogisticsEquipmentAlias = string.Empty;
|
||||
ConfigurationProductiveState = string.Empty;
|
||||
LogisticsTriggersCallDefinitionAttributes = [];
|
||||
}
|
||||
|
||||
public Common(ModuleInstanceTypeName objectType, object unitName, object containerName, object configurationState, object configurationProductiveState)
|
||||
{
|
||||
Parameters = [];
|
||||
StoragePaths = [];
|
||||
GeneralTriggers = [];
|
||||
StopTriggersDCP = [];
|
||||
LogisticsColumns = [];
|
||||
Source = string.Empty;
|
||||
StartTriggersDCP = [];
|
||||
LogisticsTriggers = [];
|
||||
Filename = string.Empty;
|
||||
ObjectType = objectType;
|
||||
LogisticsAttributes = [];
|
||||
ParametersAsCsv = string.Empty;
|
||||
StartTimeFormat = string.Empty;
|
||||
UnitName = unitName.ToString();
|
||||
LogisticsTriggersKeysKeyMapping = [];
|
||||
LogisticsEquipmentAlias = string.Empty;
|
||||
ContainerName = containerName.ToString();
|
||||
LogisticsTriggersCallDefinitionAttributes = [];
|
||||
ConfigurationState = configurationState.ToString();
|
||||
ConfigurationProductiveState = configurationProductiveState.ToString();
|
||||
}
|
||||
|
||||
public void Update(PDSFConfiguration configuration)
|
||||
{
|
||||
if (configuration.Settings.StoragePaths is null)
|
||||
StoragePaths = [];
|
||||
else
|
||||
StoragePaths = configuration.Settings.StoragePaths;
|
||||
StartTimeFormat = configuration.Settings.StartTimeFormat;
|
||||
Filename = configuration.Settings.Filename;
|
||||
//
|
||||
Source = configuration.DataCollection.Source;
|
||||
LogisticsEquipmentAlias = configuration.DataCollection.Logistics.EquipmentAlias;
|
||||
//if (LogisticsEquipmentAlias == "R47-PLC")
|
||||
//{ }
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsAttribute item in from l in configuration.DataCollection.Logistics.Attributes orderby l.Use descending, l.Order select l)
|
||||
LogisticsAttributes.Add([item.Use.ToString(), item.Order.ToString("000"), item.Key, item.Placeholder]);
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsColumn item in configuration.DataCollection.Logistics.Columns)
|
||||
LogisticsColumns.Add([item.ID.ToString(), item.Prefix]);
|
||||
foreach (PDSFConfigurationDataCollectionParameter1 item in from l in configuration.DataCollection.VirtualParameters orderby l.Use descending, l.Order select l)
|
||||
{
|
||||
if (item?.Conditions is null)
|
||||
continue;
|
||||
if (string.IsNullOrEmpty(item.Alias) && !string.IsNullOrEmpty(item.Conditions.ConditionModel?.Name))
|
||||
{
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, string.Empty, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, string.Empty, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
}
|
||||
foreach (PDSFConfigurationDataCollectionParameter item in from l in configuration.DataCollection.Parameters orderby l.Use descending, l.Order select l)
|
||||
{
|
||||
if (string.IsNullOrEmpty(item.Alias) && !string.IsNullOrEmpty(item.Conditions?.ConditionModel?.Name))
|
||||
{
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, string.Empty, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (item is null)
|
||||
continue;
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, string.Empty, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
}
|
||||
Parameters = (from l in Parameters orderby l[0] descending, l[1] select l).ToList();
|
||||
StringBuilder text = new();
|
||||
//text.AppendLine("\"AliasName\";\"Condition\";\"EventId\";\"ExceptionId\";\"Formula\";\"HardwareId\";\"OrderId\";\"ParameterName\";\"Remark\";\"ReportName\";\"SourceId\";\"Use\"");
|
||||
//"Test";"";"";"";"";"";"1";"MICROSCOPE01/MET08MESMICROSCOPE/Test";"";"MICROSCOPE01/MET08MESMICROSCOPE/FileRead";"";"True""
|
||||
_ = text.AppendLine("\"Use\";\"OrderId\";\"ReportName\";\"ParameterName\";\"AliasName\";\"HardwareId\";\"Remark\";\"Formula\"");
|
||||
foreach (string?[] parameter in Parameters)
|
||||
{
|
||||
for (int i = 0; i < 7; i++)
|
||||
_ = text.Append('"').Append(parameter[i]).Append("\";");
|
||||
_ = text.Remove(text.Length - 1, 1);
|
||||
_ = text.AppendLine();
|
||||
}
|
||||
ParametersAsCsv = text.ToString();
|
||||
foreach (PDSFConfigurationDataCollectionGeneralTriggers item in configuration.DataCollection.GeneralTriggers)
|
||||
{
|
||||
foreach (PDSFConfigurationDataCollectionGeneralTriggersVariableModel gv in item.GlobalVariables)
|
||||
GeneralTriggers.Add([item.Name, gv.Name, gv.ParameterName, gv.Formula]);
|
||||
}
|
||||
{
|
||||
PDSFConfigurationDataCollectionStartTriggersDCP item = configuration.DataCollection.StartTriggers.DCP;
|
||||
if (item is not null)
|
||||
StartTriggersDCP.Add([item.Name, item.Rule, item.ResolveGlobalVariableBeforeTrigger.ToString()]);
|
||||
}
|
||||
if (configuration.DataCollection.Logistics.Triggers.UpdateTrigger is not null)
|
||||
{
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsTriggersUpdateTriggerLogisticRequest item in configuration.DataCollection.Logistics.Triggers.UpdateTrigger.LogisticRequest)
|
||||
{
|
||||
LogisticsTriggers.Add([item.Name.ToString(), item.LogisticsColumn.Fixed.ToString(), item.Rule, item.Keys.Scenario, item.Keys.DefaultJobIndex.ToString(), item.Keys.DefaultCarrierIndex.ToString(), item.Keys.DefaultSlotIndex.ToString(), item.DataPool.ToString()]);
|
||||
if (item.Keys.KeyMapping is not null)
|
||||
LogisticsTriggersKeysKeyMapping.Add(item.Name, [item.Keys.KeyMapping.KeyName, item.Keys.KeyMapping.ParameterName, item.Keys.KeyMapping.Formula]);
|
||||
LogisticsTriggersCallDefinitionAttributes.Add(item.Name, []);
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsTriggersUpdateTriggerLogisticRequestCallDefinitionLogisticCallDefinitionAttribute att in item.CallDefinition.Attributes)
|
||||
LogisticsTriggersCallDefinitionAttributes[item.Name].Add([att.LogisticsKey, att.Source, att.MappedParameterName, att.Formula]);
|
||||
}
|
||||
}
|
||||
{
|
||||
PDSFConfigurationDataCollectionStopTriggersDCP item = configuration.DataCollection.StopTriggers.DCP;
|
||||
if (item is not null)
|
||||
StopTriggersDCP.Add([item.Name, item.Rule, item.ResolveGlobalVariableBeforeTrigger.ToString(), item.ResetGlobalVariablesAfterTrigger.ToString()]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
457
Helpers/EDA/DCP.cs
Normal file
457
Helpers/EDA/DCP.cs
Normal file
@ -0,0 +1,457 @@
|
||||
using System.Dynamic;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace File_Watcher.Helpers.EDA;
|
||||
|
||||
public class DCP
|
||||
{
|
||||
|
||||
internal static string GetEdaObjectToHtml(string edaObjectFile, Common common)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
|
||||
_ = result.AppendLine("<!DOCTYPE html>");
|
||||
_ = result.AppendLine("<html lang=\"en\">");
|
||||
_ = result.AppendLine("<head>");
|
||||
_ = result.AppendLine("<style>table, th, td{border:1px solid black;} td{padding:2px}</style>");
|
||||
_ = result.Append("<title>").Append(title).AppendLine("</title>");
|
||||
_ = result.AppendLine("</head>");
|
||||
_ = result.AppendLine("<body>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Unit Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Container Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Configuration State").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Configuration Productive State").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("LogisticsEquipmentAlias").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("StoragePath(s)").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("StartTimeFormat").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Filename").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<td nowrap>").Append(common.UnitName).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.ContainerName).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.ConfigurationState).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.ConfigurationProductiveState).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.LogisticsEquipmentAlias).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.Source).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(string.Join("</br >", common.StoragePaths)).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.StartTimeFormat).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.Filename).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Key").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Placeholder").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.LogisticsAttributes)
|
||||
{
|
||||
if (item.Length > 2 && !item[2].StartsWith("Z_"))
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("ID").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Prefix").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.LogisticsColumns)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("FullName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Alias").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("HardWareId").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Description").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Virtual").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Column#").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string?[] item in common.Parameters)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string? value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Parent Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.GeneralTriggers)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.StartTriggersDCP)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Fixed").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Scenario").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DefaultJobIndex").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DefaultCarrierIndex").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DefaultSlotIndex").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DataPool").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string?[] item in common.LogisticsTriggers)
|
||||
{
|
||||
if (item is null)
|
||||
continue;
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string? value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("<td>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("KeyName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (KeyValuePair<int, string[]> keyValuePair in common.LogisticsTriggersKeysKeyMapping)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in keyValuePair.Value)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("</td>");
|
||||
_ = result.AppendLine("<td>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("LogisticsKey").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("MappedParameterName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (KeyValuePair<int, List<string[]>> keyValuePair in common.LogisticsTriggersCallDefinitionAttributes)
|
||||
{
|
||||
foreach (string[] values in keyValuePair.Value)
|
||||
{
|
||||
if (values.Length > 0 && !values[0].StartsWith("Z_"))
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in values)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ResetGlobalVariablesAfterTrigger").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.StopTriggersDCP)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("</body>");
|
||||
_ = result.AppendLine("</html>");
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
private static string? ReplaceNull(object @object)
|
||||
{
|
||||
if (@object is null)
|
||||
return string.Empty;
|
||||
else
|
||||
return @object.ToString();
|
||||
}
|
||||
|
||||
private static void TextResolveEntry(StringBuilder result, dynamic expandoObject, int level, string super, int? i, bool group)
|
||||
{
|
||||
level += 1;
|
||||
foreach (dynamic entry in expandoObject)
|
||||
{
|
||||
#pragma warning disable IL2026, IL3050
|
||||
if (entry.Value is ExpandoObject)
|
||||
TextResolveEntry(result, entry.Value, level, string.Concat(super, " : ", entry.Key), i, group);
|
||||
else
|
||||
{
|
||||
if (entry.Value is not ICollection<object>)
|
||||
{
|
||||
if (i is null)
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("--->").AppendLine(ReplaceNull(entry.Value));
|
||||
else
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!group)
|
||||
{
|
||||
for (i = 0; i.Value < entry.Value.Count; i++)
|
||||
{
|
||||
if (entry.Value[i.Value] is ExpandoObject)
|
||||
TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
|
||||
else
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (i = 0; i.Value < entry.Value.Count; i++)
|
||||
{
|
||||
if (entry.Value[i.Value] is not ExpandoObject)
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
|
||||
}
|
||||
for (i = 0; i.Value < entry.Value.Count; i++)
|
||||
{
|
||||
if (entry.Value[i.Value] is ExpandoObject)
|
||||
TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
|
||||
}
|
||||
}
|
||||
i = null;
|
||||
}
|
||||
}
|
||||
#pragma warning restore IL2026, IL3050
|
||||
}
|
||||
level -= 1;
|
||||
if (level == 0)
|
||||
{ }
|
||||
}
|
||||
|
||||
internal static string GetText(string edaObjectFile, Common common, string json)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
if (result.Length > 0) //Skipping because System.Text.Json changed the way Expando works
|
||||
{
|
||||
#pragma warning disable IL2026, IL3050
|
||||
string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
|
||||
dynamic? expandoObject = JsonSerializer.Deserialize<ExpandoObject>(json);
|
||||
_ = result.AppendLine(title);
|
||||
_ = result.AppendLine("Loop -> \"Normal\"");
|
||||
_ = result.AppendLine(edaObjectFile);
|
||||
_ = result.AppendLine();
|
||||
TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: false);
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine(title);
|
||||
_ = result.AppendLine("Loop -> \"Grouped\"");
|
||||
_ = result.AppendLine(edaObjectFile);
|
||||
_ = result.AppendLine();
|
||||
TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: true);
|
||||
#pragma warning restore IL2026, IL3050
|
||||
}
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
internal static string GetEdaObjectToDMSGridFormat(string edaObjectFile, Common common, bool useAlias)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
if (string.IsNullOrEmpty(edaObjectFile))
|
||||
{ }
|
||||
string? value;
|
||||
string[] segments;
|
||||
int? recordStart = null;
|
||||
bool hasRecordStart = false;
|
||||
string name = string.Concat(common.LogisticsEquipmentAlias, "_", common.ContainerName);
|
||||
_ = result.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
|
||||
_ = result.Append("<Format Name=\"").Append(name).Append("\">").AppendLine();
|
||||
_ = result.AppendLine(" <General RecordStart=\"\" RecordLength=\"0\" ReadCommand=\"\" DecimalSeparator=\".\">");
|
||||
_ = result.AppendLine(" <RecordTerminator><13><10></RecordTerminator>");
|
||||
_ = result.AppendLine(" <ColumnSeparator><9></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
2502
Helpers/EDA/EDA - A.cs
Normal file
File diff suppressed because it is too large
Load Diff
6
Helpers/EDA/ModuleInstanceTypeName.cs
Normal file
6
Helpers/EDA/ModuleInstanceTypeName.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace File_Watcher.Helpers.EDA;
|
||||
|
||||
public enum ModuleInstanceTypeName
|
||||
{
|
||||
Pdsf
|
||||
}
|
116
Helpers/HelperCamstarOracle.cs
Normal file
116
Helpers/HelperCamstarOracle.cs
Normal file
@ -0,0 +1,116 @@
|
||||
using File_Watcher.Infineon.Monitoring.MonA;
|
||||
using File_Watcher.Models;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperCamstarOracle
|
||||
{
|
||||
|
||||
private static IMonIn? _MonIn;
|
||||
private static int? _LastValue;
|
||||
private static Calendar? _Calendar;
|
||||
private static DateTime? _LastUpload;
|
||||
|
||||
internal static void Heartbeat(AppSettings appSettings, IHttpClientFactory httpClientFactory, ILogger<Worker> logger, State state, CancellationToken cancellationToken)
|
||||
{
|
||||
_MonIn ??= MonIn.GetInstance(httpClientFactory);
|
||||
CamstarOracleConfiguration camstarOracleConfiguration = appSettings.CamstarOracleConfiguration;
|
||||
Task<HttpResponseMessage> httpResponseMessage = _MonIn.SendStatus(camstarOracleConfiguration.MonitorApplicationSite, camstarOracleConfiguration.MonitorApplicationResource, "Heartbeat", state);
|
||||
httpResponseMessage.Wait(cancellationToken);
|
||||
if (httpResponseMessage.Result.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
throw new Exception(httpResponseMessage.Result.StatusCode.ToString());
|
||||
Task<string> body = httpResponseMessage.Result.Content.ReadAsStringAsync(cancellationToken);
|
||||
body.Wait(cancellationToken);
|
||||
logger.LogDebug(body.Result);
|
||||
}
|
||||
|
||||
#pragma warning disable CA1416
|
||||
|
||||
private static List<EventLogEntry> GetOracleEventLogEntries(CamstarOracleConfiguration camstarOracleConfiguration, DateTime dateTime, CancellationToken cancellationToken)
|
||||
{
|
||||
List<EventLogEntry> results = [];
|
||||
EventLog[] eventLogs = EventLog.GetEventLogs();
|
||||
long ticks = dateTime.AddMinutes(-camstarOracleConfiguration.RollingMinutes).Ticks;
|
||||
foreach (EventLog eventLog in eventLogs)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
if (!eventLog.Log.Contains(camstarOracleConfiguration.LogFilter))
|
||||
continue;
|
||||
foreach (object? item in eventLog.Entries)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
if (item is not EventLogEntry eventLogEntry)
|
||||
continue;
|
||||
if (eventLogEntry.TimeGenerated.Ticks < ticks)
|
||||
continue;
|
||||
if (!camstarOracleConfiguration.MessageFilters.Any(eventLogEntry.Message.Contains))
|
||||
continue;
|
||||
results.Add(eventLogEntry);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static List<(DateTime, string)> GetOracleEventLogEntryMessages(CamstarOracleConfiguration camstarOracleConfiguration, DateTime dateTime, CancellationToken cancellationToken)
|
||||
{
|
||||
List<(DateTime, string)> results = [];
|
||||
List<EventLogEntry> collection = GetOracleEventLogEntries(camstarOracleConfiguration, dateTime, cancellationToken);
|
||||
foreach (EventLogEntry eventLogEntry in collection)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
results.Add(new(eventLogEntry.TimeGenerated, eventLogEntry.Message));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static bool Check(AppSettings appSettings, ILogger<Worker> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_MonIn is null)
|
||||
throw new NullReferenceException(nameof(_MonIn));
|
||||
string directory;
|
||||
DateTime dateTime;
|
||||
string weekOfYear;
|
||||
string weekDirectory;
|
||||
string formattedDateTime;
|
||||
List<string> lines = [];
|
||||
_Calendar ??= new CultureInfo("en-US").Calendar;
|
||||
CamstarOracleConfiguration camstarOracleConfiguration = appSettings.CamstarOracleConfiguration;
|
||||
string performanceName = string.Concat(camstarOracleConfiguration.MonitorApplicationResource, "_Count");
|
||||
lines.Clear();
|
||||
dateTime = DateTime.Now;
|
||||
weekOfYear = _Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
|
||||
weekDirectory = $"{dateTime:yyyy}_Week_{weekOfYear}{@"\"}{dateTime:yyyy-MM-dd}";
|
||||
directory = Path.Combine(camstarOracleConfiguration.Directory, weekDirectory);
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
|
||||
List<(DateTime, string)> collection = GetOracleEventLogEntryMessages(camstarOracleConfiguration, dateTime, cancellationToken);
|
||||
foreach ((DateTime timeGenerated, string message) in collection)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
formattedDateTime = timeGenerated.ToString(camstarOracleConfiguration.DateFormat);
|
||||
lines.Add($"{formattedDateTime}\t{message}");
|
||||
}
|
||||
File.WriteAllLines(Path.Combine(directory, $"{dateTime.Ticks}.tsv"), lines);
|
||||
if (_LastValue is null || _LastUpload is null || _LastValue.Value != lines.Count || new TimeSpan(dateTime.Ticks - _LastUpload.Value.Ticks).TotalMinutes > 5)
|
||||
{
|
||||
Task<HttpResponseMessage> httpResponseMessage = _MonIn.SendPerformanceMessage(camstarOracleConfiguration.MonitorApplicationSite, camstarOracleConfiguration.MonitorApplicationResource, performanceName, value: lines.Count, description: string.Empty);
|
||||
httpResponseMessage.Wait(cancellationToken);
|
||||
if (httpResponseMessage.Result.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
throw new Exception(httpResponseMessage.Result.StatusCode.ToString());
|
||||
Task<string> body = httpResponseMessage.Result.Content.ReadAsStringAsync(cancellationToken);
|
||||
body.Wait(cancellationToken);
|
||||
logger.LogDebug(body.Result);
|
||||
_LastUpload = DateTime.Now;
|
||||
_LastValue = lines.Count;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
123
Helpers/HelperCompass.cs
Normal file
123
Helpers/HelperCompass.cs
Normal file
@ -0,0 +1,123 @@
|
||||
using File_Watcher.Models;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal class HelperCompass
|
||||
{
|
||||
|
||||
private static bool _FirstRun = true;
|
||||
|
||||
private static void MapDrives(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
Process? process;
|
||||
string arguments;
|
||||
string decrypted;
|
||||
string? pathRoot;
|
||||
string[] segments;
|
||||
string standardError;
|
||||
string standardOutput;
|
||||
string fileName = "net";
|
||||
StringBuilder stringBuilder = new();
|
||||
if (appSettings.DriveConfiguration.Use is not null && appSettings.DriveConfiguration.Use.Value)
|
||||
{
|
||||
pathRoot = Path.GetPathRoot(appSettings.DriveConfiguration.Share);
|
||||
if (!string.IsNullOrEmpty(pathRoot) && !Directory.Exists(pathRoot))
|
||||
{
|
||||
if (string.IsNullOrEmpty(appSettings.DriveConfiguration.Password))
|
||||
decrypted = string.Empty;
|
||||
else
|
||||
decrypted = RijndaelEncryption.Decrypt(appSettings.DriveConfiguration.Password, appSettings.FileWatcherConfiguration.Company);
|
||||
arguments = $"use {appSettings.DriveConfiguration.Letter}: \"{appSettings.DriveConfiguration.Share}\" /p:yes /user:{appSettings.DriveConfiguration.User} {decrypted}";
|
||||
_ = stringBuilder.Clear();
|
||||
segments = arguments.Split(' ');
|
||||
for (int j = 0; j < segments.Length - 1; j++)
|
||||
_ = stringBuilder.Append(segments[j]).Append(' ');
|
||||
logger.LogInformation("// {output}", stringBuilder);
|
||||
ProcessStartInfo processStartInfo = new(fileName, arguments)
|
||||
{
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
try
|
||||
{
|
||||
process = Process.Start(processStartInfo);
|
||||
if (process is not null)
|
||||
{
|
||||
for (int j = 1; j < 45; j++)
|
||||
{
|
||||
_ = process.WaitForExit(1000);
|
||||
if (process.HasExited)
|
||||
break;
|
||||
}
|
||||
if (!process.HasExited)
|
||||
logger.LogError("// Never exited!");
|
||||
else
|
||||
{
|
||||
standardError = process.StandardError.ReadToEnd();
|
||||
standardOutput = process.StandardOutput.ReadToEnd();
|
||||
logger.LogInformation("// {error}{line}{line}// {output}", standardError, Environment.NewLine, Environment.NewLine, standardOutput);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error:");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<string> GetFiles(AppSettings appSettings, string directory)
|
||||
{
|
||||
ReadOnlyCollection<string> results;
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
results = new(Directory.GetFiles(directory, appSettings.CompassConfiguration.Pattern, SearchOption.TopDirectoryOnly));
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void CopyFiles(AppSettings appSettings, ReadOnlyCollection<string> files)
|
||||
{
|
||||
string checkFile;
|
||||
string triggerFile;
|
||||
foreach (string file in files)
|
||||
{
|
||||
checkFile = Path.Combine(appSettings.CompassConfiguration.Destination, Path.GetFileName(file));
|
||||
triggerFile = $"{checkFile}{appSettings.CompassConfiguration.TriggerAppendage}";
|
||||
if (File.Exists(checkFile))
|
||||
continue;
|
||||
if (File.Exists(triggerFile))
|
||||
continue;
|
||||
File.Copy(file, checkFile);
|
||||
File.WriteAllText(triggerFile, string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool CopyFile(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
if (_FirstRun)
|
||||
{
|
||||
_FirstRun = false;
|
||||
MapDrives(appSettings, logger);
|
||||
logger.LogCritical("MapDrives Done");
|
||||
}
|
||||
string directory;
|
||||
ReadOnlyCollection<string> files;
|
||||
DateTime[] dateTimes = [DateTime.Now, DateTime.Now.AddHours(-appSettings.CompassConfiguration.HoursBack)];
|
||||
foreach (DateTime dateTime in dateTimes)
|
||||
{
|
||||
directory = Path.Combine(appSettings.CompassConfiguration.Source, dateTime.ToString(appSettings.CompassConfiguration.YearPattern), dateTime.ToString(appSettings.CompassConfiguration.MonthPattern));
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
files = GetFiles(appSettings, directory);
|
||||
logger.LogDebug("Found {Files} file(s)", files.Count);
|
||||
CopyFiles(appSettings, files);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -7,8 +7,8 @@ internal static partial class HelperEAFLog
|
||||
|
||||
internal static bool DeleteFiles(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
string[] files = Directory.GetFiles(appSettings.WatchDirectory, appSettings.EAFLogConfiguration.SearchPattern, SearchOption.AllDirectories);
|
||||
logger.LogInformation("After {MillisecondsDelay} with search pattern '{SearchPattern}' found {files}", appSettings.MillisecondsDelay, appSettings.EAFLogConfiguration.SearchPattern, files.Length);
|
||||
string[] files = Directory.GetFiles(appSettings.FileWatcherConfiguration.WatchDirectory, appSettings.EAFLogConfiguration.SearchPattern, SearchOption.AllDirectories);
|
||||
logger.LogInformation("After {MillisecondsDelay} with search pattern '{SearchPattern}' found {files}", appSettings.FileWatcherConfiguration.MillisecondsDelay, appSettings.EAFLogConfiguration.SearchPattern, files.Length);
|
||||
foreach (string file in files)
|
||||
{
|
||||
if (file.EndsWith(".dll"))
|
||||
|
279
Helpers/HelperEDADatabase.cs
Normal file
279
Helpers/HelperEDADatabase.cs
Normal file
@ -0,0 +1,279 @@
|
||||
using File_Watcher.Helpers.EDA;
|
||||
using File_Watcher.Models;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Xml;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperEDADatabase
|
||||
{
|
||||
|
||||
private static string? _EDADataCollectionPlansLastRun;
|
||||
|
||||
private static Stream ToStream(string @this)
|
||||
{
|
||||
MemoryStream? stream = new();
|
||||
StreamWriter? writer = new(stream);
|
||||
writer.Write(@this);
|
||||
writer.Flush();
|
||||
stream.Position = 0;
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static T? ParseXML<T>(string @this, bool throwExceptions) where T : class
|
||||
{
|
||||
object? result = null;
|
||||
try
|
||||
{
|
||||
Stream stream = ToStream(@this.Trim());
|
||||
XmlReader? reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
|
||||
#pragma warning disable IL2026, IL2090
|
||||
XmlSerializer xmlSerializer = new(typeof(T), typeof(T).GetNestedTypes());
|
||||
result = xmlSerializer.Deserialize(reader);
|
||||
#pragma warning restore IL2026, IL2090
|
||||
stream.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (throwExceptions)
|
||||
throw;
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
|
||||
private static void EvaluateRows(string workingDirectory, Dictionary<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> rows, CancellationToken cancellationToken)
|
||||
{ // cSpell:disable
|
||||
// int moduleinstancetypename = 0;
|
||||
int unitname = 1;
|
||||
// int modulename = 2;
|
||||
int containername = 3;
|
||||
int configurationstate = 4;
|
||||
int configurationproductivestate = 5;
|
||||
// int containermodifiername = 6;
|
||||
int containermodifieddate = 7;
|
||||
int containerconfiguration = 8;
|
||||
int configurationmodifieddate = 9;
|
||||
// cSpell:enable
|
||||
string csv;
|
||||
string? xml;
|
||||
string json;
|
||||
string text;
|
||||
string html;
|
||||
Common common;
|
||||
string emptyAPC;
|
||||
string fileName;
|
||||
string? modifiedDate;
|
||||
string edaObjectFile;
|
||||
string goldDirectory;
|
||||
string replace = "$$$";
|
||||
string edaObjectDirectory;
|
||||
DateTime lastModifiedDate;
|
||||
string objectTypeDirectory;
|
||||
DateTime containerModifiedDate;
|
||||
PDSFConfiguration? configuration;
|
||||
DateTime configurationModifiedDate;
|
||||
JsonSerializerOptions jsonSerializerOptions = new() { WriteIndented = true };
|
||||
foreach (KeyValuePair<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> databaseElement in rows)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
emptyAPC = string.Concat(workingDirectory, @"\", databaseElement.Key, @"\EmptyAPC.xlsx");
|
||||
foreach (KeyValuePair<ModuleInstanceTypeName, List<List<object>>> tableNameElement in databaseElement.Value)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
objectTypeDirectory = string.Concat(workingDirectory, @"\", databaseElement.Key, @"\", tableNameElement.Key);
|
||||
foreach (List<object> rowItem in tableNameElement.Value)
|
||||
{ // cSpell:disable
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
// foreach (var item in rowItem)
|
||||
// Print(item.ToString());
|
||||
// if (!rowItem[containername].ToString().Contains("Plan_Pdsf_Health_Cp2Mg"))
|
||||
// if (!rowItem[unitname].ToString().Contains("HGCV1") || !rowItem[containername].ToString().Contains("Plan_Pdsf"))
|
||||
// continue;
|
||||
modifiedDate = rowItem[containermodifieddate].ToString();
|
||||
if (string.IsNullOrEmpty(modifiedDate))
|
||||
continue;
|
||||
containerModifiedDate = DateTime.Parse(modifiedDate);
|
||||
modifiedDate = rowItem[configurationmodifieddate].ToString();
|
||||
if (string.IsNullOrEmpty(modifiedDate))
|
||||
continue;
|
||||
configurationModifiedDate = DateTime.Parse(modifiedDate);
|
||||
if (containerModifiedDate < configurationModifiedDate)
|
||||
lastModifiedDate = configurationModifiedDate;
|
||||
else
|
||||
lastModifiedDate = containerModifiedDate;
|
||||
goldDirectory = string.Concat(objectTypeDirectory, @"\", rowItem[unitname], @"\", rowItem[containername], @"\Gold");
|
||||
if (!Directory.Exists(goldDirectory))
|
||||
_ = Directory.CreateDirectory(goldDirectory);
|
||||
edaObjectDirectory = string.Concat(objectTypeDirectory, @"\", rowItem[unitname], @"\", rowItem[containername], @"\", rowItem[configurationstate], @"\", rowItem[configurationproductivestate], @"\", lastModifiedDate.ToString("yyyy-MM-dd_"), new TimeSpan(lastModifiedDate.Ticks - new DateTime(lastModifiedDate.Year, lastModifiedDate.Month, lastModifiedDate.Day).Ticks).TotalSeconds);
|
||||
if (!Directory.Exists(edaObjectDirectory))
|
||||
_ = Directory.CreateDirectory(edaObjectDirectory);
|
||||
edaObjectFile = string.Concat(edaObjectDirectory, @"\", rowItem[unitname], " ", rowItem[containername], " - ", replace, " - ", rowItem[configurationstate].ToString(), " ", rowItem[configurationproductivestate].ToString());
|
||||
xml = rowItem[containerconfiguration].ToString();
|
||||
if (string.IsNullOrEmpty(xml))
|
||||
continue;
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Raw"), ".xml");
|
||||
File.WriteAllText(fileName, xml);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
common = new Common(ModuleInstanceTypeName.Pdsf, rowItem[unitname], rowItem[containername], rowItem[configurationstate], rowItem[configurationproductivestate]);
|
||||
configuration = ParseXML<PDSFConfiguration>(xml, throwExceptions: true);
|
||||
if (configuration is null)
|
||||
continue;
|
||||
// cSpell:enable
|
||||
common.Update(configuration);
|
||||
#pragma warning disable IL2026, IL3050
|
||||
json = JsonSerializer.Serialize(configuration, configuration.GetType(), jsonSerializerOptions);
|
||||
#pragma warning restore IL2026, IL3050
|
||||
if (common?.UnitName is null)
|
||||
continue;
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".csv");
|
||||
File.WriteAllText(fileName, common.ParametersAsCsv);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".json");
|
||||
File.WriteAllText(fileName, json);
|
||||
text = DCP.GetText(edaObjectFile, common, json);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".txt");
|
||||
File.WriteAllText(fileName, text);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
html = DCP.GetEdaObjectToHtml(edaObjectFile, common);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".html");
|
||||
File.WriteAllText(fileName, html);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
xml = DCP.GetEdaObjectToDMSGridFormat(edaObjectFile, common, useAlias: false);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "DMSGridFormat"), ".xml");
|
||||
File.WriteAllText(fileName, xml);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
xml = DCP.GetEdaObjectToDMSGridFormat(edaObjectFile, common, useAlias: true);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "DMSGridFormat - Alias"), ".xml");
|
||||
File.WriteAllText(fileName, xml);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
csv = DCP.GetEdaObjectToAPCParameter(edaObjectFile, common);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "APCParameter"), ".csv");
|
||||
File.WriteAllText(fileName, csv);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
csv = DCP.GetEdaObjectToAPCRunKeyNumber(edaObjectFile, common);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "APCRunKeyNumber"), ".csv");
|
||||
File.WriteAllText(fileName, csv);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "APC"), ".xlsx");
|
||||
if (File.Exists(emptyAPC) && !File.Exists(fileName))
|
||||
{
|
||||
File.Copy(emptyAPC, fileName);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
if (common.StoragePaths.Length == 0)
|
||||
continue;
|
||||
foreach (string? storagePath in common.StoragePaths)
|
||||
{
|
||||
if (string.IsNullOrEmpty(storagePath) || !Directory.Exists(Path.GetPathRoot(storagePath)))
|
||||
continue;
|
||||
if (Directory.Exists(storagePath))
|
||||
continue;
|
||||
_ = Directory.CreateDirectory(storagePath);
|
||||
}
|
||||
}
|
||||
try
|
||||
{ Directory.SetLastWriteTime(objectTypeDirectory, DateTime.Now); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void DataCollectionPlans(AppSettings appSettings, ILogger<Worker> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
int fieldCount;
|
||||
object @object;
|
||||
string? @string;
|
||||
List<object> row;
|
||||
StringBuilder sql = new();
|
||||
string objectTypeDirectory;
|
||||
#pragma warning disable IL3050
|
||||
Array objectTypes = Enum.GetValues(typeof(ModuleInstanceTypeName));
|
||||
#pragma warning restore IL3050
|
||||
Dictionary<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> rows = [];
|
||||
string decrypted = RijndaelEncryption.Decrypt(appSettings.EDADatabaseConfiguration.Password, appSettings.FileWatcherConfiguration.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)
|
||||
{
|
||||
DataCollectionPlans(appSettings, logger, cancellationToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -8,7 +8,7 @@ internal static partial class HelperEventLog
|
||||
|
||||
internal static bool ClearEventLogs(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
if (Directory.Exists(appSettings.WatchDirectory))
|
||||
if (Directory.Exists(appSettings.FileWatcherConfiguration.WatchDirectory))
|
||||
{
|
||||
#pragma warning disable CA1416
|
||||
using (EventLog eventLog = new("Security", Environment.MachineName))
|
||||
@ -26,7 +26,7 @@ internal static partial class HelperEventLog
|
||||
{ logger.LogInformation("Error: {logName} - {message}.", eventLog.LogDisplayName, ex.Message); }
|
||||
}
|
||||
#pragma warning restore CA1416
|
||||
logger.LogCritical("{Company}", appSettings.Company);
|
||||
logger.LogCritical("{Company}", appSettings.FileWatcherConfiguration.Company);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
40
Helpers/HelperISO.cs
Normal file
40
Helpers/HelperISO.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using DiscUtils.Iso9660;
|
||||
using File_Watcher.Models;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperISO
|
||||
{
|
||||
|
||||
private static void DirectoryToISO(ILogger<Worker> logger, string destinationDirectory, bool mapOnly, string directory)
|
||||
{
|
||||
byte[] bytes = [];
|
||||
string relativePath;
|
||||
string directoryName = Path.GetFileName(directory);
|
||||
CDBuilder builder = new() { UseJoliet = true, VolumeIdentifier = directoryName.Length < 25 ? directoryName : directoryName[..25] };
|
||||
IEnumerable<string> files = Directory.EnumerateFiles(directory, "*", new EnumerationOptions { IgnoreInaccessible = true, RecurseSubdirectories = true });
|
||||
foreach (string file in files)
|
||||
{
|
||||
relativePath = Path.GetRelativePath(directory, file).Replace(';', '_');
|
||||
if (!mapOnly)
|
||||
_ = builder.AddFile(relativePath, file);
|
||||
else
|
||||
_ = builder.AddFile(relativePath, bytes);
|
||||
}
|
||||
logger.LogInformation(destinationDirectory);
|
||||
builder.Build(Path.Combine(destinationDirectory, $"{directoryName}.iso"));
|
||||
logger.LogInformation(directoryName);
|
||||
}
|
||||
|
||||
internal static bool DirectoryToISO(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
IsoConfiguration isoConfiguration = appSettings.IsoConfiguration;
|
||||
logger.LogInformation(isoConfiguration.SourceDirectory);
|
||||
bool mapOnly = isoConfiguration.SourceDirectory.Length == 2;
|
||||
if (!Directory.Exists(isoConfiguration.DestinationDirectory))
|
||||
_ = Directory.CreateDirectory(isoConfiguration.DestinationDirectory);
|
||||
DirectoryToISO(logger, isoConfiguration.DestinationDirectory, mapOnly, isoConfiguration.SourceDirectory);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
45
Helpers/HelperInfinityQS.cs
Normal file
45
Helpers/HelperInfinityQS.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using File_Watcher.Models;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperInfinityQS
|
||||
{
|
||||
|
||||
private static void KillExisting(string processName)
|
||||
{
|
||||
Process[] processes = Process.GetProcessesByName(processName);
|
||||
foreach (Process process in processes)
|
||||
{
|
||||
try
|
||||
{ process.Kill(); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
private static void RunMI()
|
||||
{
|
||||
#pragma warning disable CA1416
|
||||
string processName = "iispcmi.exe";
|
||||
KillExisting(processName);
|
||||
ProcessStartInfo processStartInfo = new(processName)
|
||||
{
|
||||
Domain = "Infineon",
|
||||
UseShellExecute = false,
|
||||
UserName = "ecfisysadmin",
|
||||
PasswordInClearText = "j(1(P%xB=g}3w9db",
|
||||
WorkingDirectory = "C:/Program Files (x86)/InfinityQS International/ProFicient/Applications"
|
||||
};
|
||||
TimeSpan timeSpan = new(DateTime.Now.AddDays(7).Ticks - DateTime.Now.Ticks);
|
||||
Process process = Process.Start(processStartInfo) ?? throw new NullReferenceException(nameof(Process));
|
||||
_ = process.WaitForExit((int)timeSpan.TotalMilliseconds);
|
||||
#pragma warning restore CA1416
|
||||
}
|
||||
|
||||
internal static bool Select(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
logger.LogInformation(appSettings.FileWatcherConfiguration.Company);
|
||||
RunMI();
|
||||
return true;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
|
153
Helpers/HelperNuget.cs
Normal file
153
Helpers/HelperNuget.cs
Normal file
@ -0,0 +1,153 @@
|
||||
using File_Watcher.Models;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal class HelperNuget
|
||||
{
|
||||
|
||||
private static DateTimeOffset? GetDateTimeOffset(string keyFileExtension, FileInfo fileInfo, FileInfo extractKeyFileInfo)
|
||||
{
|
||||
DateTimeOffset? dateTimeOffset = null;
|
||||
using ZipArchive zip = ZipFile.Open(fileInfo.FullName, ZipArchiveMode.Read);
|
||||
foreach (ZipArchiveEntry zipArchiveEntry in zip.Entries)
|
||||
{
|
||||
if (!zipArchiveEntry.Name.EndsWith(keyFileExtension))
|
||||
continue;
|
||||
dateTimeOffset = zipArchiveEntry.LastWriteTime;
|
||||
if (fileInfo.FullName[0] != '\\')
|
||||
{
|
||||
zipArchiveEntry.ExtractToFile(extractKeyFileInfo.FullName);
|
||||
File.SetCreationTime(extractKeyFileInfo.FullName, fileInfo.CreationTime);
|
||||
File.SetLastWriteTime(extractKeyFileInfo.FullName, dateTimeOffset.Value.LocalDateTime);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return dateTimeOffset;
|
||||
}
|
||||
|
||||
private static void SetLastWriteTimes(ILogger<Worker> logger, NugetConfiguration nugetConfiguration, FileInfo fileInfo, DateTimeOffset dateTimeOffset)
|
||||
{
|
||||
try
|
||||
{
|
||||
string[] files;
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.LocalDateTime);
|
||||
if (!string.IsNullOrEmpty(nugetConfiguration.KeyFileExtensionB))
|
||||
{
|
||||
if (fileInfo.DirectoryName is null)
|
||||
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
|
||||
files = Directory.GetFiles(fileInfo.DirectoryName, nugetConfiguration.KeyFileExtensionB, SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.LocalDateTime);
|
||||
}
|
||||
}
|
||||
if (!string.IsNullOrEmpty(nugetConfiguration.KeyFileExtensionC))
|
||||
{
|
||||
if (fileInfo.DirectoryName is null)
|
||||
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
|
||||
files = Directory.GetFiles(fileInfo.DirectoryName, nugetConfiguration.KeyFileExtensionC, SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.LocalDateTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
string checkFile;
|
||||
logger.LogInformation("<{fileInfo.FullName}> is invalid!", fileInfo.FullName);
|
||||
checkFile = string.Concat(fileInfo.FullName, ".err");
|
||||
for (int e = 0; e < short.MaxValue; e++)
|
||||
{
|
||||
if (!File.Exists(checkFile))
|
||||
break;
|
||||
checkFile = string.Concat(checkFile, e);
|
||||
}
|
||||
try
|
||||
{ File.Move(fileInfo.FullName, checkFile); }
|
||||
catch (Exception) { logger.LogInformation("<{fileInfo.FullName}> couldn't be moved!", fileInfo.FullName); }
|
||||
}
|
||||
}
|
||||
|
||||
private static void ExtractKeyFileAndSetDateFromZipEntry(ILogger<Worker> logger, NugetConfiguration nugetConfiguration, string[] zipFiles)
|
||||
{
|
||||
string[] files;
|
||||
FileInfo fileInfo;
|
||||
string? lowerName;
|
||||
FileInfo extractKeyFileInfo;
|
||||
foreach (string zipFile in zipFiles)
|
||||
{
|
||||
fileInfo = new(zipFile);
|
||||
if (fileInfo.DirectoryName is null)
|
||||
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
|
||||
lowerName = !nugetConfiguration.RenameToLower ? null : Path.Combine(fileInfo.DirectoryName, fileInfo.Name.ToLower());
|
||||
if (nugetConfiguration.RenameToLower && lowerName is not null && lowerName != fileInfo.FullName)
|
||||
{
|
||||
files = Directory.GetFiles(fileInfo.DirectoryName, $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}*", SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
File.Move(file, Path.Combine(fileInfo.DirectoryName, Path.GetFileName(file).ToLower()));
|
||||
fileInfo = new(lowerName);
|
||||
if (fileInfo.DirectoryName is null)
|
||||
throw new NullReferenceException(nameof(fileInfo.DirectoryName));
|
||||
}
|
||||
extractKeyFileInfo = new(Path.Combine(fileInfo.DirectoryName, $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}{nugetConfiguration.KeyFileExtension}"));
|
||||
if (extractKeyFileInfo.Exists)
|
||||
{
|
||||
if (extractKeyFileInfo.CreationTime.ToString("yyyy-MM-dd") == fileInfo.CreationTime.ToString("yyyy-MM-dd") && extractKeyFileInfo.LastWriteTime.ToString("yyyy-MM-dd") == fileInfo.LastWriteTime.ToString("yyyy-MM-dd"))
|
||||
continue;
|
||||
File.Delete(extractKeyFileInfo.FullName);
|
||||
}
|
||||
DateTimeOffset? dateTimeOffset = GetDateTimeOffset(nugetConfiguration.KeyFileExtension, fileInfo, extractKeyFileInfo);
|
||||
if (dateTimeOffset is null)
|
||||
continue;
|
||||
SetLastWriteTimes(logger, nugetConfiguration, fileInfo, dateTimeOffset.Value);
|
||||
}
|
||||
}
|
||||
|
||||
private static int CopyFiles(NugetConfiguration nugetConfiguration, string[] files)
|
||||
{
|
||||
int results = 0;
|
||||
FileInfo fileInfo;
|
||||
FileInfo checkFileInfo;
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
checkFileInfo = new(Path.Combine(nugetConfiguration.Destination, fileInfo.Name));
|
||||
if (!checkFileInfo.Exists || fileInfo.LastWriteTime != checkFileInfo.LastWriteTime || fileInfo.Length != checkFileInfo.Length)
|
||||
{
|
||||
File.Copy(fileInfo.FullName, checkFileInfo.FullName, overwrite: true);
|
||||
results++;
|
||||
}
|
||||
if (string.IsNullOrEmpty(nugetConfiguration.KeyFileExtension))
|
||||
continue;
|
||||
fileInfo = new(Path.ChangeExtension(file, nugetConfiguration.KeyFileExtension));
|
||||
checkFileInfo = new(Path.Combine(nugetConfiguration.Destination, Path.ChangeExtension(fileInfo.Name, nugetConfiguration.KeyFileExtension)));
|
||||
if (!checkFileInfo.Exists || fileInfo.LastWriteTime != checkFileInfo.LastWriteTime || fileInfo.Length != checkFileInfo.Length)
|
||||
File.Copy(fileInfo.FullName, checkFileInfo.FullName, overwrite: true);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static bool Sync(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
NugetConfiguration nugetConfiguration = appSettings.NugetConfiguration;
|
||||
if (!Directory.Exists(nugetConfiguration.Source))
|
||||
_ = Directory.CreateDirectory(nugetConfiguration.Source);
|
||||
if (!Directory.Exists(nugetConfiguration.Destination))
|
||||
_ = Directory.CreateDirectory(nugetConfiguration.Destination);
|
||||
string[] files = Directory.GetFiles(nugetConfiguration.Source, nugetConfiguration.SearchPattern, SearchOption.AllDirectories);
|
||||
logger.LogInformation("Found {Files} file(s)", files.Length);
|
||||
ExtractKeyFileAndSetDateFromZipEntry(logger, nugetConfiguration, files);
|
||||
logger.LogInformation("{Files} file(s) verified", files.Length);
|
||||
int filesCopied = CopyFiles(nugetConfiguration, files);
|
||||
logger.LogInformation("Copied {FilesCopied} file(s)", filesCopied);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
281
Helpers/HelperSerial.cs
Normal file
281
Helpers/HelperSerial.cs
Normal 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;
|
||||
}
|
||||
|
||||
}
|
@ -13,13 +13,14 @@ internal static partial class HelperStratus
|
||||
private static void TryMoveFile(AppSettings appSettings, string checkFile)
|
||||
{
|
||||
string line;
|
||||
string checkDirectory;
|
||||
string weekYearDirectory;
|
||||
List<string> collection = [];
|
||||
DateTime dateTime = DateTime.Now;
|
||||
FileInfo fileInfo = new(checkFile);
|
||||
Calendar calendar = new CultureInfo("en-US").Calendar;
|
||||
char start = appSettings.StratusConfiguration.FileDelimiterPattern[0];
|
||||
string[] lines = !File.Exists(checkFile) ? [] : File.ReadAllLines(checkFile);
|
||||
string weekOfYear = calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
|
||||
string[] lines = !fileInfo.Exists ? [] : File.ReadAllLines(checkFile);
|
||||
string weekOfYear = calendar.GetWeekOfYear(fileInfo.CreationTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
line = lines[i];
|
||||
@ -28,10 +29,11 @@ internal static partial class HelperStratus
|
||||
continue;
|
||||
if (!Regex.Match(line, appSettings.StratusConfiguration.FileDelimiterPattern).Success)
|
||||
continue;
|
||||
weekYearDirectory = Path.Combine(appSettings.WatchDirectory, $"{dateTime.Year}_Week_{weekOfYear}");
|
||||
if (!Directory.Exists(weekYearDirectory))
|
||||
_ = Directory.CreateDirectory(weekYearDirectory);
|
||||
File.WriteAllLines(Path.Combine(weekYearDirectory, $"{dateTime.Ticks}.txt"), collection);
|
||||
weekYearDirectory = Path.Combine(appSettings.FileWatcherConfiguration.WatchDirectory, $"{fileInfo.CreationTime.Year}_Week_{weekOfYear}");
|
||||
checkDirectory = Path.Combine(weekYearDirectory, fileInfo.CreationTime.ToString("yyyy-MM-dd"));
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
_ = Directory.CreateDirectory(checkDirectory);
|
||||
File.WriteAllLines(Path.Combine(checkDirectory, $"{fileInfo.CreationTime.Ticks}.txt"), collection);
|
||||
collection.Clear();
|
||||
for (int j = i + 1; j < lines.Length; j++)
|
||||
collection.Add(lines[j]);
|
||||
@ -41,15 +43,64 @@ internal static partial class HelperStratus
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryArchiveFilesFramework(string sourceDirectory, string pattern, string archiveDirectory, int days)
|
||||
{
|
||||
string checkFile;
|
||||
FileInfo fileInfo;
|
||||
string weekOfYear;
|
||||
string checkDirectory;
|
||||
string[] directorySegments;
|
||||
DateTime dateTime = DateTime.Now.AddDays(-days);
|
||||
Calendar calendar = new CultureInfo("en-US").Calendar;
|
||||
string[] sourceDirectorySegments = sourceDirectory.Split(Path.DirectorySeparatorChar);
|
||||
string[] files = Directory.GetFiles(sourceDirectory, pattern, SearchOption.AllDirectories);
|
||||
if (sourceDirectorySegments.Length < 2)
|
||||
throw new Exception("Can't be root drive!");
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new FileInfo(file);
|
||||
if (string.IsNullOrEmpty(fileInfo.DirectoryName) || fileInfo.LastWriteTime > dateTime)
|
||||
continue;
|
||||
directorySegments = fileInfo.DirectoryName.Split(Path.DirectorySeparatorChar);
|
||||
if (directorySegments.Length < sourceDirectorySegments.Length)
|
||||
continue;
|
||||
weekOfYear = $"{fileInfo.CreationTime.Year}_Week_{calendar.GetWeekOfYear(fileInfo.CreationTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
|
||||
checkDirectory = string.Concat(archiveDirectory, Path.DirectorySeparatorChar, weekOfYear);
|
||||
for (int i = sourceDirectorySegments.Length; i < directorySegments.Length; i++)
|
||||
checkDirectory = string.Concat(checkDirectory, Path.DirectorySeparatorChar, directorySegments[i]);
|
||||
checkDirectory = string.Concat(checkDirectory, Path.DirectorySeparatorChar, fileInfo.CreationTime.ToString("yyyy-MM-dd"));
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
_ = Directory.CreateDirectory(checkDirectory);
|
||||
checkFile = Path.Combine(checkDirectory, fileInfo.Name);
|
||||
if (File.Exists(checkFile))
|
||||
continue;
|
||||
File.Move(fileInfo.FullName, checkFile);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool MoveFile(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
string checkFile = Path.Combine(appSettings.WatchDirectory, appSettings.StratusConfiguration.WatchFile);
|
||||
// http://10.95.154.10:8081/2023_Week_45/2023-11-08/a.txt
|
||||
string checkFile = Path.Combine(appSettings.FileWatcherConfiguration.WatchDirectory, appSettings.StratusConfiguration.WatchFile);
|
||||
try
|
||||
{ TryMoveFile(appSettings, checkFile); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Inner loop error!");
|
||||
Thread.Sleep(appSettings.MillisecondsDelay * 5);
|
||||
Thread.Sleep(appSettings.FileWatcherConfiguration.MillisecondsDelay * 5);
|
||||
}
|
||||
Console.WriteLine("Hello");
|
||||
int days = appSettings.StratusConfiguration.Days;
|
||||
string pattern = appSettings.StratusConfiguration.FileDelimiterPattern;
|
||||
string sourceDirectory = appSettings.FileWatcherConfiguration.WatchDirectory;
|
||||
int millisecondsDelay = appSettings.FileWatcherConfiguration.MillisecondsDelay;
|
||||
string archiveDirectory = Path.GetFullPath(appSettings.StratusConfiguration.Destination);
|
||||
try
|
||||
{ TryArchiveFilesFramework(sourceDirectory, pattern, archiveDirectory, days); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Inner loop error!");
|
||||
Thread.Sleep(millisecondsDelay * 5);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
157
Helpers/HelperTCP.cs
Normal file
157
Helpers/HelperTCP.cs
Normal 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.GetFullPath(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(Path.Combine(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;
|
||||
}
|
||||
|
||||
}
|
@ -11,7 +11,7 @@ internal static partial class HelperWaferCounter
|
||||
string checkFile;
|
||||
FileInfo fileInfo;
|
||||
string checkDirectory;
|
||||
string[] directories = Directory.GetDirectories(appSettings.WatchDirectory, "*", SearchOption.TopDirectoryOnly);
|
||||
string[] directories = Directory.GetDirectories(appSettings.FileWatcherConfiguration.WatchDirectory, "*", SearchOption.TopDirectoryOnly);
|
||||
foreach (string directory in directories)
|
||||
{
|
||||
checkDirectory = !appSettings.WaferCounterConfiguration.MatchPath ? appSettings.WaferCounterConfiguration.Destination : Path.Combine(appSettings.WaferCounterConfiguration.Destination, Path.GetFileName(directory));
|
||||
@ -23,7 +23,7 @@ internal static partial class HelperWaferCounter
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (new TimeSpan(DateTime.Now.Ticks - fileInfo.LastWriteTime.Ticks).TotalMilliseconds < appSettings.MillisecondsDelay)
|
||||
if (new TimeSpan(DateTime.Now.Ticks - fileInfo.LastWriteTime.Ticks).TotalMilliseconds < appSettings.FileWatcherConfiguration.MillisecondsDelay)
|
||||
continue;
|
||||
checkFile = Path.Combine(checkDirectory, Path.GetFileName(file));
|
||||
if (File.Exists(checkFile))
|
||||
|
100
Helpers/RijndaelEncryption.cs
Normal file
100
Helpers/RijndaelEncryption.cs
Normal file
@ -0,0 +1,100 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
public static class RijndaelEncryption
|
||||
{ // cSpell:disable
|
||||
|
||||
/// <summary>
|
||||
/// Change the input key GUID when you use this code in your own program.
|
||||
/// Keep this input key very safe and prevent someone from decoding it some way!!
|
||||
/// Generated 2021-08-10
|
||||
/// </summary>
|
||||
internal const string _InputKey = "970CCEF6-4307-4F6A-9AC8-377DADB889BD";
|
||||
|
||||
/// <summary>
|
||||
/// Encrypt the given text and give the byte array back as a BASE64 string
|
||||
/// </summary>
|
||||
/// <param name="text">The text to encrypt</param>
|
||||
/// <param name="salt">The password salt</param>
|
||||
/// <returns>The encrypted text</returns>
|
||||
public static string Encrypt(string text, string salt)
|
||||
{
|
||||
string result;
|
||||
if (string.IsNullOrEmpty(text))
|
||||
throw new ArgumentNullException(nameof(text));
|
||||
#pragma warning disable SYSLIB0022
|
||||
RijndaelManaged aesAlg = NewRijndaelManaged(salt);
|
||||
#pragma warning restore
|
||||
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
||||
MemoryStream msEncrypt = new();
|
||||
using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write))
|
||||
using (StreamWriter swEncrypt = new(csEncrypt))
|
||||
swEncrypt.Write(text);
|
||||
result = Convert.ToBase64String(msEncrypt.ToArray());
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a string is base64 encoded
|
||||
/// </summary>
|
||||
/// <param name="base64String">The base64 encoded string</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsBase64String(string base64String)
|
||||
{
|
||||
bool result;
|
||||
base64String = base64String.Trim();
|
||||
#pragma warning restore
|
||||
result = (base64String.Length % 4 == 0) && Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
|
||||
#pragma warning restore
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decrypts the given text
|
||||
/// </summary>
|
||||
/// <param name="cipherText">The encrypted BASE64 text</param>
|
||||
/// <param name="salt">The password salt</param>
|
||||
/// <returns>De gedecrypte text</returns>
|
||||
public static string Decrypt(string cipherText, string salt)
|
||||
{
|
||||
if (string.IsNullOrEmpty(cipherText))
|
||||
throw new ArgumentNullException(nameof(cipherText));
|
||||
if (!IsBase64String(cipherText))
|
||||
throw new Exception("The cipherText input parameter is not base64 encoded");
|
||||
string text;
|
||||
#pragma warning disable SYSLIB0022
|
||||
RijndaelManaged aesAlg = NewRijndaelManaged(salt);
|
||||
#pragma warning restore
|
||||
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
||||
byte[] cipher = Convert.FromBase64String(cipherText);
|
||||
using (MemoryStream msDecrypt = new(cipher))
|
||||
{
|
||||
using CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read);
|
||||
using StreamReader srDecrypt = new(csDecrypt);
|
||||
text = srDecrypt.ReadToEnd();
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new RijndaelManaged class and initialize it
|
||||
/// </summary>
|
||||
/// <param name="salt">The password salt</param>
|
||||
/// <returns></returns>
|
||||
#pragma warning disable SYSLIB0022, SYSLIB0041, CA5379
|
||||
private static RijndaelManaged NewRijndaelManaged(string salt)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(salt);
|
||||
byte[] saltBytes = Encoding.ASCII.GetBytes(salt);
|
||||
Rfc2898DeriveBytes key = new(_InputKey, saltBytes);
|
||||
RijndaelManaged aesAlg = new();
|
||||
#pragma warning restore
|
||||
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
|
||||
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
|
||||
return aesAlg;
|
||||
}
|
||||
|
||||
}
|
145
Infineon/Monitoring/MonA/IMonIn.cs
Normal file
145
Infineon/Monitoring/MonA/IMonIn.cs
Normal file
@ -0,0 +1,145 @@
|
||||
namespace File_Watcher.Infineon.Monitoring.MonA;
|
||||
|
||||
public interface IMonIn
|
||||
{
|
||||
Task<HttpResponseMessage> SendStatus(string site, string resource, string stateName, State state);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime timeStamp,
|
||||
string resource,
|
||||
string stateName,
|
||||
State state);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
string resource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime timeStamp,
|
||||
string resource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
int? interval);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
DateTime? timeStamp,
|
||||
string performanceName,
|
||||
double value,
|
||||
string unit);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string unit,
|
||||
int? interval);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
int? interval);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string unit);
|
||||
|
||||
Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description,
|
||||
string unit,
|
||||
int? interval);
|
||||
}
|
266
Infineon/Monitoring/MonA/MonIn.cs
Normal file
266
Infineon/Monitoring/MonA/MonIn.cs
Normal file
@ -0,0 +1,266 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace File_Watcher.Infineon.Monitoring.MonA;
|
||||
|
||||
public class MonIn : IMonIn
|
||||
{
|
||||
private readonly string _MonInUrl;
|
||||
private readonly HttpClient _HttpClient;
|
||||
private static CultureInfo? _CultureInfo;
|
||||
private static readonly Dictionary<string, MonIn> _Instances = [];
|
||||
public const string MonInUrl = "http://moninhttp.{0}.infineon.com/input/text";
|
||||
private static readonly DateTime _Utc1970DateTime = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public static MonIn GetInstance(IHttpClientFactory httpClientFactory, string url = MonInUrl)
|
||||
{
|
||||
MonIn instance;
|
||||
if (_Instances.ContainsKey(url))
|
||||
{
|
||||
instance = _Instances[url];
|
||||
}
|
||||
else
|
||||
{
|
||||
lock (_Instances)
|
||||
{
|
||||
if (!_Instances.ContainsKey(url))
|
||||
{
|
||||
instance = new MonIn(httpClientFactory, url);
|
||||
_Instances.Add(url, instance);
|
||||
}
|
||||
else
|
||||
instance = _Instances[url];
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private MonIn(IHttpClientFactory httpClientFactory, string url)
|
||||
{
|
||||
_MonInUrl = url;
|
||||
_CultureInfo = new CultureInfo("en-US");
|
||||
_HttpClient = httpClientFactory.CreateClient();
|
||||
}
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site, string resource, string stateName, State state) =>
|
||||
SendStatus(site, new DateTime?(), resource, string.Empty, stateName, state, string.Empty);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime timeStamp,
|
||||
string resource,
|
||||
string stateName,
|
||||
State state) =>
|
||||
SendStatus(site, new DateTime?(timeStamp), resource, string.Empty, stateName, state, string.Empty);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site,
|
||||
string resource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description) =>
|
||||
SendStatus(site, new DateTime?(), resource, string.Empty, stateName, state, description);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime timeStamp,
|
||||
string resource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description) =>
|
||||
SendStatus(site, new DateTime?(timeStamp), resource, string.Empty, stateName, state, description);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state) =>
|
||||
SendStatus(site, new DateTime?(), resource, subResource, stateName, state, string.Empty);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site,
|
||||
DateTime timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state) =>
|
||||
SendStatus(site, new DateTime?(timeStamp), resource, subResource, stateName, state, string.Empty);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description) =>
|
||||
SendStatus(site, new DateTime?(), resource, subResource, stateName, state, description);
|
||||
|
||||
public Task<HttpResponseMessage> SendStatus(
|
||||
string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
State state,
|
||||
string description)
|
||||
{
|
||||
string statusMessage = CreateStatusMessage(site, timeStamp, resource, subResource, stateName, state.ToString(), description);
|
||||
StringContent stringContent = new(statusMessage, Encoding.UTF8, "application/text");
|
||||
lock (_HttpClient)
|
||||
return _HttpClient.PostAsync(string.Format(_MonInUrl, site), stringContent);
|
||||
}
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value) =>
|
||||
SendPerformanceMessage(site, new DateTime?(), resource, string.Empty, performanceName, value, string.Empty, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description) =>
|
||||
SendPerformanceMessage(site, new DateTime?(), resource, string.Empty, performanceName, value, description, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, description, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
int? interval) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, string.Empty, interval);
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
DateTime? timeStamp,
|
||||
string performanceName,
|
||||
double value,
|
||||
string unit) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, unit, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string unit,
|
||||
int? interval) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, unit, interval);
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value) =>
|
||||
SendPerformanceMessage(site, new DateTime?(), resource, subResource, performanceName, value, string.Empty, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, subResource, performanceName, value, string.Empty, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description) =>
|
||||
SendPerformanceMessage(site, new DateTime?(), resource, subResource, performanceName, value, description, string.Empty, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
int? interval) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, subResource, performanceName, value, string.Empty, string.Empty, interval);
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string unit) =>
|
||||
SendPerformanceMessage(site, timeStamp, resource, subResource, performanceName, value, string.Empty, unit, new int?());
|
||||
|
||||
public Task<HttpResponseMessage> SendPerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description,
|
||||
string unit,
|
||||
int? interval)
|
||||
{
|
||||
string performanceMessage = CreatePerformanceMessage(site, timeStamp, resource, subResource, performanceName, value, description, unit, interval);
|
||||
StringContent stringContent = new(performanceMessage, Encoding.UTF8, "application/text");
|
||||
lock (_HttpClient)
|
||||
return _HttpClient.PostAsync(string.Format(_MonInUrl, site), stringContent);
|
||||
}
|
||||
|
||||
private static string CreateStatusMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string stateName,
|
||||
string state,
|
||||
string description)
|
||||
{
|
||||
StringBuilder stringBuilder = new();
|
||||
if (string.IsNullOrEmpty(subResource))
|
||||
_ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" {4} \n{5}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), stateName.Trim(), state.Trim(), description.Trim());
|
||||
else
|
||||
_ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" \"{4}\" {5} \n{6}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), subResource.Trim(), stateName.Trim(), state.Trim(), description.Trim());
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
private static string CreatePerformanceMessage(string site,
|
||||
DateTime? timeStamp,
|
||||
string resource,
|
||||
string subResource,
|
||||
string performanceName,
|
||||
double value,
|
||||
string description,
|
||||
string unit,
|
||||
int? interval)
|
||||
{
|
||||
StringBuilder stringBuilder = new();
|
||||
if (string.IsNullOrEmpty(subResource))
|
||||
{
|
||||
if (unit.Equals(string.Empty) && !interval.HasValue)
|
||||
_ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" {4} \n{5}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), performanceName.Trim(), value, description.Trim());
|
||||
else
|
||||
_ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" {4} {5} {{interval={6}, unit={7}}}\n", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), performanceName.Trim(), value, description.Trim(), interval.HasValue ? interval.Value.ToString() : (object)string.Empty, unit.Trim());
|
||||
}
|
||||
else if (unit.Equals(string.Empty) && !interval.HasValue)
|
||||
_ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" \"{4}\" {5} \n{6}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), subResource.Trim(), performanceName.Trim(), value, description.Trim());
|
||||
else
|
||||
_ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" \"{4}\" {5} {6} {{interval={7}, unit={8}}}\n", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), subResource.Trim(), performanceName.Trim(), value, description.Trim(), interval.HasValue ? interval.Value.ToString() : (object)string.Empty, unit.Trim());
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
private static string GetDateTimeNowAsPosix(DateTime timeStamp)
|
||||
{
|
||||
if (timeStamp > DateTime.Now)
|
||||
timeStamp = DateTime.Now;
|
||||
return ((int)timeStamp.ToUniversalTime().Subtract(_Utc1970DateTime).TotalSeconds).ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
}
|
11
Infineon/Monitoring/MonA/State.cs
Normal file
11
Infineon/Monitoring/MonA/State.cs
Normal file
@ -0,0 +1,11 @@
|
||||
namespace File_Watcher.Infineon.Monitoring.MonA;
|
||||
|
||||
public enum State
|
||||
{
|
||||
Up,
|
||||
Ok,
|
||||
Warning,
|
||||
Critical,
|
||||
Down,
|
||||
Unknown,
|
||||
}
|
@ -1,20 +1,107 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using View_by_Distance.Shared.Models;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record AppSettings(EAFLogConfiguration EAFLogConfiguration,
|
||||
public record AppSettings(CamstarOracleConfiguration CamstarOracleConfiguration,
|
||||
CompassConfiguration CompassConfiguration,
|
||||
DeterministicHashCodeConfiguration DeterministicHashCodeConfiguration,
|
||||
DriveConfiguration DriveConfiguration,
|
||||
EAFLogConfiguration EAFLogConfiguration,
|
||||
EDADatabaseConfiguration EDADatabaseConfiguration,
|
||||
FileWatcherConfiguration FileWatcherConfiguration,
|
||||
InfinityQSConfiguration InfinityQSConfiguration,
|
||||
IsoConfiguration IsoConfiguration,
|
||||
MetadataSettings MetadataSettings,
|
||||
MetrologyConfiguration MetrologyConfiguration,
|
||||
NugetConfiguration NugetConfiguration,
|
||||
ResultSettings ResultSettings,
|
||||
SerialConfiguration SerialConfiguration,
|
||||
StratusConfiguration StratusConfiguration,
|
||||
WaferCounterConfiguration WaferCounterConfiguration,
|
||||
string BuildNumber,
|
||||
string Company,
|
||||
string GitCommitSeven,
|
||||
string Helper,
|
||||
int MillisecondsDelay,
|
||||
string WatchDirectory)
|
||||
TransmissionControlProtocolConfiguration TransmissionControlProtocolConfiguration,
|
||||
WaferCounterConfiguration WaferCounterConfiguration)
|
||||
{
|
||||
|
||||
public static AppSettings Get(IConfigurationRoot configurationRoot)
|
||||
{
|
||||
AppSettings result;
|
||||
#pragma warning disable IL3050, IL2026
|
||||
CamstarOracleConfiguration? camstarOracleConfiguration = configurationRoot.GetSection(nameof(CamstarOracleConfiguration)).Get<CamstarOracleConfiguration>();
|
||||
CompassConfiguration? compassConfiguration = configurationRoot.GetSection(nameof(CompassConfiguration)).Get<CompassConfiguration>();
|
||||
DeterministicHashCodeConfiguration? deterministicHashCodeConfiguration = configurationRoot.GetSection(nameof(DeterministicHashCodeConfiguration)).Get<DeterministicHashCodeConfiguration>();
|
||||
DriveConfiguration? driveConfiguration = configurationRoot.GetSection(nameof(DriveConfiguration)).Get<DriveConfiguration>();
|
||||
EAFLogConfiguration? eafLogConfiguration = configurationRoot.GetSection(nameof(EAFLogConfiguration)).Get<EAFLogConfiguration>();
|
||||
EDADatabaseConfiguration? edaDatabaseConfiguration = configurationRoot.GetSection(nameof(EDADatabaseConfiguration)).Get<EDADatabaseConfiguration>();
|
||||
FileWatcherConfiguration? fileWatcherConfiguration = configurationRoot.GetSection(nameof(FileWatcherConfiguration)).Get<FileWatcherConfiguration>();
|
||||
InfinityQSConfiguration? infinityQSConfiguration = configurationRoot.GetSection(nameof(InfinityQSConfiguration)).Get<InfinityQSConfiguration>();
|
||||
IsoConfiguration? isoConfiguration = configurationRoot.GetSection(nameof(IsoConfiguration)).Get<IsoConfiguration>();
|
||||
MetadataSettings? metadataSettings = configurationRoot.GetSection(nameof(MetadataSettings)).Get<MetadataSettings>();
|
||||
MetrologyConfiguration? metrologyConfiguration = configurationRoot.GetSection(nameof(MetrologyConfiguration)).Get<MetrologyConfiguration>();
|
||||
NugetConfiguration? nugetConfiguration = configurationRoot.GetSection(nameof(NugetConfiguration)).Get<NugetConfiguration>();
|
||||
ResultSettings? resultSettings = configurationRoot.GetSection(nameof(ResultSettings)).Get<ResultSettings>();
|
||||
SerialConfiguration? serialConfiguration = configurationRoot.GetSection(nameof(SerialConfiguration)).Get<SerialConfiguration>();
|
||||
StratusConfiguration? stratusConfiguration = configurationRoot.GetSection(nameof(StratusConfiguration)).Get<StratusConfiguration>();
|
||||
TransmissionControlProtocolConfiguration? transmissionControlProtocolConfiguration = configurationRoot.GetSection(nameof(TransmissionControlProtocolConfiguration)).Get<TransmissionControlProtocolConfiguration>();
|
||||
WaferCounterConfiguration? waferCounterConfiguration = configurationRoot.GetSection(nameof(WaferCounterConfiguration)).Get<WaferCounterConfiguration>();
|
||||
#pragma warning restore IL3050, IL2026
|
||||
if (camstarOracleConfiguration is null
|
||||
|| compassConfiguration is null
|
||||
|| deterministicHashCodeConfiguration is null
|
||||
|| driveConfiguration is null
|
||||
|| eafLogConfiguration is null
|
||||
|| edaDatabaseConfiguration is null
|
||||
|| fileWatcherConfiguration is null
|
||||
|| infinityQSConfiguration is null
|
||||
|| isoConfiguration is null
|
||||
|| metadataSettings is null
|
||||
|| metrologyConfiguration is null
|
||||
|| nugetConfiguration is null
|
||||
|| resultSettings is null
|
||||
|| serialConfiguration is null
|
||||
|| stratusConfiguration is null
|
||||
|| transmissionControlProtocolConfiguration is null
|
||||
|| waferCounterConfiguration is null
|
||||
|| fileWatcherConfiguration?.Company 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())}");
|
||||
}
|
||||
result = new(camstarOracleConfiguration,
|
||||
compassConfiguration,
|
||||
deterministicHashCodeConfiguration,
|
||||
driveConfiguration,
|
||||
eafLogConfiguration,
|
||||
edaDatabaseConfiguration,
|
||||
fileWatcherConfiguration,
|
||||
infinityQSConfiguration,
|
||||
isoConfiguration,
|
||||
metadataSettings,
|
||||
metrologyConfiguration,
|
||||
nugetConfiguration,
|
||||
resultSettings,
|
||||
serialConfiguration,
|
||||
stratusConfiguration,
|
||||
transmissionControlProtocolConfiguration,
|
||||
waferCounterConfiguration);
|
||||
Verify(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void Verify(AppSettings appSettings)
|
||||
{
|
||||
if (appSettings.DeterministicHashCodeConfiguration.MaxDegreeOfParallelism > Environment.ProcessorCount)
|
||||
throw new Exception($"Environment.ProcessorCount must be larger or equal to {nameof(appSettings.DeterministicHashCodeConfiguration.MaxDegreeOfParallelism)}");
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, AppSettingsSourceGenerationContext.Default.AppSettings);
|
||||
|
@ -1,2 +0,0 @@
|
||||
[*.cs]
|
||||
csharp_preserve_single_line_statements = true
|
@ -1,97 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models.Binder;
|
||||
|
||||
public class AppSettings
|
||||
{
|
||||
|
||||
public string? BuildNumber { get; set; }
|
||||
public string? Company { get; set; }
|
||||
public string? GitCommitSeven { get; set; }
|
||||
public string? Helper { get; set; }
|
||||
public int? MillisecondsDelay { get; set; }
|
||||
public string? WatchDirectory { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, BinderAppSettingsSourceGenerationContext.Default.AppSettings);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PreVerify(IConfigurationRoot configurationRoot, AppSettings? appSettings)
|
||||
{
|
||||
if (appSettings?.BuildNumber is null)
|
||||
{
|
||||
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
|
||||
{
|
||||
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
|
||||
continue;
|
||||
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
|
||||
continue;
|
||||
if (!physicalFileProvider.Root.Contains("UserSecrets"))
|
||||
continue;
|
||||
throw new NotSupportedException(physicalFileProvider.Root);
|
||||
}
|
||||
throw new NotSupportedException("Not Found!");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Verify(AppSettings _)
|
||||
{
|
||||
}
|
||||
|
||||
private static Models.AppSettings Get(AppSettings? appSettings,
|
||||
Models.EAFLogConfiguration eafLogConfiguration,
|
||||
Models.MetrologyConfiguration metrologyConfiguration,
|
||||
Models.StratusConfiguration stratusConfiguration,
|
||||
Models.WaferCounterConfiguration waferCounterConfiguration)
|
||||
{
|
||||
Models.AppSettings result;
|
||||
if (appSettings is null) throw new NullReferenceException(nameof(appSettings));
|
||||
if (appSettings.BuildNumber is null) throw new NullReferenceException(nameof(BuildNumber));
|
||||
if (appSettings.Company is null) throw new NullReferenceException(nameof(Company));
|
||||
if (appSettings.GitCommitSeven is null) throw new NullReferenceException(nameof(GitCommitSeven));
|
||||
if (appSettings.Helper is null) throw new NullReferenceException(nameof(Helper));
|
||||
if (appSettings.MillisecondsDelay is null) throw new NullReferenceException(nameof(MillisecondsDelay));
|
||||
if (appSettings.WatchDirectory is null) throw new NullReferenceException(nameof(WatchDirectory));
|
||||
Verify(appSettings);
|
||||
result = new(eafLogConfiguration,
|
||||
metrologyConfiguration,
|
||||
stratusConfiguration,
|
||||
waferCounterConfiguration,
|
||||
appSettings.BuildNumber,
|
||||
appSettings.Company,
|
||||
appSettings.GitCommitSeven,
|
||||
appSettings.Helper,
|
||||
appSettings.MillisecondsDelay.Value,
|
||||
appSettings.WatchDirectory);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Models.AppSettings Get(IConfigurationRoot configurationRoot,
|
||||
Models.EAFLogConfiguration eafLogConfiguration,
|
||||
Models.MetrologyConfiguration metrologyConfiguration,
|
||||
Models.StratusConfiguration stratusConfiguration,
|
||||
Models.WaferCounterConfiguration waferCounterConfiguration)
|
||||
{
|
||||
Models.AppSettings result;
|
||||
#pragma warning disable IL3050, IL2026
|
||||
AppSettings? appSettings = configurationRoot.Get<AppSettings>();
|
||||
#pragma warning restore IL3050, IL2026
|
||||
PreVerify(configurationRoot, appSettings);
|
||||
result = Get(appSettings,
|
||||
eafLogConfiguration,
|
||||
metrologyConfiguration,
|
||||
stratusConfiguration,
|
||||
waferCounterConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(AppSettings))]
|
||||
internal partial class BinderAppSettingsSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models.Binder;
|
||||
|
||||
public class EAFLogConfiguration
|
||||
{
|
||||
|
||||
public string? SearchPattern { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, BinderEAFLogConfigurationSourceGenerationContext.Default.EAFLogConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PreVerify(IConfigurationRoot configurationRoot, EAFLogConfiguration? configuration)
|
||||
{
|
||||
if (configuration?.SearchPattern is null)
|
||||
{
|
||||
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
|
||||
{
|
||||
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
|
||||
continue;
|
||||
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
|
||||
continue;
|
||||
if (!physicalFileProvider.Root.Contains("UserSecrets"))
|
||||
continue;
|
||||
throw new NotSupportedException(physicalFileProvider.Root);
|
||||
}
|
||||
throw new NotSupportedException("Not Found!");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Verify(EAFLogConfiguration _)
|
||||
{
|
||||
}
|
||||
|
||||
private static Models.EAFLogConfiguration Get(EAFLogConfiguration? configuration)
|
||||
{
|
||||
Models.EAFLogConfiguration result;
|
||||
if (configuration is null) throw new NullReferenceException(nameof(configuration));
|
||||
if (configuration.SearchPattern is null) throw new NullReferenceException(nameof(configuration.SearchPattern));
|
||||
Verify(configuration);
|
||||
result = new(configuration.SearchPattern);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Models.EAFLogConfiguration Get(IConfigurationRoot configurationRoot)
|
||||
{
|
||||
Models.EAFLogConfiguration result;
|
||||
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.EAFLogConfiguration));
|
||||
#pragma warning disable IL3050, IL2026
|
||||
EAFLogConfiguration? configuration = configurationSection.Get<EAFLogConfiguration>();
|
||||
#pragma warning restore IL3050, IL2026
|
||||
PreVerify(configurationRoot, configuration);
|
||||
result = Get(configuration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(EAFLogConfiguration))]
|
||||
internal partial class BinderEAFLogConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models.Binder;
|
||||
|
||||
public class MetrologyConfiguration
|
||||
{
|
||||
|
||||
public int? DirectoriesBack { get; set; }
|
||||
public int? DeleteOlderThanWeeks { get; set; }
|
||||
public string[]? HardcodedValues { get; set; }
|
||||
public string[]? SourceDirectories { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, BinderMetrologyConfigurationSourceGenerationContext.Default.MetrologyConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PreVerify(IConfigurationRoot configurationRoot, MetrologyConfiguration? configuration)
|
||||
{
|
||||
if (configuration?.DirectoriesBack is null)
|
||||
{
|
||||
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
|
||||
{
|
||||
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
|
||||
continue;
|
||||
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
|
||||
continue;
|
||||
if (!physicalFileProvider.Root.Contains("UserSecrets"))
|
||||
continue;
|
||||
throw new NotSupportedException(physicalFileProvider.Root);
|
||||
}
|
||||
throw new NotSupportedException("Not Found!");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Verify(MetrologyConfiguration _)
|
||||
{
|
||||
}
|
||||
|
||||
private static Models.MetrologyConfiguration Get(MetrologyConfiguration? configuration)
|
||||
{
|
||||
Models.MetrologyConfiguration result;
|
||||
if (configuration is null) throw new NullReferenceException(nameof(configuration));
|
||||
if (configuration.DirectoriesBack is null) throw new NullReferenceException(nameof(configuration.DirectoriesBack));
|
||||
if (configuration.DeleteOlderThanWeeks is null) throw new NullReferenceException(nameof(configuration.DeleteOlderThanWeeks));
|
||||
if (configuration.HardcodedValues is null) throw new NullReferenceException(nameof(configuration.HardcodedValues));
|
||||
if (configuration.SourceDirectories is null) throw new NullReferenceException(nameof(configuration.SourceDirectories));
|
||||
Verify(configuration);
|
||||
result = new(configuration.DirectoriesBack.Value,
|
||||
configuration.DeleteOlderThanWeeks.Value,
|
||||
configuration.HardcodedValues,
|
||||
configuration.SourceDirectories);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Models.MetrologyConfiguration Get(IConfigurationRoot configurationRoot)
|
||||
{
|
||||
Models.MetrologyConfiguration result;
|
||||
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.MetrologyConfiguration));
|
||||
#pragma warning disable IL3050, IL2026
|
||||
MetrologyConfiguration? configuration = configurationSection.Get<MetrologyConfiguration>();
|
||||
#pragma warning restore IL3050, IL2026
|
||||
PreVerify(configurationRoot, configuration);
|
||||
result = Get(configuration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(MetrologyConfiguration))]
|
||||
internal partial class BinderMetrologyConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
@ -1,73 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models.Binder;
|
||||
|
||||
public class StratusConfiguration
|
||||
{
|
||||
|
||||
public string? Destination { get; set; }
|
||||
public string? FileDelimiterPattern { get; set; }
|
||||
public string? WatchFile { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, BinderStratusConfigurationSourceGenerationContext.Default.StratusConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PreVerify(IConfigurationRoot configurationRoot, StratusConfiguration? configuration)
|
||||
{
|
||||
if (configuration?.Destination is null)
|
||||
{
|
||||
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
|
||||
{
|
||||
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
|
||||
continue;
|
||||
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
|
||||
continue;
|
||||
if (!physicalFileProvider.Root.Contains("UserSecrets"))
|
||||
continue;
|
||||
throw new NotSupportedException(physicalFileProvider.Root);
|
||||
}
|
||||
throw new NotSupportedException("Not Found!");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Verify(StratusConfiguration _)
|
||||
{
|
||||
}
|
||||
|
||||
private static Models.StratusConfiguration Get(StratusConfiguration? configuration)
|
||||
{
|
||||
Models.StratusConfiguration result;
|
||||
if (configuration is null) throw new NullReferenceException(nameof(configuration));
|
||||
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
|
||||
if (configuration.FileDelimiterPattern is null) throw new NullReferenceException(nameof(configuration.FileDelimiterPattern));
|
||||
if (configuration.WatchFile is null) throw new NullReferenceException(nameof(configuration.WatchFile));
|
||||
Verify(configuration);
|
||||
result = new(configuration.Destination,
|
||||
configuration.FileDelimiterPattern,
|
||||
configuration.WatchFile);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Models.StratusConfiguration Get(IConfigurationRoot configurationRoot)
|
||||
{
|
||||
Models.StratusConfiguration result;
|
||||
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.StratusConfiguration));
|
||||
#pragma warning disable IL3050, IL2026
|
||||
StratusConfiguration? configuration = configurationSection.Get<StratusConfiguration>();
|
||||
#pragma warning restore IL3050, IL2026
|
||||
PreVerify(configurationRoot, configuration);
|
||||
result = Get(configuration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(StratusConfiguration))]
|
||||
internal partial class BinderStratusConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models.Binder;
|
||||
|
||||
public class WaferCounterConfiguration
|
||||
{
|
||||
|
||||
public string? Destination { get; set; }
|
||||
public bool? MatchPath { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, BinderWaferCounterConfigurationSourceGenerationContext.Default.WaferCounterConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PreVerify(IConfigurationRoot configurationRoot, WaferCounterConfiguration? configuration)
|
||||
{
|
||||
if (configuration?.Destination is null)
|
||||
{
|
||||
foreach (IConfigurationProvider configurationProvider in configurationRoot.Providers)
|
||||
{
|
||||
if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider)
|
||||
continue;
|
||||
if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider)
|
||||
continue;
|
||||
if (!physicalFileProvider.Root.Contains("UserSecrets"))
|
||||
continue;
|
||||
throw new NotSupportedException(physicalFileProvider.Root);
|
||||
}
|
||||
throw new NotSupportedException("Not Found!");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Verify(WaferCounterConfiguration _)
|
||||
{
|
||||
}
|
||||
|
||||
private static Models.WaferCounterConfiguration Get(WaferCounterConfiguration? configuration)
|
||||
{
|
||||
Models.WaferCounterConfiguration result;
|
||||
if (configuration is null) throw new NullReferenceException(nameof(configuration));
|
||||
if (configuration.Destination is null) throw new NullReferenceException(nameof(configuration.Destination));
|
||||
if (configuration.MatchPath is null) throw new NullReferenceException(nameof(configuration.MatchPath));
|
||||
Verify(configuration);
|
||||
result = new(configuration.Destination,
|
||||
configuration.MatchPath.Value);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Models.WaferCounterConfiguration Get(IConfigurationRoot configurationRoot)
|
||||
{
|
||||
Models.WaferCounterConfiguration result;
|
||||
IConfigurationSection configurationSection = configurationRoot.GetSection(nameof(Models.WaferCounterConfiguration));
|
||||
#pragma warning disable IL3050, IL2026
|
||||
WaferCounterConfiguration? configuration = configurationSection.Get<WaferCounterConfiguration>();
|
||||
#pragma warning restore IL3050, IL2026
|
||||
PreVerify(configurationRoot, configuration);
|
||||
result = Get(configuration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(WaferCounterConfiguration))]
|
||||
internal partial class BinderWaferCounterConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
28
Models/CamstarOracleConfiguration.cs
Normal file
28
Models/CamstarOracleConfiguration.cs
Normal file
@ -0,0 +1,28 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record CamstarOracleConfiguration(string DateFormat,
|
||||
string Directory,
|
||||
string LogFilter,
|
||||
string[] MessageFilters,
|
||||
string MonitorApplicationResource,
|
||||
string MonitorApplicationSite,
|
||||
int MillisecondsDelay,
|
||||
int RollingMinutes)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, CamstarOracleConfigurationSourceGenerationContext.Default.CamstarOracleConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(CamstarOracleConfiguration))]
|
||||
internal partial class CamstarOracleConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
27
Models/CompassConfiguration.cs
Normal file
27
Models/CompassConfiguration.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record CompassConfiguration(string Destination,
|
||||
int HoursBack,
|
||||
string MonthPattern,
|
||||
string Pattern,
|
||||
string Source,
|
||||
string TriggerAppendage,
|
||||
string YearPattern)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, CompassConfigurationSourceGenerationContext.Default.CompassConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(CompassConfiguration))]
|
||||
internal partial class CompassConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
22
Models/DeterministicHashCodeConfiguration.cs
Normal file
22
Models/DeterministicHashCodeConfiguration.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record DeterministicHashCodeConfiguration(int MaxDegreeOfParallelism,
|
||||
string[] SidecarExtensions)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, DeterministicHashCodeConfigurationSourceGenerationContext.Default.DeterministicHashCodeConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(DeterministicHashCodeConfiguration))]
|
||||
internal partial class DeterministicHashCodeConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
25
Models/DriveConfiguration.cs
Normal file
25
Models/DriveConfiguration.cs
Normal 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
|
||||
{
|
||||
}
|
27
Models/EDADatabaseConfiguration.cs
Normal file
27
Models/EDADatabaseConfiguration.cs
Normal 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
|
||||
{
|
||||
}
|
24
Models/FileWatcherConfiguration.cs
Normal file
24
Models/FileWatcherConfiguration.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record FileWatcherConfiguration(string Company,
|
||||
string Helper,
|
||||
int MillisecondsDelay,
|
||||
string WatchDirectory)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, FileWatcherConfigurationSourceGenerationContext.Default.FileWatcherConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(FileWatcherConfiguration))]
|
||||
internal partial class FileWatcherConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
34
Models/InfinityQSConfiguration.cs
Normal file
34
Models/InfinityQSConfiguration.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record Test(string Name,
|
||||
long Value);
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(Test[]))]
|
||||
internal partial class TestCollectionSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
|
||||
public record InfinityQSConfiguration(string ConnectionString,
|
||||
string DestinationDirectory,
|
||||
long SubGroupTime,
|
||||
string TestsFile,
|
||||
Test[] Tests)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, InfinityQSConfigurationSourceGenerationContext.Default.InfinityQSConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(InfinityQSConfiguration))]
|
||||
internal partial class InfinityQSConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
22
Models/IsoConfiguration.cs
Normal file
22
Models/IsoConfiguration.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record IsoConfiguration(string DestinationDirectory,
|
||||
string SourceDirectory)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, IsoConfigurationSourceGenerationContext.Default.IsoConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(IsoConfiguration))]
|
||||
internal partial class IsoConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
27
Models/NugetConfiguration.cs
Normal file
27
Models/NugetConfiguration.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record NugetConfiguration(string Destination,
|
||||
string KeyFileExtension,
|
||||
string KeyFileExtensionB,
|
||||
string KeyFileExtensionC,
|
||||
bool RenameToLower,
|
||||
string SearchPattern,
|
||||
string Source)
|
||||
{
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string result = JsonSerializer.Serialize(this, NugetConfigurationSourceGenerationContext.Default.NugetConfiguration);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(NugetConfiguration))]
|
||||
internal partial class NugetConfigurationSourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
24
Models/SerialConfiguration.cs
Normal file
24
Models/SerialConfiguration.cs
Normal 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
|
||||
{
|
||||
}
|
@ -3,7 +3,8 @@ using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Watcher.Models;
|
||||
|
||||
public record StratusConfiguration(string Destination,
|
||||
public record StratusConfiguration(int Days,
|
||||
string Destination,
|
||||
string FileDelimiterPattern,
|
||||
string WatchFile)
|
||||
{
|
||||
|
25
Models/TransmissionControlProtocolConfiguration.cs
Normal file
25
Models/TransmissionControlProtocolConfiguration.cs
Normal 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
|
||||
{
|
||||
}
|
19
Program.cs
19
Program.cs
@ -14,16 +14,17 @@ public class Program
|
||||
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
|
||||
#pragma warning restore IL3050
|
||||
_ = webApplicationBuilder.Configuration.AddUserSecrets<Program>();
|
||||
EAFLogConfiguration eafLogConfiguration = Models.Binder.EAFLogConfiguration.Get(webApplicationBuilder.Configuration);
|
||||
MetrologyConfiguration metrologyConfiguration = Models.Binder.MetrologyConfiguration.Get(webApplicationBuilder.Configuration);
|
||||
StratusConfiguration stratusConfiguration = Models.Binder.StratusConfiguration.Get(webApplicationBuilder.Configuration);
|
||||
WaferCounterConfiguration waferCounterConfiguration = Models.Binder.WaferCounterConfiguration.Get(webApplicationBuilder.Configuration);
|
||||
AppSettings appSettings = Models.Binder.AppSettings.Get(webApplicationBuilder.Configuration, eafLogConfiguration, metrologyConfiguration, stratusConfiguration, waferCounterConfiguration);
|
||||
if (string.IsNullOrEmpty(appSettings.Company))
|
||||
AppSettings appSettings = AppSettings.Get(webApplicationBuilder.Configuration);
|
||||
if (string.IsNullOrEmpty(appSettings.FileWatcherConfiguration.Company))
|
||||
throw new Exception("Company name must have a value!");
|
||||
try
|
||||
{
|
||||
List<string> collection = [];
|
||||
List<string> collection =
|
||||
[
|
||||
$"BuildNumber:{webApplicationBuilder.Configuration.GetValue<string>("BuildNumber")};",
|
||||
$"GitCommitSeven:{webApplicationBuilder.Configuration.GetValue<string>("GitCommitSeven")};"
|
||||
];
|
||||
_ = webApplicationBuilder.Services.AddHttpClient();
|
||||
_ = webApplicationBuilder.Services.AddHostedService<Worker>();
|
||||
_ = webApplicationBuilder.Services.AddSingleton(collection);
|
||||
_ = webApplicationBuilder.Services.AddSingleton(appSettings);
|
||||
@ -41,13 +42,13 @@ public class Program
|
||||
}
|
||||
using WebApplication webApplication = webApplicationBuilder.Build();
|
||||
logger = webApplication.Services.GetRequiredService<ILogger<Program>>();
|
||||
if (string.IsNullOrEmpty(appSettings.Company))
|
||||
if (string.IsNullOrEmpty(appSettings.FileWatcherConfiguration.Company))
|
||||
{
|
||||
Environment.ExitCode = -1;
|
||||
_ = webApplication.StopAsync();
|
||||
}
|
||||
logger.LogInformation("Starting Web Application");
|
||||
logger.LogCritical("{Company}", appSettings.Company);
|
||||
logger.LogCritical("{Company}", appSettings.FileWatcherConfiguration.Company);
|
||||
await webApplication.RunAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
83
Worker.cs
83
Worker.cs
@ -1,4 +1,4 @@
|
||||
using File_Watcher.Models;
|
||||
using File_Watcher.Models;
|
||||
using Microsoft.Extensions.Hosting.WindowsServices;
|
||||
using System.Data;
|
||||
|
||||
@ -7,52 +7,89 @@ namespace File_Watcher;
|
||||
public partial class Worker : BackgroundService
|
||||
{
|
||||
|
||||
private bool? _First;
|
||||
private readonly bool _IsWindowsService;
|
||||
private readonly ILogger<Worker> _Logger;
|
||||
private readonly AppSettings _AppSettings;
|
||||
private readonly IHttpClientFactory _HttpClientFactory;
|
||||
|
||||
public Worker(IServiceProvider serviceProvider, ILogger<Worker> logger, AppSettings appSettings, List<string> collection)
|
||||
public Worker(IHttpClientFactory httpClientFactory, ILogger<Worker> logger, IServiceProvider serviceProvider, AppSettings appSettings, List<string> collection)
|
||||
{
|
||||
_Logger = logger;
|
||||
_AppSettings = appSettings;
|
||||
logger.LogInformation("{buildNumber}-{gitCommitSeven}", _AppSettings.BuildNumber, _AppSettings.GitCommitSeven);
|
||||
_HttpClientFactory = httpClientFactory;
|
||||
logger.LogInformation(string.Join(Environment.NewLine, collection));
|
||||
try
|
||||
{ logger.LogInformation("<{folder}>", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); }
|
||||
catch (Exception) { }
|
||||
_First = null;
|
||||
_IsWindowsService = collection.Contains(nameof(WindowsServiceLifetime));
|
||||
}
|
||||
|
||||
private void Body()
|
||||
public override Task StopAsync(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))
|
||||
_ = Directory.CreateDirectory(_AppSettings.WatchDirectory);
|
||||
if (_AppSettings.FileWatcherConfiguration.Helper == nameof(Helpers.HelperCamstarOracle))
|
||||
Helpers.HelperCamstarOracle.Heartbeat(_AppSettings, _HttpClientFactory, _Logger, Infineon.Monitoring.MonA.State.Down, cancellationToken);
|
||||
return base.StopAsync(cancellationToken);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken cancellationToken) =>
|
||||
await Body(cancellationToken);
|
||||
private async Task Body(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_IsWindowsService)
|
||||
{
|
||||
_Logger.LogInformation("Set break point and skip to run {_AppSettings.FileWatcherConfiguration.Helper}!", _AppSettings.FileWatcherConfiguration.Helper);
|
||||
throw new EvaluateException($"Set break point and skip to run {_AppSettings.FileWatcherConfiguration.Helper}!");
|
||||
}
|
||||
if (!_IsWindowsService)
|
||||
{
|
||||
for (int i = 0; i < int.MaxValue; i++)
|
||||
{
|
||||
BodyInner(cancellationToken);
|
||||
Thread.Sleep(_AppSettings.FileWatcherConfiguration.MillisecondsDelay);
|
||||
}
|
||||
}
|
||||
while (_IsWindowsService && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
BodyInner(cancellationToken);
|
||||
await Task.Delay(_AppSettings.FileWatcherConfiguration.MillisecondsDelay, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private void BodyInner(CancellationToken cancellationToken)
|
||||
{
|
||||
_Logger.LogInformation("A) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.FileWatcherConfiguration.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt"));
|
||||
if (_First is null || _First.Value)
|
||||
{
|
||||
_First = false;
|
||||
if (_AppSettings.FileWatcherConfiguration.Helper == nameof(Helpers.HelperCamstarOracle))
|
||||
Helpers.HelperCamstarOracle.Heartbeat(_AppSettings, _HttpClientFactory, _Logger, Infineon.Monitoring.MonA.State.Up, cancellationToken);
|
||||
}
|
||||
if (!Directory.Exists(_AppSettings.FileWatcherConfiguration.WatchDirectory))
|
||||
_ = Directory.CreateDirectory(_AppSettings.FileWatcherConfiguration.WatchDirectory);
|
||||
else
|
||||
{
|
||||
_ = _AppSettings.Helper switch
|
||||
_ = _AppSettings.FileWatcherConfiguration.Helper switch
|
||||
{
|
||||
nameof(Helpers.HelperEAFLog) => Helpers.HelperEAFLog.DeleteFiles(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperNuget) => Helpers.HelperNuget.Sync(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperTCP) => Helpers.HelperTCP.ReadWrite(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperISO) => Helpers.HelperISO.DirectoryToISO(_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.Select(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperEventLog) => Helpers.HelperEventLog.ClearEventLogs(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperWaferCounter) => Helpers.HelperWaferCounter.MoveFile(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperSerial) => Helpers.HelperSerial.ReadWrite(_AppSettings, _Logger, cancellationToken),
|
||||
nameof(Helpers.HelperMetrologyFiles) => Helpers.HelperMetrologyFiles.SortAndDelete(_AppSettings, _Logger),
|
||||
nameof(Helpers.HelperCamstarOracle) => Helpers.HelperCamstarOracle.Check(_AppSettings, _Logger, cancellationToken),
|
||||
nameof(Helpers.DeterministicHashCodeHelper) => Helpers.DeterministicHashCodeHelper.WindowsWork(_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"));
|
||||
_Logger.LogInformation("B) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.FileWatcherConfiguration.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt"));
|
||||
}
|
||||
|
||||
private async Task Body(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_IsWindowsService)
|
||||
throw new EvaluateException("Set break point and skip!");
|
||||
while (_IsWindowsService && !stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
Body();
|
||||
await Task.Delay(_AppSettings.MillisecondsDelay, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken) =>
|
||||
await Body(stoppingToken);
|
||||
}
|
35
package-lock.json
generated
35
package-lock.json
generated
@ -1,35 +0,0 @@
|
||||
{
|
||||
"name": "File-Watcher",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"devDependencies": {
|
||||
"prettier": "3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "http://localhost:4873/prettier/-/prettier-3.0.0.tgz",
|
||||
"integrity": "sha512-zBf5eHpwHOGPC47h0zrPyNn+eAEIdEzfywMoYn2XPi0P44Zp0tSq64rq0xAREh4auw2cJZHo9QUob+NqCQky4g==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"prettier": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "http://localhost:4873/prettier/-/prettier-3.0.0.tgz",
|
||||
"integrity": "sha512-zBf5eHpwHOGPC47h0zrPyNn+eAEIdEzfywMoYn2XPi0P44Zp0tSq64rq0xAREh4auw2cJZHo9QUob+NqCQky4g==",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
}
|
10
package.json
10
package.json
@ -1,10 +0,0 @@
|
||||
{
|
||||
"scripts": {
|
||||
"prettier.check": "prettier . --check",
|
||||
"prettier.write": "prettier . --write",
|
||||
"garbage-collect": "git gc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"prettier": "3.0.0"
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user