From f1bac2f5a7f3f79509ff0d461b85b53dc58e41a4 Mon Sep 17 00:00:00 2001 From: Mike Phares Date: Tue, 8 Mar 2022 17:39:25 -0700 Subject: [PATCH] Files for dotnet framework / EAF --- .../FileHandlers/DEP08SIASM/FileRead.cs | 4 - .../FileHandlers/DEP08SIASM/ProcessData.cs | 8 +- .../FileHandlers/DownloadJpegFile/FileRead.cs | 27 +- Adaptation/FileHandlers/FileRead.cs | 304 --------------- Adaptation/FileHandlers/ToArchive/FileRead.cs | 5 +- Adaptation/FileHandlers/jpeg/FileRead.cs | 24 ++ Adaptation/FileHandlers/jpeg/ProcessData.cs | 11 +- DEP08SIASM.csproj | 151 ++++++++ FileHandlers/FileRead.cs | 350 ++++++++++++++++++ Properties/AssemblyInfo.cs | 36 ++ Shared/FilePathGenerator.cs | 20 + Shared/FilePathGeneratorInfo.cs | 63 ++++ Shared/Mapper.cs | 74 ++++ 13 files changed, 744 insertions(+), 333 deletions(-) delete mode 100644 Adaptation/FileHandlers/FileRead.cs create mode 100644 DEP08SIASM.csproj create mode 100644 FileHandlers/FileRead.cs create mode 100644 Properties/AssemblyInfo.cs create mode 100644 Shared/FilePathGenerator.cs create mode 100644 Shared/FilePathGeneratorInfo.cs create mode 100644 Shared/Mapper.cs diff --git a/Adaptation/FileHandlers/DEP08SIASM/FileRead.cs b/Adaptation/FileHandlers/DEP08SIASM/FileRead.cs index 185da83..5da8116 100644 --- a/Adaptation/FileHandlers/DEP08SIASM/FileRead.cs +++ b/Adaptation/FileHandlers/DEP08SIASM/FileRead.cs @@ -16,9 +16,7 @@ namespace Adaptation.FileHandlers.DEP08SIASM; public class FileRead : Shared.FileRead, IFileRead { - private readonly bool _IsDummy; private readonly bool _IsXToAPC; - private readonly bool _IsXToIQS; private readonly bool _IsXToSPaCe; private readonly bool _IsXToSPaCeVillach; private readonly Dictionary _CellNames; @@ -35,9 +33,7 @@ public class FileRead : Shared.FileRead, IFileRead throw new Exception(cellInstanceConnectionName); if (!_IsDuplicator) throw new Exception(cellInstanceConnectionName); - _IsDummy = _Hyphens == (int)Hyphen.IsDummy; _IsXToAPC = _Hyphens == (int)Hyphen.IsXToAPC; - _IsXToIQS = _Hyphens == (int)Hyphen.IsXToIQS; _CellNames = new Dictionary(); _IsXToSPaCe = _Hyphens == (int)Hyphen.IsXToSPaCe; _IsXToSPaCeVillach = _Hyphens == (int)Hyphen.IsXToSPaCeVillach; diff --git a/Adaptation/FileHandlers/DEP08SIASM/ProcessData.cs b/Adaptation/FileHandlers/DEP08SIASM/ProcessData.cs index d8f10f0..b7a8fa1 100644 --- a/Adaptation/FileHandlers/DEP08SIASM/ProcessData.cs +++ b/Adaptation/FileHandlers/DEP08SIASM/ProcessData.cs @@ -1,10 +1,4 @@ -using Adaptation.Shared; -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; - -namespace Adaptation.FileHandlers.DEP08SIASM; +namespace Adaptation.FileHandlers.DEP08SIASM; public class ProcessData { diff --git a/Adaptation/FileHandlers/DownloadJpegFile/FileRead.cs b/Adaptation/FileHandlers/DownloadJpegFile/FileRead.cs index bc5a31d..dbcfeda 100644 --- a/Adaptation/FileHandlers/DownloadJpegFile/FileRead.cs +++ b/Adaptation/FileHandlers/DownloadJpegFile/FileRead.cs @@ -7,9 +7,10 @@ using FFMpegCore; using System; using System.Collections.Generic; using System.Diagnostics; -using System.Drawing; using System.IO; +using System.Reflection; using System.Text.Json; +using System.Threading; namespace Adaptation.FileHandlers.DownloadJpegFile; @@ -17,6 +18,7 @@ public class FileRead : Shared.FileRead, IFileRead { private readonly Timer _Timer; + private readonly string _FFmpegFileName; private readonly string _StaticFileServer; public FileRead(ISMTP smtp, Dictionary fileParameter, string cellInstanceName, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList modelObjectParameters, string equipmentDictionaryName, Dictionary> dummyRuns, bool useCyclicalForDescription, bool isEAFHosted) : @@ -32,6 +34,11 @@ public class FileRead : Shared.FileRead, IFileRead if (_IsDuplicator) throw new Exception(cellInstanceConnectionName); _StaticFileServer = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, string.Concat("CellInstance.", cellInstanceName, ".StaticFileServer")); + string entryAssemblyLocationDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + string ffmpegFileName = Path.Combine(entryAssemblyLocationDirectory, "ffmpeg.dll"); + _FFmpegFileName = Path.Combine(entryAssemblyLocationDirectory, "ffmpeg.exe"); + if (File.Exists(ffmpegFileName) && !File.Exists(_FFmpegFileName)) + File.Copy(ffmpegFileName, _FFmpegFileName); if (!Debugger.IsAttached && fileConnectorConfiguration.PreProcessingMode != FileConnectorConfiguration.PreProcessingModeEnum.Process) _Timer = new Timer(Callback, null, (int)(fileConnectorConfiguration.FileScanningIntervalInSeconds * 1000), Timeout.Infinite); else @@ -121,11 +128,19 @@ public class FileRead : Shared.FileRead, IFileRead { if (string.IsNullOrEmpty(_StaticFileServer)) throw new Exception(); - _ = FFMpegArguments - .FromUrlInput(new Uri(string.Concat("rtsp://", _StaticFileServer, '/', _FileConnectorConfiguration.SourceDirectoryCloaking))) - .OutputToFile(Path.Combine(_FileConnectorConfiguration.TargetFileLocation, $"{_CellInstanceName}_{DateTime.Now.Ticks}{_FileConnectorConfiguration.TargetFileName}")) - .ProcessSynchronously(throwOnError: false); - //FFMpeg.Snapshot(inputPath, outputPath, new Size(200, 400), TimeSpan.FromMinutes(1)); + string fileName = $"{_CellInstanceName}_{DateTime.Now.Ticks}{_FileConnectorConfiguration.TargetFileName}"; + string destFileName = Path.Combine(_FileConnectorConfiguration.TargetFileLocation, fileName); + string sourceFileName = Path.Combine(_FileConnectorConfiguration.SourceFileLocation, fileName); + if (!File.Exists(_FFmpegFileName)) + File.WriteAllText(Path.ChangeExtension(destFileName, ".err"), $"<{_FFmpegFileName}> doesn't exits!"); + else + { + _ = FFMpegArguments + .FromUrlInput(new Uri(string.Concat("rtsp://", _StaticFileServer, '/', _FileConnectorConfiguration.SourceDirectoryCloaking))) + .OutputToFile(sourceFileName) + .ProcessSynchronously(throwOnError: false); + File.Move(sourceFileName, destFileName); + } } private void Callback(object state) diff --git a/Adaptation/FileHandlers/FileRead.cs b/Adaptation/FileHandlers/FileRead.cs deleted file mode 100644 index 6fd556b..0000000 --- a/Adaptation/FileHandlers/FileRead.cs +++ /dev/null @@ -1,304 +0,0 @@ -//using Adaptation.Helpers; -//using Adaptation.Shared; -//using Adaptation.Shared.Deposition; -//using log4net; -//using System; -//using System.Collections.Generic; -//using System.IO; -//using System.Linq; -//using System.Text; -//using System.Text.Json; -//using System.Threading; - -//namespace Adaptation.FileHandlers -//{ - -// public partial class FileRead : ILogic -// { - -// private ConfigData _ConfigData; - -// public FileRead() -// { -// Logistics = new Logistics(); -// _Log = LogManager.GetLogger(typeof(FileRead)); -// } - -// public ILogic ShallowCopy() => (ILogic)MemberwiseClone(); - -// public void WaitForThread() => WaitForThread(thread: null, threadExceptions: null); - -// public Tuple GetOpenInsightTuple() -// { -// Tuple results = new(_ConfigData.OpenInsightGaNViewer, _ConfigData); -// return results; -// } - -// public Tuple> GetExtractResult(string reportFullPath, string eventName) -// { -// Tuple> results; -// _FileParameter.Clear(); -// DateTime dateTime = DateTime.Now; -// if (_ConfigData.IsEvent && _ConfigData.Duplicator is null) -// results = GetExtractResult(reportFullPath); -// else if (_ConfigData.Duplicator.HasValue) -// results = GetDuplicatorExtractResult(reportFullPath, dateTime); -// else -// { -// results = new Tuple>(string.Empty, null, new List()); -// SupportExtractResult(reportFullPath); -// } -// if (results.Item2 is null) -// results = new Tuple>(results.Item1, JsonSerializer.Deserialize("[]"), results.Item3); -// int count = results.Item2.Value.GetArrayLength(); -// if (count > 0 && _ConfigData.EafHosted) -// WritePDSF(results.Item2.Value); -// UpdateLastTicksDuration(DateTime.Now.Ticks - dateTime.Ticks); -// return results; -// } - -// private Tuple> GetExtractResult(string reportFullPath) -// { -// Tuple> results = new(string.Empty, null, new List()); -// FileInfo fileInfo = new(reportFullPath); -// Logistics = new Logistics(ConfigData.NullData, _ConfigData.CellNames, _ConfigData.MesEntities, fileInfo, useSplitForMID: false); -// SetFileParameterLotIDToLogisticsMID(); -// ProcessData processData = new(this, _ConfigData, results.Item3); -// if (!processData.AnalysisTXTResults.Any() && !processData.AnalysisXMLResults.Any() && !processData.RunMeasurements.Any()) -// throw new Exception("No Data"); -// if (processData.AnalysisTXTResults.Any()) -// Logistics.MID = processData.AnalysisTXTResults[0].LotID; -// else if (processData.RunMeasurements.Any()) -// { -// if (!processData.RunMeasurements[0].MID.StartsWith(_ConfigData.FileConnectorConfiguration.SourceFileFilter.Substring(0, 2))) -// Logistics.MID = _ConfigData.FileConnectorConfiguration.SourceFileFilter.Substring(0, 2); -// else -// Logistics.MID = processData.RunMeasurements[0].MID; -// } -// string reactor = _ConfigData.GetCurrentReactor(this); -// if (string.IsNullOrEmpty(reactor)) -// throw new Exception("Unable to match Current Reactor"); -// Logistics.ProcessJobID = reactor; -// if (processData.RunMeasurements.Any()) -// SetFileParameterLotIDToLogisticsMID(); -// results = processData.GetResults(this, _ConfigData, results.Item3); -// return results; -// } - -// private Tuple> GetDuplicatorExtractResult(string reportFullPath, DateTime dateTime) -// { -// Tuple> results; -// Tuple pdsf = ProcessDataStandardFormat.GetLogisticsColumnsAndBody(reportFullPath); -// Logistics = new Logistics(reportFullPath, pdsf.Item1); -// SetFileParameterLotIDToLogisticsMID(); -// JsonElement pdsfBodyValues = ProcessDataStandardFormat.GetArray(pdsf); -// results = new Tuple>(pdsf.Item1, pdsfBodyValues, new List()); -// List processDataDescriptions = _ConfigData.GetProcessDataDescriptions(pdsfBodyValues); -// Dictionary> keyValuePairs = ProcessData.GetKeyValuePairs(_ConfigData, pdsfBodyValues, processDataDescriptions, extra: false); -// bool isDummyRun = (ConfigData.DummyRuns.Any() && ConfigData.DummyRuns.ContainsKey(Logistics.JobID) && ConfigData.DummyRuns[Logistics.JobID].Any() && (from l in ConfigData.DummyRuns[Logistics.JobID] where l == Logistics.Sequence select 1).Any()); -// if (isDummyRun) -// { -// try -// { File.SetLastWriteTime(reportFullPath, dateTime); } -// catch (Exception) { } -// } -// bool isMock = _ConfigData.Duplicator.Value is ConfigData.Level.IsR69TXTAPCMock or ConfigData.Level.IsR71HealthCp2MgAPCMock or ConfigData.Level.IsR69TXTIQSMock or ConfigData.Level.IsR71XMLIQSMock; -// if ((isDummyRun || _Configuration.FileScanningIntervalInSeconds > 0) && _ConfigData.Duplicator.Value != ConfigData.Level.IsArchive && !isMock) -// { -// string successDirectory; -// string duplicateDirectory; -// string[] segments = Path.GetFileNameWithoutExtension(reportFullPath).Split('_'); -// if (_ConfigData.Duplicator.Value != ConfigData.Level.IsXToAPC) -// successDirectory = string.Empty; -// else -// { -// successDirectory = string.Concat(Path.GetDirectoryName(_Configuration.TargetFileLocation), @"\ViewerPath"); -// if (!Directory.Exists(successDirectory)) -// _ = Directory.CreateDirectory(successDirectory); -// } -// if (_ConfigData.Duplicator.Value is ConfigData.Level.IsXToSPaCe or ConfigData.Level.IsXToSPaCeVillach) -// duplicateDirectory = _Configuration.TargetFileLocation; -// else -// duplicateDirectory = string.Concat(_Configuration.TargetFileLocation, @"\", segments[0]); -// if (segments.Length > 2) -// duplicateDirectory = string.Concat(duplicateDirectory, @"-", segments[2]); -// if (!Directory.Exists(duplicateDirectory)) -// _ = Directory.CreateDirectory(duplicateDirectory); -// string logisticsSequence = Logistics.Sequence.ToString(); -// List> tuples = new(); -// string duplicateFile = string.Concat(duplicateDirectory, @"\", Path.GetFileName(reportFullPath)); -// if (isDummyRun || _ConfigData.Duplicator.Value != ConfigData.Level.IsXToArchive) -// { -// Test test; -// List> linesCollection; -// foreach (KeyValuePair> keyValuePair in keyValuePairs) -// { -// test = keyValuePair.Key; -// switch (test) -// { -// case Test.GRATXTCenter: -// case Test.GRATXTEdge: -// case Test.LogbookCAC: -// case Test.GrowthRateXML: -// if (_ConfigData.EafHosted) -// { -// if (_ConfigData.Duplicator.Value != ConfigData.Level.IsXToIQS || reportFullPath.EndsWith("_Health_Cp2Mg.pdsf")) -// File.Copy(reportFullPath, duplicateFile, overwrite: true); -// else -// { -// linesCollection = ProcessData.GetLines(this, _ConfigData, pdsfBodyValues, test); -// foreach (Tuple tuple in linesCollection) -// tuples.Add(new Tuple(tuple.Item1, tuple.Item2)); -// } -// } -// break; -// default: -// throw new Exception(); -// } -// } -// } -// if (_ConfigData.Duplicator.Value != ConfigData.Level.IsXToArchive) -// Shared0413(dateTime, isDummyRun, successDirectory, duplicateDirectory, tuples, duplicateFile); -// else -// { -// string destinationDirectory = WriteScopeInfo(_ConfigData.ProgressPath, Logistics, dateTime, duplicateDirectory, tuples); -// if (isDummyRun) -// Shared0607(reportFullPath, duplicateDirectory, logisticsSequence, destinationDirectory); -// } -// } -// return results; -// } - -// private void SupportExtractResult(string reportFullPath) -// { -// ConfigData.ConnectionAction connectionAction = _ConfigData.GetConnectionActionValue(); -// switch (connectionAction) -// { -// case ConfigData.ConnectionAction.MoveDLGFile: -// case ConfigData.ConnectionAction.MoveDLGFileForParse: -// case ConfigData.ConnectionAction.MoveTXTOrXMLFile: -// case ConfigData.ConnectionAction.MoveXMLFile: -// break; -// case ConfigData.ConnectionAction.RenameTXTFile: -// if (reportFullPath.Contains('#')) -// { -// string fourZeroHashTag = "40#"; -// string sixThreeHashTag = "63#"; -// string nineFiveHashTag = "95#"; -// string[] segments = Path.GetFileNameWithoutExtension(reportFullPath).Split('_'); -// if ((from l in segments where l != fourZeroHashTag && l != sixThreeHashTag && l != nineFiveHashTag select l).Any()) -// { -// string wavelengthGroup; -// string text = File.ReadAllText(reportFullPath); -// if (text.Contains("wavelength 40")) -// wavelengthGroup = "40#"; -// else if (text.Contains("wavelength 63")) -// wavelengthGroup = "63#"; -// else if (text.Contains("wavelength 95")) -// wavelengthGroup = "95#"; -// else -// wavelengthGroup = "###"; -// StringBuilder stringBuilder = new(); -// for (int i = 0; i < segments.Length; i++) -// { -// _ = stringBuilder.Append(segments[i]).Append('_'); -// if (i == 2) -// _ = stringBuilder.Append(wavelengthGroup).Append('_'); -// } -// if (stringBuilder.Length > 0) -// _ = stringBuilder.Remove(stringBuilder.Length - 1, 1); -// string fileName = Path.Combine(Path.GetDirectoryName(reportFullPath), stringBuilder.ToString()); -// File.WriteAllText(fileName, text); -// File.Delete(reportFullPath); -// } -// } -// break; -// case ConfigData.ConnectionAction.SplitCACFile: -// ProcessData.SplitCACFile(_ConfigData, reportFullPath); -// break; -// case ConfigData.ConnectionAction.MoveCACFile: -// FileInfo fileInfo = new(Path.Combine(_ConfigData.FileConnectorConfiguration.TargetFileLocation, Path.GetFileName(reportFullPath))); -// if (fileInfo.Exists && new FileInfo(reportFullPath).LastWriteTime > fileInfo.LastWriteTime) -// { -// try -// { File.Delete(fileInfo.FullName); } -// catch (Exception) { } -// Thread.Sleep(500); -// } -// break; -// case ConfigData.ConnectionAction.WritePDSFFile: -// string mesEntity = _ConfigData.CellName; -// FileInfo sourceFileInfo = new(reportFullPath); -// string extension = string.Concat(".", _ConfigData.FileConnectorConfiguration.TargetFileName.Split('.')[1]); -// string ticks = string.Concat(_ConfigData.FileConnectorConfiguration.TargetFileLocation, @"\", sourceFileInfo.LastWriteTime.Ticks); -// FileInfo pdsfFileInfo = new(string.Concat(_ConfigData.FileConnectorConfiguration.TargetFileLocation, @"\", mesEntity, "_", sourceFileInfo.LastWriteTime.ToString("yyMMddHHmmssfff"), "_dlg", extension)); -// if (pdsfFileInfo.Exists) -// throw new Exception("Destination file already exists!"); -// string pdsfText = ProcessData.GetPDSFTextFromDLG(_ConfigData, mesEntity, sourceFileInfo, useSetpoint: false, writeFiles: false, fullDateTime: false, backFill: true); -// File.WriteAllText(ticks, pdsfText); -// File.SetLastWriteTime(ticks, sourceFileInfo.LastWriteTime); -// File.Move(ticks, pdsfFileInfo.FullName); -// break; -// case ConfigData.ConnectionAction.RaiseCACFileEvent: -// case ConfigData.ConnectionAction.RaiseTXTFileEvent: -// case ConfigData.ConnectionAction.RaiseXMLFileEvent: -// throw new Exception(); -// default: -// throw new Exception(); -// } -// } - -// private void MoveArchive() -// { -// const int midLength = 7; -// const int midSegment = 5; -// const char midPadding = '0'; -// string destinationDirectory; -// string logisticsSequence = Logistics.Sequence.ToString(); -// string group = Logistics.MID.PadLeft(midLength, midPadding).Substring(0, midSegment).PadRight(midLength, midPadding); -// string rootDestinationDirectory = string.Concat(Path.GetDirectoryName(_Configuration.TargetFileLocation), @"\", Logistics.MesEntity); -// string[] matchDirectories = new string[] { GetDirectoriesRecursively(rootDestinationDirectory, logisticsSequence).FirstOrDefault() }; -// if (matchDirectories.Length == 0 || string.IsNullOrEmpty(matchDirectories[0])) -// matchDirectories = Directory.GetDirectories(rootDestinationDirectory, string.Concat('*', logisticsSequence, '*'), SearchOption.AllDirectories); -// if ((matchDirectories is null) || matchDirectories.Length != 1) -// throw new Exception("Didn't find directory by logistics sequence"); -// if (matchDirectories[0].Contains("_processing failed")) -// destinationDirectory = string.Concat(rootDestinationDirectory, @"\", "_Process_Failed"); -// else if (matchDirectories[0].Contains("_in process")) -// destinationDirectory = string.Concat(rootDestinationDirectory, @"\All_other_files_and_folders"); -// else if (matchDirectories[0].Contains("_processed")) -// destinationDirectory = string.Concat(rootDestinationDirectory, @"\- Archive\", group); -// else -// throw new Exception(); -// if (!Directory.Exists(destinationDirectory)) -// _ = Directory.CreateDirectory(destinationDirectory); -// string directoryName = Path.GetFileName(matchDirectories[0]); -// if (directoryName != logisticsSequence) -// throw new Exception("directoryName != logisticsSequence"); -// else -// { -// string sourceDirectoryName = Path.GetDirectoryName(matchDirectories[0]); -// string destinationDirectoryName = string.Concat(destinationDirectory, @"\", Path.GetFileName(sourceDirectoryName)); -// if (destinationDirectoryName != sourceDirectoryName) -// Directory.Move(sourceDirectoryName, destinationDirectoryName); -// } -// } - -// public void Move(string reportFullPath, Tuple> extractResults, Exception exception = null) -// { -// Shared1872(reportFullPath, exception); -// bool isErrorFile = exception is not null; -// if (!isErrorFile && _ConfigData.Duplicator.HasValue) -// { -// if (_ConfigData.Duplicator.Value == ConfigData.Level.IsXToArchive) -// Shared0192(reportFullPath); -// else if (_ConfigData.EafHosted && _ConfigData.Duplicator.Value == ConfigData.Level.IsArchive) -// MoveArchive(); -// if (_ConfigData.EafHosted && !string.IsNullOrEmpty(_ConfigData.ProgressPath)) -// CreateProgressDirectory(_ConfigData.ProgressPath, Logistics, (int?)_ConfigData.Duplicator, exceptionLines: null); -// } -// } - -// } - -//} \ No newline at end of file diff --git a/Adaptation/FileHandlers/ToArchive/FileRead.cs b/Adaptation/FileHandlers/ToArchive/FileRead.cs index 0a20e26..18646a2 100644 --- a/Adaptation/FileHandlers/ToArchive/FileRead.cs +++ b/Adaptation/FileHandlers/ToArchive/FileRead.cs @@ -6,7 +6,6 @@ using Adaptation.Shared.Methods; using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text.Json; namespace Adaptation.FileHandlers.ToArchive; @@ -113,9 +112,9 @@ public class FileRead : Shared.FileRead, IFileRead { if (dateTime == DateTime.MinValue) { } - Tuple> results = new(string.Empty, null, null, new List()); + Tuple> results = new(string.Empty, null, null, new List()); Tuple pdsf = ProcessDataStandardFormat.GetLogisticsColumnsAndBody(reportFullPath); - _Logistics = new Logistics(reportFullPath, pdsf.Item1); + _Logistics = new Logistics(reportFullPath, pdsf.Item1); SetFileParameterLotIDToLogisticsMID(); return results; } diff --git a/Adaptation/FileHandlers/jpeg/FileRead.cs b/Adaptation/FileHandlers/jpeg/FileRead.cs index b246b84..767e420 100644 --- a/Adaptation/FileHandlers/jpeg/FileRead.cs +++ b/Adaptation/FileHandlers/jpeg/FileRead.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Text.Json; namespace Adaptation.FileHandlers.jpeg; @@ -39,6 +40,29 @@ public class FileRead : Shared.FileRead, IFileRead throw new Exception(cellInstanceConnectionName); foreach (ModelObjectParameterDefinition modelObjectParameterDefinition in reactors) _Reactors.Add(modelObjectParameterDefinition.Name.Split('.')[1], modelObjectParameterDefinition.Value); + string entryAssemblyLocationDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + string x86 = Path.Combine(entryAssemblyLocationDirectory, "x86"); + if (!Directory.Exists(x86)) + _ = Directory.CreateDirectory(x86); + string tessdata = Path.Combine(entryAssemblyLocationDirectory, "tessdata"); + if (!Directory.Exists(tessdata)) + _ = Directory.CreateDirectory(tessdata); + string pdfttfSource = Path.Combine(entryAssemblyLocationDirectory, "pdf.ttf"); + string pdfttfDestination = Path.Combine(tessdata, Path.GetFileName(pdfttfSource)); + if (File.Exists(pdfttfSource) && !File.Exists(pdfttfDestination)) + File.Copy(pdfttfSource, pdfttfDestination); + string tesseract41dllSource = Path.Combine(entryAssemblyLocationDirectory, "tesseract41.dll"); + string tesseract41dllDestination = Path.Combine(x86, Path.GetFileName(tesseract41dllSource)); + if (File.Exists(tesseract41dllSource) && !File.Exists(tesseract41dllDestination)) + File.Copy(tesseract41dllSource, tesseract41dllDestination); + string engtraineddataSource = Path.Combine(entryAssemblyLocationDirectory, "eng.traineddata"); + string engtraineddataDestination = Path.Combine(tessdata, Path.GetFileName(engtraineddataSource)); + if (File.Exists(engtraineddataSource) && !File.Exists(engtraineddataDestination)) + File.Copy(engtraineddataSource, engtraineddataDestination); + string leptonica1800dllSource = Path.Combine(entryAssemblyLocationDirectory, "leptonica-1.80.0.dll"); + string leptonica1800dllDestination = Path.Combine(x86, Path.GetFileName(leptonica1800dllSource)); + if (File.Exists(leptonica1800dllSource) && !File.Exists(leptonica1800dllDestination)) + File.Copy(leptonica1800dllSource, leptonica1800dllDestination); } void IFileRead.Move(Tuple> extractResults, Exception exception) => Move(extractResults, exception); diff --git a/Adaptation/FileHandlers/jpeg/ProcessData.cs b/Adaptation/FileHandlers/jpeg/ProcessData.cs index a21ef15..35b4dfe 100644 --- a/Adaptation/FileHandlers/jpeg/ProcessData.cs +++ b/Adaptation/FileHandlers/jpeg/ProcessData.cs @@ -1,20 +1,13 @@ -using Adaptation.Eaf.Management.ConfigurationData.CellAutomation; -using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration; using Adaptation.Shared; -using Adaptation.Shared.Deposition; using Adaptation.Shared.Methods; using log4net; using System; using System.Collections.Generic; using System.Data; using System.Drawing; -using System.Drawing.Imaging; -using System.Globalization; using System.IO; using System.Linq; -using System.Text; using System.Text.Json; -using System.Text.Json.Serialization; using Tesseract; namespace Adaptation.FileHandlers.jpeg; @@ -105,7 +98,7 @@ public class ProcessData : IProcessData #pragma warning disable CA1416 - private static (MemoryStream memoryStream, Color[]) Get(IFileRead fileRead, int thresHold, int endY, int endX, int startY, int startX) + private static (MemoryStream memoryStream, Color[]) Get(IFileRead fileRead, int thresHold, int startX, int startY, int endX, int endY) { Color color; List colors = new(); @@ -147,7 +140,7 @@ public class ProcessData : IProcessData #pragma warning restore CA1416 - private static (MemoryStream, Color[]) Get(IFileRead fileRead, int thresHold) => Get(fileRead, thresHold, 68, 1559, 32, 1094); + private static (MemoryStream, Color[]) Get(IFileRead fileRead, int thresHold) => Get(fileRead, thresHold, 330, 16, 400, 32); private void Parse(IFileRead fileRead, List fileInfoCollection) { diff --git a/DEP08SIASM.csproj b/DEP08SIASM.csproj new file mode 100644 index 0000000..df318ce --- /dev/null +++ b/DEP08SIASM.csproj @@ -0,0 +1,151 @@ + + + + + Debug + AnyCPU + {435F7498-2A8A-4D9C-A932-8437C87F7220} + 10.0 + Library + Properties + DEP08SIASM + DEP08SIASM + v4.8 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + x86 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 4.7.0 + + + 2.39.0 + + + 1.6.1 + + + 5.0.1 + + + 4.1.1 + + + + \ No newline at end of file diff --git a/FileHandlers/FileRead.cs b/FileHandlers/FileRead.cs new file mode 100644 index 0000000..709d98a --- /dev/null +++ b/FileHandlers/FileRead.cs @@ -0,0 +1,350 @@ +using Adaptation.Eaf.Management.ConfigurationData.CellAutomation; +using Adaptation.FileHandlers; +using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration; +using Adaptation.Shared; +using Adaptation.Shared.Methods; +using Eaf.Core; +using Eaf.Core.Smtp; +using Eaf.EquipmentCore.DataCollection.Reporting; +using Eaf.EquipmentCore.SelfDescription.ElementDescription; +using Eaf.EquipmentCore.SelfDescription.EquipmentStructure; +using Eaf.EquipmentCore.SelfDescription.ParameterTypes; +using Ifx.Eaf.EquipmentConnector.File.Component.Reader; +using Ifx.Eaf.EquipmentConnector.File.SelfDescription; +using log4net; +using Shared; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; + +namespace DEP08SIASM.FileHandlers; + +public partial class FileRead : FileReaderHandler, ISMTP +{ + + private readonly ILog _Log; + private IFileRead _FileRead; + private EquipmentEvent _EquipmentEvent; + private readonly bool _UseCyclicalForDescription; + private FilePathGenerator _FilePathGeneratorForError; + private FilePathGenerator _FilePathGeneratorForTarget; + private readonly List _EquipmentParameters; + private static readonly Dictionary> _DummyRuns; + + static FileRead() => _DummyRuns = new Dictionary>(); + + public FileRead() + { + if (FileParameter is null) + FileParameter = new Dictionary(); + _FileRead = null; + _UseCyclicalForDescription = false; + _Log = LogManager.GetLogger(typeof(FileRead)); + _EquipmentParameters = new List(); + } + + public override void CreateSelfDescription() + { + MethodBase methodBase = new StackFrame().GetMethod(); + _Log.Debug(string.Concat(methodBase.Name, " - Entry")); + try + { + if (Equipment is null) + throw new Exception(); + CreateSelfDescription(methodBase); + _Log.Debug(string.Concat(methodBase.Name, " - Try - Exit")); + } + catch (Exception ex) + { + _Log.Error(string.Concat(methodBase.Name, " - Catch - Entry {", ex.Message, "}", Environment.NewLine, Environment.NewLine, ex.StackTrace)); + long breakAfter = DateTime.Now.AddSeconds(30).Ticks; + for (short i = 0; i < short.MaxValue; i++) + { + if (DateTime.Now.Ticks > breakAfter) + break; + Thread.Sleep(500); + } + throw; + } + } + + public override bool Extract(string reportFullPath, string eventName) + { + MethodBase methodBase = new StackFrame().GetMethod(); + _Log.Debug(string.Concat(methodBase.Name, " - Entry - {", reportFullPath, "}")); + Tuple> extractResults = null; + try + { + extractResults = _FileRead.GetExtractResult(reportFullPath, eventName); + TriggerEvents(extractResults); + _FileRead.Move(extractResults); + FilePathGeneratorInfoMove(extractResults); + _FileRead.WaitForThread(); + _Log.Debug(string.Concat(methodBase.Name, " - Try - Exit")); + return true; + } + catch (Exception ex) + { + _Log.Error(string.Concat(methodBase.Name, " - Catch - Entry {", ex.Message, "}", Environment.NewLine, Environment.NewLine, ex.StackTrace)); + _FileRead.Move(extractResults, exception: ex); + FilePathGeneratorInfoMove(extractResults, exception: ex); + return false; + } + } + + private void Send(EmailMessage emailMessage) + { + ISmtp smtp = Backbone.Instance.GetBackboneComponentsOfType().SingleOrDefault(); + if (smtp is not null) + smtp.Send(emailMessage); + } + + void ISMTP.SendLowPriorityEmailMessage(string subject, string body) + { + EmailMessage emailMessage = new(subject, body, MailPriority.Low); + Send(emailMessage); + } + + void ISMTP.SendHighPriorityEmailMessage(string subject, string body) + { + EmailMessage emailMessage = new(subject, body, MailPriority.High); + Send(emailMessage); + } + + void ISMTP.SendNormalPriorityEmailMessage(string subject, string body) + { + EmailMessage emailMessage = new(subject, body, MailPriority.Normal); + Send(emailMessage); + } + + private void AddParameterRangeAndEvent() + { + string description; + bool allowNull = false; + EquipmentParameter equipmentParameter; + JsonProperty[] jsonProperties = _FileRead.GetDefault(); + Dictionary keyValuePairs = _FileRead.GetDisplayNamesJsonElement(); + Dictionary parameterTypeDefinitions = new(); + FileConnectorParameterTypeDefinitionProvider fileConnectorParameterTypeDefinitionProvider = new(); + foreach (ParameterTypeDefinition parameterTypeDefinition in fileConnectorParameterTypeDefinitionProvider.GetAllParameterTypeDefinition()) + { + switch (parameterTypeDefinition.Name) + { + case nameof(String): + parameterTypeDefinitions.Add(JsonValueKind.String, parameterTypeDefinition); + break; + case nameof(Double): + parameterTypeDefinitions.Add(JsonValueKind.Number, parameterTypeDefinition); + break; + case nameof(Boolean): + parameterTypeDefinitions.Add(JsonValueKind.True, parameterTypeDefinition); + parameterTypeDefinitions.Add(JsonValueKind.False, parameterTypeDefinition); + break; + default: + break; + } + } + foreach (JsonProperty jsonProperty in jsonProperties) + { + if (jsonProperty.Value.ValueKind == JsonValueKind.Object && !parameterTypeDefinitions.ContainsKey(JsonValueKind.Object)) + { + StructuredType structuredType = new(nameof(StructuredType), string.Empty, new List()); + parameterTypeDefinitions.Add(JsonValueKind.Object, structuredType); + Equipment.SelfDescriptionBuilder.AddParameterTypeDefinition(structuredType); + } + if (!parameterTypeDefinitions.ContainsKey(jsonProperty.Value.ValueKind)) + throw new Exception(string.Concat('{', jsonProperty.Value.ValueKind, "} is not mapped!")); + } + foreach (JsonProperty jsonProperty in jsonProperties) + { + if (jsonProperty.Value.ValueKind == JsonValueKind.Null && !allowNull) + throw new Exception(); + if (jsonProperty.Value.ValueKind != JsonValueKind.String || !keyValuePairs.ContainsKey(jsonProperty.Name)) + description = string.Empty; + else + description = keyValuePairs[jsonProperty.Name].Split('|')[0]; + equipmentParameter = new EquipmentParameter(jsonProperty.Name, parameterTypeDefinitions[jsonProperty.Value.ValueKind], description); + _EquipmentParameters.Add(equipmentParameter); + } + _ = Equipment.SelfDescriptionBuilder.RootEquipmentElementBuilder.AddParameterRange(_EquipmentParameters); + _EquipmentEvent = new EquipmentEvent(_FileRead.EventName, _FileRead.GetEventDescription(), _EquipmentParameters); + _ = Equipment.SelfDescriptionBuilder.RootEquipmentElementBuilder.AddEvent(_EquipmentEvent); + } + + private void CreateSelfDescription(MethodBase methodBase) + { + string cellInstanceName; + string equipmentTypeName = string.Empty; + string equipmentDictionaryName = string.Empty; + EquipmentElement equipmentElement = Equipment.SelfDescriptionBuilder.RootEquipmentElementBuilder.Item; + if (Backbone.Instance?.CellName is null) + cellInstanceName = string.Empty; + else + cellInstanceName = Backbone.Instance.CellName; + string cellInstanceConnectionName = equipmentElement.Name; + FileConnectorConfiguration fileConnectorConfiguration = Mapper.Map(Configuration); + string parameterizedModelObjectDefinitionType = methodBase.DeclaringType.FullName; + IList modelObjectParameters = Mapper.Map(ConfiguredParameters); + _FileRead = CellInstanceConnectionName.Get(this, FileParameter, cellInstanceName, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, _DummyRuns, _UseCyclicalForDescription, isEAFHosted: true); + if (_FileRead.IsEvent) + AddParameterRangeAndEvent(); + } + + private object GetFilePathGeneratorInfo(string reportFullPath, bool isErrorFile) + { + FilePathGeneratorInfo result; + FilePathGenerator filePathGeneratorOriginal; + if (Configuration is null) + result = null; + else + { + if (isErrorFile) + { + if (_FilePathGeneratorForError is null) + _FilePathGeneratorForError = new FilePathGenerator(Configuration, reportFullPath, isErrorFile: true); + filePathGeneratorOriginal = _FilePathGeneratorForError; + } + else + { + if (_FilePathGeneratorForTarget is null) + _FilePathGeneratorForTarget = new FilePathGenerator(Configuration, reportFullPath, isErrorFile: false); + filePathGeneratorOriginal = _FilePathGeneratorForTarget; + } + result = new FilePathGeneratorInfo(filePathGeneratorOriginal, reportFullPath, isErrorFile, FileParameter); + } + return result; + } + + private void FilePathGeneratorInfoMove(Tuple> extractResults, Exception exception = null) + { + bool isErrorFile = exception is not null; + object filePathGeneratorInfo = GetFilePathGeneratorInfo(_FileRead.ReportFullPath, isErrorFile); + if (filePathGeneratorInfo is not null and FilePathGeneratorInfo filePathGenerator) + { + string[] exceptionLines = _FileRead.Move(extractResults, filePathGenerator.To, filePathGenerator.From, filePathGenerator.ResolvedFileLocation, exception); + if (isErrorFile) + { + try + { + StringBuilder stringBuilder = new(); + foreach (string item in exceptionLines) + _ = stringBuilder.Append("<").Append(item).AppendLine(">"); + ISmtp smtp = Backbone.Instance.GetBackboneComponentsOfType().SingleOrDefault(); + EmailMessage emailMessage = new(_FileRead.ExceptionSubject, stringBuilder.ToString(), MailPriority.High); + smtp.Send(emailMessage); + } + catch (Exception) { } + } + } + } + + private List GetParameterValues(List headerNames, JsonElement[] jsonElements, int i) + { + List results = new(); + if (_UseCyclicalForDescription && i > 0) + throw new Exception(); + object value; + List list; + JsonProperty[] jsonProperties = jsonElements[i].EnumerateObject().ToArray(); + if (jsonProperties.Length != _EquipmentParameters.Count) + throw new Exception(); + for (int p = 0; p < jsonProperties.Length; p++) + { + if (!_UseCyclicalForDescription || headerNames.Contains(jsonProperties[p].Name)) + value = jsonProperties[p].Value.ToString(); + else + { + list = new List(); + for (int z = 0; z < jsonElements.Length; z++) + list.Add(new object[] { z, jsonElements[z].GetProperty(jsonProperties[p].Name).ToString() }); + value = list; + } + results.Add(new ParameterValue(_EquipmentParameters[p], value, DateTime.Now)); + } + return results; + } + + private void TriggerEvents(Tuple> extractResults) + { + List headerNames; + List parameters; + if (!_UseCyclicalForDescription) + headerNames = null; + else + headerNames = _FileRead.GetHeaderNames(); + for (int i = 0; i < extractResults.Item3.Length; i++) + { + if (_EquipmentEvent is not null) + { + _Log.Debug(string.Concat("TriggerEvent - {", _FileRead.ReportFullPath, "} ", i, " of ", extractResults.Item3.Length)); + parameters = GetParameterValues(headerNames, extractResults.Item3, i); + if (_EquipmentEvent is not null) + Equipment.DataCollection.TriggerEvent(_EquipmentEvent, parameters); + if (_UseCyclicalForDescription) + break; + } + } + } + + public Tuple> ReExtract(string json) + { + Tuple> results; + string cellInstanceName; + if (!json.Contains(nameof(cellInstanceName))) + throw new Exception(); + string equipmentTypeName; + if (!json.Contains(nameof(equipmentTypeName))) + throw new Exception(); + string equipmentDictionaryName; + if (!json.Contains(nameof(equipmentDictionaryName))) + throw new Exception(); + string cellInstanceConnectionName; + if (!json.Contains(nameof(cellInstanceConnectionName))) + throw new Exception(); + if (!json.Contains(nameof(FileConnectorConfiguration))) + throw new Exception(); + if (!json.Contains(nameof(IList))) + throw new Exception(); + string parameterizedModelObjectDefinitionType; + if (!json.Contains(nameof(parameterizedModelObjectDefinitionType))) + throw new Exception(); + Dictionary> dummyRuns = new(); + Dictionary fileParameter = new(); + MethodBase methodBase = new StackFrame().GetMethod(); + JsonElement jsonElement = JsonSerializer.Deserialize(json); + cellInstanceName = jsonElement.GetProperty(nameof(cellInstanceName)).ToString(); + equipmentTypeName = jsonElement.GetProperty(nameof(equipmentTypeName)).ToString(); + equipmentDictionaryName = jsonElement.GetProperty(nameof(equipmentDictionaryName)).ToString(); + cellInstanceConnectionName = jsonElement.GetProperty(nameof(cellInstanceConnectionName)).ToString(); + JsonElement fileConnectorConfigurationJsonElement = jsonElement.GetProperty(nameof(FileConnectorConfiguration)); + parameterizedModelObjectDefinitionType = jsonElement.GetProperty(nameof(parameterizedModelObjectDefinitionType)).ToString(); + if (fileConnectorConfigurationJsonElement.ValueKind != JsonValueKind.Object) + throw new Exception(); + JsonSerializerOptions jsonSerializerOptions = new() { Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; + FileConnectorConfiguration fileConnectorConfiguration = JsonSerializer.Deserialize(fileConnectorConfigurationJsonElement.ToString(), jsonSerializerOptions); + JsonElement modelObjectParameterDefinitionJsonElement = jsonElement.GetProperty(nameof(IList)); + if (modelObjectParameterDefinitionJsonElement.ValueKind != JsonValueKind.Array) + throw new Exception(); + IList modelObjectParameters = JsonSerializer.Deserialize>(modelObjectParameterDefinitionJsonElement.ToString(), jsonSerializerOptions); + _FileRead = CellInstanceConnectionName.Get(this, FileParameter, cellInstanceName, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, _DummyRuns, _UseCyclicalForDescription, isEAFHosted: false); + results = _FileRead.ReExtract(); + if (results?.Item2 is null) + throw new Exception(); + else + { + TriggerEvents(results); + _FileRead.Move(results); + FilePathGeneratorInfoMove(results); + } + return results; + } + +} +// 2022-02-15 -> FileRead \ No newline at end of file diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..dc65d63 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DEP08SIASM")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Infineon Technologies")] +[assembly: AssemblyProduct("DEP08SIASM")] +[assembly: AssemblyCopyright("Copyright © Infineon Technologies 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("435f7498-2a8a-4d9c-a932-8437c87f7220")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("2.39.0.0")] +[assembly: AssemblyFileVersion("2.39.0.0")] diff --git a/Shared/FilePathGenerator.cs b/Shared/FilePathGenerator.cs new file mode 100644 index 0000000..490ca8c --- /dev/null +++ b/Shared/FilePathGenerator.cs @@ -0,0 +1,20 @@ +using Ifx.Eaf.EquipmentConnector.File.Component; +using Ifx.Eaf.EquipmentConnector.File.Configuration; +using System.Collections.Generic; + +namespace Shared; + +public class FilePathGenerator : Ifx.Eaf.EquipmentConnector.File.Component.FilePathGenerator +{ + + public FileConnectorConfiguration FileConnectorConfiguration { get; private set; } + + public FilePathGenerator(FileConnectorConfiguration config, Dictionary customPattern = null) : base(config, customPattern) => FileConnectorConfiguration = config; + + public FilePathGenerator(FileConnectorConfiguration config, File file, bool isErrorFile = false, Dictionary customPattern = null) : base(config, file, isErrorFile, customPattern) => FileConnectorConfiguration = config; + + public FilePathGenerator(FileConnectorConfiguration config, string sourceFilePath, bool isErrorFile = false, Dictionary customPattern = null) : base(config, sourceFilePath, isErrorFile, customPattern) => FileConnectorConfiguration = config; + + public string GetSubFolderPath() => SubFolderPath; + +} diff --git a/Shared/FilePathGeneratorInfo.cs b/Shared/FilePathGeneratorInfo.cs new file mode 100644 index 0000000..bb6393e --- /dev/null +++ b/Shared/FilePathGeneratorInfo.cs @@ -0,0 +1,63 @@ +using System.IO; + +namespace Shared; + +public class FilePathGeneratorInfo +{ + + public string To { get; protected set; } + public string From { get; protected set; } + public bool IsErrorFile { get; protected set; } + public string SubFolderPath { get; protected set; } + public string FirstDirectory { get; protected set; } + public string ReportFullPath { get; protected set; } + public string ResolvedFileLocation { get; protected set; } + + public FilePathGeneratorInfo(object originalFilePathGenerator, string reportFullPath, bool isErrorFile, System.Collections.Generic.Dictionary fileParameter) + { + ReportFullPath = reportFullPath; + IsErrorFile = isErrorFile; + if (originalFilePathGenerator is null || originalFilePathGenerator is not FilePathGenerator original) + { + FirstDirectory = string.Empty; + ResolvedFileLocation = string.Empty; + To = string.Empty; + From = string.Empty; + } + else + { + string directorySeparatorChar = Path.DirectorySeparatorChar.ToString(); + FilePathGenerator filePathGenerator = new(original.FileConnectorConfiguration, reportFullPath, isErrorFile); + SubFolderPath = filePathGenerator.GetSubFolderPath(); + if (string.IsNullOrEmpty(SubFolderPath)) + FirstDirectory = SubFolderPath; + else + FirstDirectory = SubFolderPath.Split(Path.DirectorySeparatorChar)[0]; + ResolvedFileLocation = filePathGenerator.GetTargetFolder(); + if (string.IsNullOrEmpty(ResolvedFileLocation) && string.IsNullOrEmpty(SubFolderPath)) + To = string.Empty; + else if (string.IsNullOrEmpty(SubFolderPath)) + To = ResolvedFileLocation; + else + To = string.Concat(ResolvedFileLocation.Replace(SubFolderPath, string.Empty), Path.DirectorySeparatorChar, FirstDirectory); +#if (true) + if (string.IsNullOrEmpty(original.FileConnectorConfiguration.DefaultPlaceHolderValue)) + original.FileConnectorConfiguration.DefaultPlaceHolderValue = "NA"; + if (fileParameter is not null && fileParameter.Count == 1 && To.Contains(original.FileConnectorConfiguration.DefaultPlaceHolderValue)) + { + foreach (System.Collections.Generic.KeyValuePair keyValuePair in fileParameter) + To = To.Replace(string.Concat(original.FileConnectorConfiguration.DefaultPlaceHolderValue), keyValuePair.Value); + } +#endif + if (original.FileConnectorConfiguration.SourceFileLocation.EndsWith(directorySeparatorChar)) + From = string.Concat(original.FileConnectorConfiguration.SourceFileLocation, FirstDirectory); + else + From = string.Concat(original.FileConnectorConfiguration.SourceFileLocation, Path.DirectorySeparatorChar, FirstDirectory); + if (From.EndsWith(directorySeparatorChar) && !To.EndsWith(directorySeparatorChar)) + To = string.Concat(To, Path.DirectorySeparatorChar); + else if (To.EndsWith(directorySeparatorChar) && !From.EndsWith(directorySeparatorChar)) + To = To.Remove(To.Length - 1, 1); + } + } + +} diff --git a/Shared/Mapper.cs b/Shared/Mapper.cs new file mode 100644 index 0000000..7b06a06 --- /dev/null +++ b/Shared/Mapper.cs @@ -0,0 +1,74 @@ +using Eaf.Management.ConfigurationData.CellAutomation; +using Ifx.Eaf.EquipmentConnector.File.Configuration; +using System.Collections.Generic; + +namespace Shared; + +public static class Mapper +{ + + internal static Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration Map(FileConnectorConfiguration configuration) + { + Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration result = new() + { + AlternateTargetFolder = configuration.AlternateTargetFolder, + ConnectionRetryInterval = configuration.ConnectionRetryInterval, + ConnectionSettings = new List(), + CopySourceFolderStructure = configuration.CopySourceFolderStructure, + DefaultPlaceHolderValue = configuration.DefaultPlaceHolderValue, + //DeleteAbandonedEmptySourceSubFolders = configuration.DeleteAbandonedEmptySourceSubFolders, + DeleteEmptySourceSubFolders = configuration.DeleteEmptySourceSubFolders, + ErrorPostProcessingMode = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.PostProcessingModeEnum)configuration.ErrorPostProcessingMode, + ErrorTargetFileLocation = configuration.ErrorTargetFileLocation, + ErrorTargetFileName = configuration.ErrorTargetFileName, + FileAgeFilterMode = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.FileAgeFilterEnum)configuration.FileAgeFilterMode, + FileAgeThreshold = configuration.FileAgeThreshold, + //FileHandlers = configuration.FileHandlers, + FileHandleTimeout = (long)configuration.FileHandleTimeout, + FileHandleWaitTime = configuration.FileHandleWaitTime, + FileScanningIntervalInSeconds = configuration.FileScanningIntervalInSeconds, + FileScanningOption = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.FileScanningOptionEnum)configuration.FileScanningOption, + FolderAgeCheckIndividualSubFolders = configuration.FolderAgeCheckIndividualSubFolders, + FolderAgeThreshold = configuration.FolderAgeThreshold, + //FolderOperationsSubFolderLevel = configuration.FolderOperationsSubFolderLevel, + IdleEventWaitTimeInSeconds = (long)configuration.IdleEventWaitTimeInSeconds, + IfFileExistAction = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.IfFileExistEnum)configuration.IfFileExistAction, + IfPostProcessingFailsAction = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.IfPostProcessingFailsEnum)configuration.IfPostProcessingFailsAction, + IncludeSubDirectories = configuration.IncludeSubDirectories, + PostProcessingRetries = configuration.PostProcessingRetries, + PreProcessingMode = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.PreProcessingModeEnum)configuration.PreProcessingMode, + PostProcessingMode = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.PostProcessingModeEnum)configuration.PostProcessingMode, + SourceDirectoryCloaking = configuration.SourceDirectoryCloaking, + SourceFileFilter = configuration.SourceFileFilter, + SourceFileFilters = configuration.SourceFileFilters, + SourceFileLocation = configuration.SourceFileLocation, + TargetFileLocation = configuration.TargetFileLocation, + TargetFileName = configuration.TargetFileName, + TriggerOnChanged = configuration.TriggerOnChanged, + TriggerOnCreated = configuration.TriggerOnCreated, + UseZip64Mode = configuration.UseZip64Mode, + ZipErrorTargetFileName = configuration.ZipErrorTargetFileName, + ZipFileAmount = configuration.ZipFileAmount, + ZipFileSubFolderLevel = configuration.ZipFileSubFolderLevel, + ZipFileTime = configuration.ZipFileTime, + ZipMode = (Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration.FileConnectorConfiguration.ZipModeEnum)configuration.ZipMode, + ZipTargetFileName = configuration.ZipTargetFileName, + }; + foreach (Ifx.Eaf.Common.Configuration.ConnectionSetting connectionSetting in configuration.ConnectionSettings) + result.ConnectionSettings.Add(new Adaptation.Ifx.Eaf.Common.Configuration.ConnectionSetting(connectionSetting.Name, connectionSetting.Value)); + return result; + } + + internal static IList Map(IList configuredParameters) + { + List results = new(); + Adaptation.Eaf.Management.ConfigurationData.CellAutomation.ModelObjectParameterType modelObjectParameterType; + for (int i = 0; i < configuredParameters.Count; i++) + { + modelObjectParameterType = (Adaptation.Eaf.Management.ConfigurationData.CellAutomation.ModelObjectParameterType)configuredParameters[i].ValueType; + results.Add(new Adaptation.Eaf.Management.ConfigurationData.CellAutomation.ModelObjectParameterDefinition() { Id = i, Name = configuredParameters[i].Name, Value = configuredParameters[i].Value, ValueType = modelObjectParameterType, EnumType = modelObjectParameterType.ToString() }); + } + return results; + } + +}