file-watcher/Helpers/HelperInfinityQS.cs

207 lines
9.1 KiB
C#

using File_Watcher.Models;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Watcher.Helpers;
internal static partial class HelperInfinityQS
{
internal record Record([property: JsonPropertyName("count_se_sgtm")] int CountSeSubgroupTime,
[property: JsonPropertyName("date_time")] DateTime DateTime,
[property: JsonPropertyName("max_se_lot")] int MaxSeLot,
[property: JsonPropertyName("max_se_prcs")] int MaxSeProcess,
[property: JsonPropertyName("max_se_sgrp")] int MaxSeSubgroup,
[property: JsonPropertyName("max_se_test")] int MaxSeTest,
[property: JsonPropertyName("max_se_val")] float MaxSeValue,
[property: JsonPropertyName("min_se_sgrp")] int MinSeSubgroup,
[property: JsonPropertyName("test")] string Test);
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Record[]))]
internal partial class RecordCollectionSourceGenerationContext : JsonSerializerContext
{
}
private static string GetCommandText(InfinityQSConfiguration infinityQSConfiguration, Test test)
{ // cSpell:disable
List<string> results = [];
results.Add(" select min_se_sgrp, ");
results.Add(" max_se_sgrp, ");
results.Add(" max_se_prcs, ");
results.Add(" max_se_lot, ");
results.Add(" max_se_test, ");
results.Add(" max_se_val, ");
results.Add($" '{test.Name}' test, ");
results.Add(" dateadd(HH, -7, (dateadd(SS, convert(bigint, max_se_sgtm), '19700101'))) date_time, ");
results.Add(" count_se_sgtm ");
results.Add(" from ( ");
results.Add(" select ");
results.Add(" max(se.f_lot) max_se_lot, ");
results.Add(" max(se.f_val) max_se_val, ");
results.Add(" min(se.f_lot) min_se_lot, ");
results.Add(" min(se.f_val) min_se_val, ");
results.Add(" max(se.f_prcs) max_se_prcs, ");
results.Add(" max(se.f_sgrp) max_se_sgrp, ");
results.Add(" max(se.f_sgtm) max_se_sgtm, ");
results.Add(" max(se.f_test) max_se_test, ");
results.Add(" min(se.f_prcs) min_se_prcs, ");
results.Add(" min(se.f_sgrp) min_se_sgrp, ");
results.Add(" count(se.f_sgtm) count_se_sgtm ");
results.Add(" from [spcepiworld].[dbo].[sgrp_ext] se ");
results.Add(" where se.f_tsno = 1 ");
results.Add(" and se.f_val <> 0 ");
results.Add(" and se.f_flag = 0 ");
results.Add($" and se.f_test = {test.Value} ");
results.Add($" and se.f_sgtm > {infinityQSConfiguration.SubGroupTime} ");
results.Add(" group by se.f_sgtm, se.f_prcs, se.f_lot ");
results.Add(" ) qa ");
results.Add(" where qa.count_se_sgtm > 1 ");
results.Add(" and min_se_lot = max_se_lot ");
results.Add(" and min_se_val = max_se_val ");
results.Add(" and min_se_prcs = max_se_prcs ");
results.Add(" for json path ");
return string.Join(' ', results);
} // cSpell:enable
private static string GetCommandText(ReadOnlyCollection<int> subGroups)
{ // cSpell:disable
List<string> results = [];
results.Add(" update [spcepiworld].[dbo].[sgrp_ext] ");
results.Add(" set f_flag = 1 ");
results.Add(" where f_flag = 0 ");
results.Add($" and f_sgrp in ({string.Join(',', subGroups)}) ");
return string.Join(Environment.NewLine, results);
} // cSpell:enable
private static StringBuilder GetForJsonPath(InfinityQSConfiguration infinityQSConfiguration, string commandText)
{
StringBuilder stringBuilder = new();
using SqlConnection sqlConnection = new(infinityQSConfiguration.ConnectionString);
sqlConnection.Open();
using SqlCommand sqlCommand = new(commandText, sqlConnection);
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess);
while (sqlDataReader.Read())
_ = stringBuilder.Append(sqlDataReader.GetString(0));
return stringBuilder;
}
private static int? ExecuteNonQuery(InfinityQSConfiguration infinityQSConfiguration, string commandText)
{
int? result;
if (!string.IsNullOrEmpty(infinityQSConfiguration.ConnectionString))
result = null;
else
{
using SqlConnection sqlConnection = new(infinityQSConfiguration.ConnectionString);
sqlConnection.Open();
using SqlCommand sqlCommand = new(commandText, sqlConnection);
result = sqlCommand.ExecuteNonQuery();
}
return result;
}
private static void Disable(InfinityQSConfiguration infinityQSConfiguration, string checkFile, ReadOnlyCollection<int> collection)
{
string commandText = GetCommandText(collection);
File.WriteAllText(checkFile, commandText);
_ = ExecuteNonQuery(infinityQSConfiguration, commandText);
}
private static ReadOnlyCollection<Test> GetTests(InfinityQSConfiguration infinityQSConfiguration)
{
List<Test> results = new(infinityQSConfiguration.Tests);
if (File.Exists(infinityQSConfiguration.TestsFile))
{
string json = File.ReadAllText(infinityQSConfiguration.TestsFile);
List<long> distinct = infinityQSConfiguration.Tests.Select(l => l.Value).ToList();
Test[]? tests = JsonSerializer.Deserialize(json, TestCollectionSourceGenerationContext.Default.TestArray);
if (tests is not null)
{
foreach (Test test in tests)
{
if (distinct.Contains(test.Value))
continue;
distinct.Add(test.Value);
results.AddRange(tests);
}
}
}
return new(results);
}
private static void DisableMaxDuplicates(AppSettings appSettings)
{
Record[]? records;
bool added;
string json;
string commandText;
StringBuilder result;
List<int> collection = [];
ReadOnlyCollection<Test> tests = GetTests(appSettings.InfinityQSConfiguration);
if (!Directory.Exists(appSettings.InfinityQSConfiguration.DestinationDirectory))
_ = Directory.CreateDirectory(appSettings.InfinityQSConfiguration.DestinationDirectory);
string checkFile = Path.Combine(appSettings.InfinityQSConfiguration.DestinationDirectory, ".sql");
foreach (Test test in tests)
{
added = false;
if (File.Exists(checkFile))
continue;
commandText = GetCommandText(appSettings.InfinityQSConfiguration, test);
result = GetForJsonPath(appSettings.InfinityQSConfiguration, commandText);
if (result.Length == 0)
continue;
records = JsonSerializer.Deserialize(result.ToString(), RecordCollectionSourceGenerationContext.Default.RecordArray);
if (records is null || records.Length < 1)
continue;
foreach (Record record in records)
{
if (collection.Contains(record.MaxSeSubgroup))
continue;
if (!added)
added = true;
collection.Add(record.MaxSeSubgroup);
}
if (!added)
continue;
json = JsonSerializer.Serialize(records, RecordCollectionSourceGenerationContext.Default.RecordArray);
File.WriteAllText(Path.Combine(appSettings.InfinityQSConfiguration.DestinationDirectory, $"{DateTime.Now.Ticks}.json"), json);
Thread.Sleep(500);
if (collection.Count > 1000)
break;
}
if (collection.Count > 0)
Disable(appSettings.InfinityQSConfiguration, checkFile, new(collection));
}
private static void RunMI()
{
#pragma warning disable CA1416
ProcessStartInfo processStartInfo = new("iispcmi.exe")
{
Domain = "Infineon",
UseShellExecute = false,
UserName = "ecfisysadmin",
PasswordInClearText = "j(1(P%xB=g}3w9db",
WorkingDirectory = "C:/Program Files (x86)/InfinityQS International/ProFicient/Applications"
};
Process process = Process.Start(processStartInfo) ?? throw new NullReferenceException(nameof(Process));
process.WaitForExit();
#pragma warning restore CA1416
}
internal static bool Select(AppSettings appSettings, ILogger<Worker> logger)
{
logger.LogInformation(appSettings.Company);
if (string.IsNullOrEmpty(appSettings.InfinityQSConfiguration.ConnectionString))
RunMI();
else
DisableMaxDuplicates(appSettings);
return true;
}
}