Files
dep08cepiepsilon/Adaptation/FileHandlers/StatusQueryV2InstanceStatuses/FileRead.cs

248 lines
11 KiB
C#

using Adaptation.Eaf.Management.ConfigurationData.CellAutomation;
using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using Adaptation.Shared;
using Adaptation.Shared.Duplicator;
using Adaptation.Shared.Methods;
using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
namespace Adaptation.FileHandlers.StatusQueryV2InstanceStatuses;
#nullable enable
public class FileRead : Shared.FileRead, IFileRead
{
private readonly Timer _Timer;
private readonly HttpClient _HttpClient;
public FileRead(ISMTP smtp, Dictionary<string, string> fileParameter, string cellInstanceName, int? connectionCount, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList<ModelObjectParameterDefinition> modelObjectParameters, string equipmentDictionaryName, Dictionary<string, List<long>> dummyRuns, Dictionary<long, List<Shared.Metrology.WS.Results>> staticRuns, bool useCyclicalForDescription, bool isEAFHosted) :
base(new Description(), false, smtp, fileParameter, cellInstanceName, connectionCount, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, staticRuns, useCyclicalForDescription, isEAFHosted: connectionCount is null)
{
_MinFileLength = 10;
_NullData = string.Empty;
_Logistics = new(this);
if (_FileParameter is null)
throw new Exception(cellInstanceConnectionName);
if (_ModelObjectParameterDefinitions is null)
throw new Exception(cellInstanceConnectionName);
string statusQueryV2URL = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "Status.Query.V2.URL");
_HttpClient = new(new HttpClientHandler() { UseDefaultCredentials = true }) { BaseAddress = new(statusQueryV2URL) };
if (!Debugger.IsAttached && fileConnectorConfiguration.PreProcessingMode != FileConnectorConfiguration.PreProcessingModeEnum.Process && fileConnectorConfiguration.FileScanningIntervalInSeconds is not null)
_Timer = new Timer(Callback, null, (int)(fileConnectorConfiguration.FileScanningIntervalInSeconds.Value * 1000), Timeout.Infinite);
else
{
_Timer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite);
Callback(null);
}
}
void IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, Exception exception)
{
bool isErrorFile = exception is not null;
if (!isErrorFile && !string.IsNullOrEmpty(_Logistics.ReportFullPath))
{
FileInfo fileInfo = new(_Logistics.ReportFullPath);
if (fileInfo.Exists && fileInfo.LastWriteTime < fileInfo.CreationTime)
File.SetLastWriteTime(_Logistics.ReportFullPath, fileInfo.CreationTime);
}
Move(extractResults);
}
void IFileRead.WaitForThread() =>
WaitForThread(thread: null, threadExceptions: null);
string IFileRead.GetEventDescription()
{
string result = _Description.GetEventDescription();
return result;
}
List<string> IFileRead.GetHeaderNames()
{
List<string> results = _Description.GetHeaderNames();
return results;
}
string[] IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, string to, string from, string resolvedFileLocation, Exception exception)
{
string[] results = Move(extractResults, to, from, resolvedFileLocation, exception);
return results;
}
JsonProperty[] IFileRead.GetDefault()
{
JsonProperty[] results = _Description.GetDefault(this, _Logistics);
return results;
}
Dictionary<string, string> IFileRead.GetDisplayNamesJsonElement()
{
Dictionary<string, string> results = _Description.GetDisplayNamesJsonElement(this);
return results;
}
List<IDescription> IFileRead.GetDescriptions(IFileRead fileRead, List<Test> tests, IProcessData processData)
{
List<IDescription> results = _Description.GetDescriptions(fileRead, _Logistics, tests, processData);
return results;
}
Tuple<string, Test[], JsonElement[], List<FileInfo>> IFileRead.GetExtractResult(string reportFullPath, string eventName)
{
Tuple<string, Test[], JsonElement[], List<FileInfo>> results;
if (string.IsNullOrEmpty(eventName))
throw new Exception();
_ReportFullPath = reportFullPath;
DateTime dateTime = DateTime.Now;
results = GetExtractResult(reportFullPath, dateTime);
if (results.Item3 is null)
results = new Tuple<string, Test[], JsonElement[], List<FileInfo>>(results.Item1, Array.Empty<Test>(), Array.Empty<JsonElement>(), results.Item4);
if (results.Item3.Length > 0 && _IsEAFHosted)
WritePDSF(this, results.Item3);
UpdateLastTicksDuration(DateTime.Now.Ticks - dateTime.Ticks);
return results;
}
Tuple<string, Test[], JsonElement[], List<FileInfo>> IFileRead.ReExtract()
{
Tuple<string, Test[], JsonElement[], List<FileInfo>> results;
List<string> headerNames = _Description.GetHeaderNames();
Dictionary<string, string> keyValuePairs = _Description.GetDisplayNamesJsonElement(this);
results = ReExtract(this, headerNames, keyValuePairs);
return results;
}
private Tuple<string, Test[], JsonElement[], List<FileInfo>> GetExtractResult(string reportFullPath, DateTime dateTime) =>
throw new Exception(string.Concat("See ", nameof(Callback)));
private void ExportXmlToJson()
{
string xml;
string sourceDirectory = Path.GetFullPath(_FileConnectorConfiguration.SourceFileLocation);
string fileName = Path.Combine(sourceDirectory, $"{_FileConnectorConfiguration.SourceFileFilter}.xml");
if (!Directory.Exists(sourceDirectory))
_ = Directory.CreateDirectory(sourceDirectory);
_Log.Info($"Downloading from URL: {_HttpClient.BaseAddress}");
HttpResponseMessage httpResponseMessage = _HttpClient.GetAsync(_HttpClient.BaseAddress).Result;
xml = httpResponseMessage.Content.ReadAsStringAsync().Result;
File.WriteAllText(fileName, xml);
_Log.Info($"File saved: {fileName}");
Parse(_Log, sourceDirectory, _FileConnectorConfiguration.SourceFileFilter, xml);
}
private static void Parse(ILog log, string sourceDirectory, string name, string xml)
{
ArrayOfRuntimeInstanceStatusReport? arrayOfRuntimeInstanceStatusReport = ParseXML<ArrayOfRuntimeInstanceStatusReport>(xml, throwExceptions: true);
if (arrayOfRuntimeInstanceStatusReport is not null)
WriteAllText(log, sourceDirectory, name, arrayOfRuntimeInstanceStatusReport);
}
private static T? ParseXML<T>(string value, bool throwExceptions) where T : class
{
object? result;
try
{
Stream stream = ToStream(value.Trim());
XmlReader xmlReader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
#pragma warning disable IL2026, IL2090
XmlSerializer xmlSerializer = new(typeof(T), typeof(T).GetNestedTypes());
result = xmlSerializer.Deserialize(xmlReader);
#pragma warning restore IL2026, IL2090
stream.Dispose();
}
catch (Exception)
{
result = null;
if (throwExceptions)
throw;
}
return result as T;
}
private static MemoryStream ToStream(string value)
{
MemoryStream memoryStream = new();
StreamWriter streamWriter = new(memoryStream);
streamWriter.Write(value);
streamWriter.Flush();
memoryStream.Position = 0;
return memoryStream;
}
private static void WriteAllText(ILog log, string sourceDirectory, string name, ArrayOfRuntimeInstanceStatusReport arrayOfRuntimeInstanceStatusReport)
{
string json;
string fileName = Path.Combine(sourceDirectory, $"{name}.json");
JsonSerializerOptions jsonSerializerOptions = new() { WriteIndented = true };
json = Serialize(jsonSerializerOptions, arrayOfRuntimeInstanceStatusReport)
.Replace("\"\"", "null")
.Replace("\"true\"", "true")
.Replace("\"True\"", "true")
.Replace("\"false\"", "false")
.Replace("\"False\"", "false");
File.WriteAllText(fileName, json);
log.Info($"File saved: {fileName}");
Record[]? records = JsonSerializer.Deserialize(json, RecordSourceGenerationContext.Default.RecordArray);
if (records is not null)
{
string key;
Dictionary<string, Record> keyValuePairs = new();
foreach (Record record in records)
{
key = $"{record.CellInstanceName}";
if (!keyValuePairs.ContainsKey(key))
keyValuePairs.Add(key, record);
if (record.Startable is null || !record.Startable.Value)
continue;
log.Info($"CellInstanceName: {record.CellInstanceName}, MachineName: {record.MachineName}, State: {record.State}, ErrorDescription: {record.ErrorDescription}");
}
json = JsonSerializer.Serialize(keyValuePairs, DictionaryStringRecordSourceGenerationContext.Default.DictionaryStringRecord);
File.WriteAllText($"{fileName}.json", json);
}
}
private static string Serialize(JsonSerializerOptions jsonSerializerOptions, ArrayOfRuntimeInstanceStatusReport arrayOfRuntimeInstanceStatusReport) =>
#pragma warning disable IL3050, IL2026
JsonSerializer.Serialize(arrayOfRuntimeInstanceStatusReport.RuntimeInstanceStatusReport, jsonSerializerOptions);
#pragma warning restore IL3050, IL2026
private void Callback(object? state)
{
try
{ ExportXmlToJson(); }
catch (Exception exception)
{
string subject = string.Concat("Exception:", _CellInstanceConnectionName);
string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace);
try
{ _SMTP.SendHighPriorityEmailMessage(subject, body); }
catch (Exception) { }
}
try
{
if (_FileConnectorConfiguration.FileScanningIntervalInSeconds is null)
throw new NotImplementedException();
TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks);
_ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite);
}
catch (Exception exception)
{
string subject = string.Concat("Exception:", _CellInstanceConnectionName);
string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace);
try
{ _SMTP.SendHighPriorityEmailMessage(subject, body); }
catch (Exception) { }
}
}
}