712 lines
41 KiB
C#

using Adaptation.Eaf.Management.ConfigurationData.CellAutomation;
using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using Adaptation.Shared;
using Adaptation.Shared.Metrology;
using Infineon.Monitoring.MonA;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Threading;
namespace Adaptation.Helpers
{
public partial class ConfigData : ConfigDataBase
{
internal class Reactor
{
public string Name { get; internal set; }
public string FilePrefix { get; internal set; }
}
internal const object NullData = null;
internal const int MinFileLength = 100;
public bool EC { get; private set; }
public string ApcPath { get; private set; }
public string EdaPath { get; private set; }
public string IqsFile { get; private set; }
public string IqsPath { get; private set; }
public string TracePath { get; private set; }
public Level? Duplicator { get; private set; }
public string IfxChannel { get; private set; }
public string IfxSubject { get; private set; }
public string IqsTempPath { get; private set; }
public string VillachPath { get; private set; }
public string LogisticPath { get; private set; }
public string ProgressPath { get; private set; }
public string IqsQueryFilter { get; private set; }
public string IfxSubjectPrefix { get; private set; }
public List<string> MappedParts { get; private set; }
public string OpenInsightSiViewer { get; internal set; }
public string ArchiveSourceDirectory { get; private set; }
public string ConnectionStringIrmnSpc { get; private set; }
public string ConnectionStringG4Wafers { get; private set; }
public string IfxConfigurationLocation { get; private set; }
public List<string> TransportSetupMessages { get; private set; }
public string IfxConfigurationLocationLocalCopy { get; private set; }
public static Dictionary<string, List<long>> DummyRuns { get; private set; }
private Timer _Timer;
private int _LastDummyRunIndex;
private readonly Calendar _Calendar;
private readonly string _ReportFullPath;
public ConfigData(ILogic logic, string cellName, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, IList<ModelObjectParameterDefinition> modelObjectParameterDefinitions, string parameterizedModelObjectDefinitionType, bool isEAFHosted) :
base(cellName, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, isEAFHosted)
{
_LastDummyRunIndex = -1;
TransportSetupMessages = new List<string>();
CultureInfo cultureInfo = new CultureInfo("en-US");
_Calendar = cultureInfo.Calendar;
string firstSourceFileFilter = fileConnectorConfiguration.SourceFileFilter.Split('|')[0];
IsSourceTimer = (fileConnectorConfiguration.SourceFileFilter == "*Timer.txt");
if (DummyRuns is null)
DummyRuns = new Dictionary<string, List<long>>();
bool isDuplicator = cellInstanceConnectionName.StartsWith(cellName);
if (!isDuplicator)
Duplicator = null;
else
{
CellNames.Add(cellName, cellName);
MesEntities.Add(cellName, cellName);
int level = (cellInstanceConnectionName.Length - cellInstanceConnectionName.Replace("-", string.Empty).Length);
Duplicator = (Level)level;
}
if (isDuplicator)
ProcessDataDescription = new Duplicator.Description();
else
ProcessDataDescription = new ProcessData.FileRead.Description();
if (!isDuplicator)
{
//Verify(fileConnectorConfiguration, cellInstanceConnectionName);
if (!EafHosted)
VerifyProcessDataDescription(logic);
else
WriteExportAliases(logic, cellName, cellInstanceConnectionName);
}
MappedParts = new List<string>();
System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
EC = (ipGlobalProperties.DomainName.ToLower().Contains("ec.local"));
bool isMET08PRFUSB4000Villach = (equipmentElementName == string.Concat(EquipmentType.MET08PRFUSB4000, "_Villach"));
if (!modelObjectParameterDefinitions.Any())
{
CellNames.Add(cellName, "****"); MesEntities.Add(cellName, "****");
IfxChannel = string.Empty;
IfxSubjectPrefix = string.Empty;
IfxConfigurationLocation = string.Empty;
IfxConfigurationLocationLocalCopy = string.Empty;
IfxSubject = string.Empty;
ArchiveSourceDirectory = string.Empty;
ConnectionStringG4Wafers = string.Empty;
ConnectionStringIrmnSpc = string.Empty;
}
else
{
int index;
string key;
string variable = string.Empty;
Dictionary<string, string> iqsSection = new Dictionary<string, string>();
Dictionary<string, string> pathSection = new Dictionary<string, string>();
Dictionary<string, string> tibcoSection = new Dictionary<string, string>();
Dictionary<string, string> commonSection = new Dictionary<string, string>();
List<Tuple<string, string>> reactorTuples = new List<Tuple<string, string>>();
Dictionary<string, string> openInsightSection = new Dictionary<string, string>();
Dictionary<string, string> connectionStringsSection = new Dictionary<string, string>();
Dictionary<string, Dictionary<string, string>> reactorSection = new Dictionary<string, Dictionary<string, string>>();
foreach (ModelObjectParameterDefinition modelObjectParameterDefinition in modelObjectParameterDefinitions)
{
if (!modelObjectParameterDefinition.Name.Contains('.'))
continue;
else if (modelObjectParameterDefinition.Name.StartsWith("Description.") && (modelObjectParameterDefinition.Name.EndsWith(".EventName") || modelObjectParameterDefinition.Name.EndsWith(".EquipmentType")))
continue;
index = modelObjectParameterDefinition.Name.IndexOf(".");
if (index <= -1)
continue;
key = modelObjectParameterDefinition.Name.Substring(0, index);
variable = modelObjectParameterDefinition.Name.Substring(index + 1);
if (key == "COMMON")
commonSection.Add(variable, modelObjectParameterDefinition.Value);
else if (key == "CONNECTION STRINGS")
connectionStringsSection.Add(variable, modelObjectParameterDefinition.Value);
else if (key == "IQS")
iqsSection.Add(variable, modelObjectParameterDefinition.Value);
else if (key == "PATH")
pathSection.Add(variable, modelObjectParameterDefinition.Value);
else if (key == "REACTOR")
reactorTuples.Add(new Tuple<string, string>(variable, modelObjectParameterDefinition.Value));
else if (key == "TIBCO")
tibcoSection.Add(variable, modelObjectParameterDefinition.Value);
else if (key == "OpenInsight")
openInsightSection.Add(variable, modelObjectParameterDefinition.Value);
else
throw new Exception();
}
foreach (Tuple<string, string> tuple in reactorTuples)
{
if (!tuple.Item1.Contains('.'))
continue;
index = tuple.Item1.IndexOf(".");
if (index <= -1)
continue;
key = tuple.Item1.Substring(0, index);
variable = tuple.Item1.Substring(index + 1);
if (!reactorSection.ContainsKey(key))
reactorSection.Add(key, new Dictionary<string, string>() { { "NAME", key } });
reactorSection[key].Add(variable, tuple.Item2);
}
if (!iqsSection.Any())
throw new Exception("IQS section is missing from configuration");
else
{
key = "PATH";
if (iqsSection.ContainsKey(key))
IqsPath = iqsSection[key];
else
throw new Exception(string.Concat("Missing IQS Configuration entry for ", key));
if (string.IsNullOrEmpty(IqsPath))
throw new Exception(string.Format("IQS key {0} is empty", key));
key = "FILE";
if (iqsSection.ContainsKey(key))
IqsFile = iqsSection[key];
else
throw new Exception(string.Concat("Missing IQS Configuration entry for ", key));
if (eventName.HasValue && eventName.Value == EventName.FileRead && string.IsNullOrEmpty(IqsFile))
throw new Exception(string.Format("IQS key {0} is empty", key));
key = "QUERY";
if (iqsSection.ContainsKey(key))
IqsQueryFilter = iqsSection[key];
else
throw new Exception(string.Concat("Missing IQS Configuration entry for ", key));
if (eventName.HasValue && eventName.Value == EventName.FileRead && string.IsNullOrEmpty(IqsQueryFilter))
throw new Exception(string.Format("IQS key {0} is empty", key));
}
if (!pathSection.Any())
throw new Exception("Path section is missing from configuration");
else
{
key = "TRACE";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
TracePath = pathSection[key];
if (!string.IsNullOrEmpty(TracePath) && !Directory.Exists(TracePath))
Directory.CreateDirectory(TracePath);
key = "LOGISTIC";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
LogisticPath = pathSection[key];
if (!string.IsNullOrEmpty(LogisticPath) && !Directory.Exists(LogisticPath))
Directory.CreateDirectory(LogisticPath);
key = "VILLACH";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
VillachPath = pathSection[key];
if (!string.IsNullOrEmpty(VillachPath) && !Directory.Exists(VillachPath))
Directory.CreateDirectory(VillachPath);
key = "IQS";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
IqsTempPath = pathSection[key];
if (!string.IsNullOrEmpty(IqsTempPath) && !Directory.Exists(IqsTempPath))
Directory.CreateDirectory(IqsTempPath);
key = "Progress";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
ProgressPath = pathSection[key];
if (!string.IsNullOrEmpty(ProgressPath) && Directory.Exists(Path.GetPathRoot(ProgressPath)) && !Directory.Exists(ProgressPath))
Directory.CreateDirectory(ProgressPath);
key = "EDA";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
EdaPath = pathSection[key];
if (!string.IsNullOrEmpty(EdaPath) && !Directory.Exists(EdaPath))
Directory.CreateDirectory(EdaPath);
key = "APC";
if (pathSection.ContainsKey(key) && pathSection[key].StartsWith(@"\\"))
ApcPath = pathSection[key];
if (!string.IsNullOrEmpty(ApcPath) && !Directory.Exists(ApcPath))
Directory.CreateDirectory(ApcPath);
}
if (!commonSection.Any())
throw new Exception("Common section is missing from configuration");
else
{
if (isMET08PRFUSB4000Villach)
{
key = "MAPPED_PARTS";
if (!commonSection.ContainsKey(key))
throw new Exception("Mapped Parts KEY is missing from Equipment Type Configuration");
else
{
string mappedParts = commonSection[key];
if (mappedParts.Contains(','))
MappedParts = mappedParts.Split(',').ToList();
else
MappedParts = new string[] { mappedParts }.ToList();
}
if (!MappedParts.Any())
throw new Exception(string.Format("Common section key {0} is empty", key));
key = "ARCHIVE_SOURCE_DIRECTORY";
if (commonSection.ContainsKey(key))
ArchiveSourceDirectory = commonSection[key];
}
key = "CELL_NAMES";
if (!commonSection.ContainsKey(key) || !commonSection[key].Contains(';') || !commonSection[key].Contains(':'))
throw new Exception();
else
{
string[] segments;
string[] cellNames = commonSection[key].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in cellNames)
{
segments = item.Split(':');
CellNames.Add(segments[0].Trim(), segments[1].Trim());
}
}
if (!string.IsNullOrEmpty(cellName) && !CellNames.ContainsKey(cellName))
throw new Exception();
key = "MES_ENTITIES";
if (!commonSection.ContainsKey(key) || !commonSection[key].Contains(';') || !commonSection[key].Contains(':')) throw new Exception();
else
{
string[] segments;
string[] mesEntity = commonSection[key].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in mesEntity)
{
segments = item.Split(':');
MesEntities.Add(segments[0].Trim(), segments[1].Trim());
}
}
if (!string.IsNullOrEmpty(cellName) && !MesEntities.ContainsKey(cellName))
throw new Exception();
}
if (isMET08PRFUSB4000Villach)
{
if (!tibcoSection.Any())
throw new Exception("TIBCO section is missing from configuration");
else
{
key = "IFX_CHANNEL";
if (tibcoSection.ContainsKey(key))
IfxChannel = tibcoSection[key];
else
throw new Exception("IFX_CHANNEL is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(IfxChannel))
throw new Exception(string.Format("TIBCO section key {0} is empty", key));
key = "IFX_SUBJECT_PREFIX";
if (tibcoSection.ContainsKey(key))
IfxSubjectPrefix = tibcoSection[key];
else
throw new Exception("IFX_SUBJECT_PREFIX is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(IfxSubjectPrefix))
throw new Exception(string.Format("TIBCO section key {0} is empty", key));
key = "IFX_CONFIGURATION_LOCATION";
if (tibcoSection.ContainsKey(key))
IfxConfigurationLocation = tibcoSection[key];
else
throw new Exception("IFX_CONFIGURATION_LOCATION is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(IfxConfigurationLocation))
throw new Exception(string.Format("TIBCO section key {0} is empty", key));
key = "IFX_CONFIGURATION_LOCATION_LOCAL_COPY";
if (tibcoSection.ContainsKey(key))
IfxConfigurationLocationLocalCopy = tibcoSection[key];
else
throw new Exception("IFX_CONFIGURATION_LOCATION_LOCAL_COPY is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(IfxConfigurationLocationLocalCopy))
throw new Exception(string.Format("TIBCO section key {0} is empty", key));
key = "IFX_SUBJECT";
if (tibcoSection.ContainsKey(key))
IfxSubject = tibcoSection[key];
else
throw new Exception("IFX_SUBJECT KEY is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(IfxSubject))
throw new Exception(string.Format("TIBCO section key {0} is empty", key));
}
}
if (IsDatabaseExportToIPDSF || isMET08PRFUSB4000Villach)
{
if (!connectionStringsSection.Any())
throw new Exception("Connection Strings section is missing from configuration");
else
{
key = "G4WAFERS";
if (connectionStringsSection.ContainsKey(key))
ConnectionStringG4Wafers = connectionStringsSection[key];
else
throw new Exception("G4WAFERS is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(ConnectionStringG4Wafers))
throw new Exception(string.Format("Connection String key {0} is empty", key));
key = "IRMNSPC";
if (connectionStringsSection.ContainsKey(key))
ConnectionStringIrmnSpc = connectionStringsSection[key];
else
throw new Exception("IRMNSPC is missing from Equipment Type Configuration");
if (string.IsNullOrEmpty(ConnectionStringIrmnSpc))
throw new Exception(string.Format("IRMNSPC key {0} is empty", key));
//
Si.SQLDatabase.SetConnectionStringIrmnSpc(ConnectionStringIrmnSpc);
Si.SQLDatabase.SetConnectionStringG4Wafers(ConnectionStringG4Wafers);
Si.EpiControlPlan.CPGet.Parameters.SetConnectionStringIrmnSpc(ConnectionStringIrmnSpc);
Si.EpiControlPlan.CPGet.Parameters.SetConnectionStringG4Wafers(ConnectionStringG4Wafers);
Si.EpiControlPlan.CPGet.PartHistory.SetConnectionStringIrmnSpc(ConnectionStringIrmnSpc);
Si.EpiControlPlan.CPGet.PartHistory.SetConnectionStringG4Wafers(ConnectionStringG4Wafers);
Si.EpiControlPlan.CPGet.PartParameters.SetConnectionStringIrmnSpc(ConnectionStringIrmnSpc);
Si.EpiControlPlan.CPGet.PartParameters.SetConnectionStringG4Wafers(ConnectionStringG4Wafers);
}
}
if (!openInsightSection.Any())
throw new Exception("OpenInsight section is missing from configuration");
else
{
key = "SiViewer";
if (openInsightSection.ContainsKey(key))
OpenInsightSiViewer = openInsightSection[key];
if (string.IsNullOrEmpty(OpenInsightSiViewer))
throw new Exception(string.Format("OpenInsight key {0} is empty", key));
if (!OpenInsightSiViewer.Contains(":") || !OpenInsightSiViewer.Contains("."))
throw new Exception(string.Format("OpenInsight key {0} is invalid", key));
}
if (!MesEntities.Any())
throw new Exception();
if (isMET08PRFUSB4000Villach)
{
Si.Transport.Initialize(this);
if (!string.IsNullOrEmpty(fileConnectorConfiguration.SourceFileLocation))
TransportSetupMessages = Si.Transport.Setup(useSleep: true, setIfxTransport: true, setParameters: true);
else
TransportSetupMessages = Si.Transport.Setup(useSleep: false, setIfxTransport: false, setParameters: false);
}
if (IsSourceTimer || IsDatabaseExportToIPDSF || (Duplicator.HasValue && Duplicator.Value == Level.IsDummy))
{
if (!Directory.Exists(fileConnectorConfiguration.SourceFileLocation))
Directory.CreateDirectory(fileConnectorConfiguration.SourceFileLocation);
_ReportFullPath = string.Concat(fileConnectorConfiguration.SourceFileLocation, firstSourceFileFilter.Replace("*", @"\"));
if (Debugger.IsAttached || fileConnectorConfiguration.PreProcessingMode == FileConnectorConfiguration.PreProcessingModeEnum.Process)
Callback(null);
else
{
int milliSeconds;
milliSeconds = (int)((fileConnectorConfiguration.FileScanningIntervalInSeconds * 1000) / 2);
_Timer = new Timer(Callback, null, milliSeconds, Timeout.Infinite); milliSeconds += 2000;
}
}
}
}
public void CheckProcessDataDescription(Dictionary<Test, List<Duplicator.Description>> results, bool extra)
{
foreach (Test test in results.Keys)
{
if (test == Test)
{
if (!(ProcessDataDescription is ProcessData.FileRead.Description))
ProcessDataDescription = new ProcessData.FileRead.Description();
}
else
throw new Exception();
}
}
private void CallbackIsDummy(string traceDummyFile, List<Tuple<string, string, string, string, int>> tuples, bool fileConnectorConfigurationIncludeSubDirectories, bool includeSubDirectoriesExtra)
{
int fileCount;
string[] files;
string monARessource;
string checkDirectory;
string sourceArchiveFile;
string inProcessDirectory;
const string site = "sjc";
const string monInURL = "http://moninhttp.sjc.infineon.com/input/text";
MonIn monIn = MonIn.GetInstance(monInURL);
string stateName = string.Concat("Dummy_", _EventName);
foreach (Tuple<string, string, string, string, int> item in tuples)
{
monARessource = item.Item1;
sourceArchiveFile = item.Item2;
inProcessDirectory = item.Item3;
checkDirectory = item.Item4;
fileCount = item.Item5;
try
{
if (fileCount > 0 || string.IsNullOrEmpty(checkDirectory))
{
File.AppendAllLines(traceDummyFile, new string[] { site, monARessource, stateName, State.Warning.ToString() });
monIn.SendStatus(site, monARessource, stateName, State.Warning);
for (int i = 1; i < 12; i++)
Thread.Sleep(500);
}
else if (inProcessDirectory == checkDirectory)
continue;
if (!EafHosted)
continue;
if (!File.Exists(sourceArchiveFile))
continue;
if (!long.TryParse(Path.GetFileNameWithoutExtension(sourceArchiveFile).Replace("x", string.Empty), out long sequence))
continue;
ZipFile.ExtractToDirectory(sourceArchiveFile, inProcessDirectory);
if (fileConnectorConfigurationIncludeSubDirectories && includeSubDirectoriesExtra)
{
if (_EventName == EventName.FileRead)
checkDirectory = string.Concat(checkDirectory, @"\", sequence);
else if (_EventName == EventName.FileReadDaily)
checkDirectory = string.Concat(checkDirectory, @"\Source\", sequence);
else
throw new Exception();
}
if (fileConnectorConfigurationIncludeSubDirectories)
files = Directory.GetFiles(inProcessDirectory, "*", SearchOption.AllDirectories);
else
files = Directory.GetFiles(inProcessDirectory, "*", SearchOption.TopDirectoryOnly);
if (files.Length > 250)
throw new Exception("Safety net!");
foreach (string file in files)
File.SetLastWriteTime(file, new DateTime(sequence));
if (!fileConnectorConfigurationIncludeSubDirectories)
{
foreach (string file in files)
File.Move(file, string.Concat(checkDirectory, @"\", Path.GetFileName(file)));
}
else
{
string[] directories = Directory.GetDirectories(inProcessDirectory, "*", SearchOption.AllDirectories);
foreach (string directory in directories)
Directory.CreateDirectory(string.Concat(checkDirectory, directory.Substring(inProcessDirectory.Length)));
foreach (string file in files)
File.Move(file, string.Concat(checkDirectory, file.Substring(inProcessDirectory.Length)));
}
File.AppendAllLines(traceDummyFile, new string[] { site, monARessource, stateName, State.Ok.ToString() });
monIn.SendStatus(site, monARessource, stateName, State.Ok);
}
catch (Exception exception)
{
File.AppendAllLines(traceDummyFile, new string[] { site, monARessource, stateName, State.Critical.ToString(), exception.Message, exception.StackTrace });
monIn.SendStatus(site, monARessource, stateName, State.Critical);
try
{
Eaf.Core.Smtp.ISmtp smtp = Eaf.Core.Backbone.Instance.GetBackboneComponentsOfType<Eaf.Core.Smtp.ISmtp>().SingleOrDefault();
Eaf.Core.Smtp.EmailMessage emailMessage = new Eaf.Core.Smtp.EmailMessage(string.Concat("Exception:", EquipmentElementName), string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace), Eaf.Core.Smtp.MailPriority.High);
smtp.Send(emailMessage);
}
catch (Exception) { }
}
}
}
private void CallbackIsDummy()
{
DateTime dateTime = DateTime.Now;
bool check = (dateTime.Hour > 7 && dateTime.Hour < 18 && dateTime.DayOfWeek != DayOfWeek.Sunday && dateTime.DayOfWeek != DayOfWeek.Saturday);
if (check)
{
int fileCount;
string[] files;
string monARessource;
string checkDirectory;
string sourceArchiveFile;
string sourceFileLocation;
string inProcessDirectory;
string weekOfYear = _Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
string traceDummyDirectory = string.Concat(Path.GetPathRoot(TracePath), @"\TracesDummy\", CellName, @"\Source\", dateTime.ToString("yyyy"), "___Week_", weekOfYear);
if (!Directory.Exists(traceDummyDirectory))
Directory.CreateDirectory(traceDummyDirectory);
string traceDummyFile = string.Concat(traceDummyDirectory, @"\", dateTime.Ticks, " - ", CellName, ".txt");
File.AppendAllText(traceDummyFile, string.Empty);
List<Tuple<string, string, string, string, int>> tuples = new List<Tuple<string, string, string, string, int>>();
string progressDirectory = Path.GetFullPath(string.Concat(FileConnectorConfiguration.SourceFileLocation, @"\_ Progress"));
if (progressDirectory != ProgressPath || !Directory.Exists(progressDirectory))
throw new Exception("Invalid progress path");
foreach (var keyValuePair in CellNames)
{
monARessource = keyValuePair.Key;
if (!keyValuePair.Value.Contains(@"\"))
continue;
foreach (string sourceFileFilter in FileConnectorConfiguration.SourceFileFilter.Split('|'))
{
if (sourceFileFilter.ToLower().StartsWith(keyValuePair.Value.Replace(@"\", string.Empty)))
sourceFileLocation = Path.GetFullPath(FileConnectorConfiguration.SourceFileLocation);
else if (FileConnectorConfiguration.SourceFileLocation.ToLower().EndsWith(keyValuePair.Value))
sourceFileLocation = Path.GetFullPath(FileConnectorConfiguration.SourceFileLocation);
else
sourceFileLocation = Path.GetFullPath(string.Concat(FileConnectorConfiguration.SourceFileLocation, @"\", keyValuePair.Value));
sourceArchiveFile = Path.GetFullPath(string.Concat(sourceFileLocation, @"\", sourceFileFilter));
if (!File.Exists(sourceArchiveFile))
continue;
if (!DummyRuns.ContainsKey(monARessource))
DummyRuns.Add(monARessource, new List<long>());
tuples.Add(new Tuple<string, string, string, string, int>(monARessource, sourceFileFilter, sourceFileLocation, sourceArchiveFile, 0));
}
}
File.AppendAllLines(traceDummyFile, from l in tuples select l.Item4);
if (tuples.Any())
{
_LastDummyRunIndex += 1;
if (_LastDummyRunIndex >= tuples.Count)
_LastDummyRunIndex = 0;
monARessource = tuples[_LastDummyRunIndex].Item1;
string sourceFileFilter = tuples[_LastDummyRunIndex].Item2;
sourceFileLocation = tuples[_LastDummyRunIndex].Item3;
sourceArchiveFile = tuples[_LastDummyRunIndex].Item4;
//fileCount = tuples[_LastDummyRunIndex].Item5;
tuples.Clear();
if (long.TryParse(Path.GetFileNameWithoutExtension(sourceArchiveFile).Replace("x", string.Empty), out long sequence))
{
if (!DummyRuns[monARessource].Contains(sequence))
DummyRuns[monARessource].Add(sequence);
inProcessDirectory = string.Concat(progressDirectory, @"\Dummy_in process\", sequence);
checkDirectory = inProcessDirectory;
if (!Directory.Exists(checkDirectory))
Directory.CreateDirectory(checkDirectory);
files = Directory.GetFiles(checkDirectory, "*", SearchOption.AllDirectories);
fileCount = files.Length;
if (files.Any())
{
if (files.Length > 250)
throw new Exception("Safety net!");
try
{
foreach (string file in files)
File.Delete(file);
}
catch (Exception) { }
}
tuples.Add(new Tuple<string, string, string, string, int>(monARessource, sourceArchiveFile, inProcessDirectory, checkDirectory, fileCount));
checkDirectory = sourceFileLocation;
files = Directory.GetFiles(checkDirectory, string.Concat("*", sequence, "*"), SearchOption.TopDirectoryOnly);
fileCount = files.Length;
tuples.Add(new Tuple<string, string, string, string, int>(monARessource, sourceArchiveFile, inProcessDirectory, checkDirectory, fileCount));
}
}
if (tuples.Any())
CallbackIsDummy(traceDummyFile, tuples, FileConnectorConfiguration.IncludeSubDirectories.Value, includeSubDirectoriesExtra: false);
}
}
private void Callback(object state)
{
try
{
if (Duplicator is null)
{
if (File.Exists(_ReportFullPath))
File.Delete(_ReportFullPath);
File.WriteAllText(_ReportFullPath, string.Empty);
}
else if (Duplicator.Value == Level.IsDummy)
CallbackIsDummy();
else
throw new Exception();
}
catch (Exception exception)
{
try
{
Eaf.Core.Smtp.ISmtp smtp = Eaf.Core.Backbone.Instance.GetBackboneComponentsOfType<Eaf.Core.Smtp.ISmtp>().SingleOrDefault();
Eaf.Core.Smtp.EmailMessage emailMessage = new Eaf.Core.Smtp.EmailMessage(string.Concat("Exception:", EquipmentElementName), string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace), Eaf.Core.Smtp.MailPriority.High);
smtp.Send(emailMessage);
}
catch (Exception) { }
}
try
{
TimeSpan timeSpan;
if (IsDatabaseExportToIPDSF)
timeSpan = new TimeSpan(DateTime.Now.AddMinutes(1).Ticks - DateTime.Now.Ticks);
else if (IsSourceTimer)
timeSpan = new TimeSpan(DateTime.Now.AddMinutes(15).Ticks - DateTime.Now.Ticks);
else if (Duplicator.HasValue && Duplicator.Value == Level.IsDummy)
timeSpan = new TimeSpan(DateTime.Now.AddSeconds(FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks);
else if (Duplicator.HasValue)
timeSpan = new TimeSpan(DateTime.Now.AddSeconds(30).Ticks - DateTime.Now.Ticks);
else
timeSpan = new TimeSpan(DateTime.Now.AddDays(.5).Ticks - DateTime.Now.Ticks);
if (!(_Timer is null))
_Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite);
else
_Timer = new Timer(Callback, null, (long)timeSpan.TotalMilliseconds, Timeout.Infinite);
}
catch (Exception exception)
{
try
{
Eaf.Core.Smtp.ISmtp smtp = Eaf.Core.Backbone.Instance.GetBackboneComponentsOfType<Eaf.Core.Smtp.ISmtp>().SingleOrDefault();
Eaf.Core.Smtp.EmailMessage emailMessage = new Eaf.Core.Smtp.EmailMessage(string.Concat("Exception:", EquipmentElementName), string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace), Eaf.Core.Smtp.MailPriority.High);
smtp.Send(emailMessage);
}
catch (Exception) { }
}
}
public Tuple<string, JsonElement?, List<FileInfo>> IsManualOIEntry(string reportFullPath)
{
Tuple<string, JsonElement?, List<FileInfo>> results;
string monARessource;
const string site = "sjc";
string equipment = string.Empty;
string description = string.Empty;
string stateName = "MANUAL_OI_ENTRY";
string json = File.ReadAllText(reportFullPath);
JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
results = new Tuple<string, JsonElement?, List<FileInfo>>(string.Empty, jsonElement, new List<FileInfo>());
foreach (JsonProperty jsonProperty in jsonElement.EnumerateObject())
{
if (jsonProperty.Name == "Equipment")
equipment = jsonProperty.Value.ToString();
else if (jsonProperty.Name == "Description")
description = jsonProperty.Value.ToString();
}
if (string.IsNullOrEmpty(equipment))
monARessource = CellName;
else
monARessource = equipment;
const string monInURL = "http://moninhttp.sjc.infineon.com/input/text";
MonIn monIn = MonIn.GetInstance(monInURL);
if (EafHosted)
monIn.SendStatus(site, monARessource, stateName, State.Warning, description);
return results;
}
private void Archive(string sourceFileLocation, string sourceFileFilter, Calendar calendar, string directoryName, string newDirectoryName, int minFiles)
{
string newDirectroyRoot = sourceFileLocation.Replace(directoryName, newDirectoryName);
if (!Directory.Exists(newDirectroyRoot))
Directory.CreateDirectory(newDirectroyRoot);
if (Directory.Exists(sourceFileLocation))
{
string[] files = Directory.GetFiles(sourceFileLocation, sourceFileFilter, SearchOption.TopDirectoryOnly);
if (files.Length > minFiles)
{
string newFile;
string weekOfYear;
DateTime dateTime;
string newDirectroy;
DateTime creationTime;
DateTime lastWriteTime;
for (int i = 1; i < 50; i++)
Thread.Sleep(500);
foreach (var file in files)
{
creationTime = new FileInfo(file).CreationTime;
lastWriteTime = new FileInfo(file).LastWriteTime;
if (creationTime < lastWriteTime)
dateTime = creationTime;
else
dateTime = lastWriteTime;
weekOfYear = calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
newDirectroy = string.Concat(newDirectroyRoot, @"\", dateTime.ToString("yyyy"), "___Week_", weekOfYear);
if (!Directory.Exists(newDirectroy))
Directory.CreateDirectory(newDirectroy);
newFile = string.Concat(newDirectroy, @"\", Path.GetFileName(file));
if (File.Exists(newFile))
File.Delete(newFile);
try { File.Move(file, string.Concat(newDirectroy, @"\", Path.GetFileName(file))); } catch (Exception e) { Print(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace)); }
try { Directory.SetLastWriteTime(newDirectroy, dateTime); } catch (Exception e) { Print(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace)); }
}
try { Directory.SetLastWriteTime(sourceFileLocation, DateTime.Now); } catch (Exception e) { Print(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace)); }
}
}
}
}
}