initialize

This commit is contained in:
Pruefer
2025-06-06 09:15:13 +02:00
commit fa7c2730f1
5817 changed files with 1339670 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
using System;
namespace com.itac.mes.tools
{
public static class Constants
{
public static String SERVICE_NAME = "iTAC SiMM Proxy";
public static String LOGGER = "iTAC-OIB";
}
}

View File

@@ -0,0 +1,149 @@
#region Namespace
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
#endregion
namespace com.itac.mes.tools
{
public class DeserializedEventArgs
{
public DeserializedEventArgs(object deserializedObject) { DeserializedObject = deserializedObject; }
public object DeserializedObject { get; set; }
}
/// <summary>
/// Observes the directory local ./xml.
/// Whenever a new file (only *.xml files) was read the content is interpreted as xml.
/// The (simplified) first tag is treated as a simple typeName. If this simpleType name was
/// added as a type to the local map (typeDict) the xml stream will be deserialized.
/// If deserialisation was successful the instance is reported to the event handler.
///
/// </summary>
public class DirectoryMonitor
{
private bool _isShutdown = false;
private Dictionary<string, Type> typeDict;
public delegate void DeserializedObjectEventHandler(object sender, object deserializedObject);
public event DeserializedObjectEventHandler deserializedObjectEvent;
protected void raiseObjectDeserialized(object deserializedObject)
{
if (deserializedObjectEvent != null) deserializedObjectEvent(this, deserializedObject);
}
public void addType(Type typeToSerialize)
{
if (typeDict == null)
{
typeDict = new Dictionary<string, Type>();
}
typeDict.Add(typeToSerialize.Name, typeToSerialize);
}
public void Start()
{
var thread = new Thread(Run);
thread.Start();
}
public void Run()
{
Thread.CurrentThread.Name = "DirectoryMonitor";
while (!_isShutdown)
{
try
{
// Directory.GetFiles() returns an array of strings which are not just
// the file/directory name but the whole path to that file folder.
string[] fileList = Directory.GetFiles("./xml");
for (int i = 0; i < fileList.Length; i++)
{
if (File.Exists(fileList[i]))
{
//File Info is a Class which extend FileSystemInfo class.
FileInfo finfo = new FileInfo(fileList[i]);
//finfo.Length returns the File size.
if (fileList[i].ToLower().EndsWith("xml"))
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "FILE: " + fileList[i] + " :Size>" + finfo.Length);
if (File.Exists(fileList[i]))
{
using (StreamReader myFile = new StreamReader(fileList[i], System.Text.Encoding.Default))
{
string sContent = myFile.ReadToEnd();
// solange weiter lesen, bis eine Zeile erkannt wird, die nicht mit <? oder <!-- anfängt
int startOffset = sContent.IndexOf("<");
sContent = sContent.Substring(startOffset);
while (sContent.StartsWith("<?") || sContent.StartsWith("<!--"))
{
startOffset = sContent.IndexOf("<", 1);
sContent = sContent.Substring(startOffset);
}
myFile.BaseStream.Seek(startOffset, SeekOrigin.Begin);
myFile.BaseStream.Position = startOffset;
byte[] byteArray = Encoding.ASCII.GetBytes(sContent);
var stream = new MemoryStream(byteArray);
// convert stream to string
var reader = new StreamReader(stream);
myFile.BaseStream.Seek(startOffset, SeekOrigin.Begin);
myFile.BaseStream.Position = startOffset;
// root tag is simple class Name
try
{
String typeName = sContent.Substring(sContent.IndexOf("<") + 1, sContent.IndexOf(">") - 1);
if (typeDict.ContainsKey(typeName))
{
Type type = typeDict[typeName];
XmlSerializer serializer = new XmlSerializerFactory().CreateSerializer(type);
object deserializedObject = serializer.Deserialize(reader);
raiseObjectDeserialized(deserializedObject);
}
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "error processing xml file, ", e);
}
}
}
finfo.Delete();
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "FILE: " + fileList[i] + " has unsupported extension");
}
}
}
Thread.Sleep(1000);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "error processing xml file, " + e.Message);
Thread.Sleep(1000);
}
}
}
private string getFileContent(string v)
{
string sContent = "";
try
{
}
catch (Exception) { }
return sContent;
}
}
}

View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DB6626C3-81A3-49F4-9117-B20C9B87A2C4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ItacTools</RootNamespace>
<AssemblyName>ItacTools</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>icon_itac_logo_oib.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net">
<HintPath>..\libs\itac\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Constants.cs" />
<Compile Include="DirectoryMonitor.cs" />
<Compile Include="ItacXmlSerializer.cs" />
<Compile Include="KeyValue.cs" />
<Compile Include="LogHandler.cs" />
<Compile Include="MessageWriter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StatisticWorker.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="icon_itac_logo_oib.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,293 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace com.itac.mes.tools
{
public class ItacXmlSerializer
{
private static int MAX_INDENT_LEVEL = 15;
private static int indentationWidth = 2;
private int indentationLevel = 0;
private bool formatting = true;
private StringBuilder writer;
private static String[] indentStrings;
private bool logXmlFormat = true;// Eine Möglichkeit auch nicht-XML zu loggen
static ItacXmlSerializer()
{
indentStrings = new String[MAX_INDENT_LEVEL];
for (int level = 0; level < MAX_INDENT_LEVEL; level++)
{
StringBuilder indentBuffer = new StringBuilder();
int count = level * indentationWidth;
for (int i = 0; i < count; i++)
{
indentBuffer.Append(' ');
}
indentStrings[level] = indentBuffer.ToString();
}
}
// [MethodImpl(MethodImplOptions.Synchronized)]
public StringBuilder serialize(Object source)
{
writer = new StringBuilder();
if (source.GetType().IsArray)
{
writeArray("", source);
}
else
{
writeStart(source.GetType().Name, true);
writeStructure(source);
writeEnd(source.GetType().Name, true, true);
}
return writer;
}
private void indent()
{
if (formatting)
{
indentationLevel += 1;
}
}
private void unindent()
{
if (formatting && indentationLevel > 0)
{
indentationLevel -= 1;
}
}
private void writeArray(String fieldName, Object fieldvalue)
{
Object[] array = (Object[])fieldvalue;
// do not print empty arrays
if (array != null && array.Length > 0)
{
if (!fieldName.Equals(""))
{
writeStart(fieldName, true);
}
String simpleClassName = fieldvalue.GetType().Name.Substring(0, fieldvalue.GetType().Name.Length - 2);
for (int i = 0; i < array.Length; i++)
{
writeStart(simpleClassName, true);
writeStructure(array[i]);
writeEnd(simpleClassName, true, false);
}
if (!fieldName.Equals(""))
{
writeEnd(fieldName, true, false);
}
}
}
private void allClassProperties(List<PropertyInfo> fieldList, Type clazz)
{
// über alle Felder aller parent Interfaces, solange das Interface nicht Object ist.
if (clazz == null || clazz == typeof(Object))
{
return;
}
// fields: all public fields
PropertyInfo[] fields = clazz.GetProperties();
foreach (PropertyInfo field in fields)
{
fieldList.Add(field);
}
}
private void allClassFields(List<FieldInfo> fieldList, Type clazz)
{
// über alle Felder aller parent Interfaces, solange das Interface nicht Object ist.
if (clazz == null || clazz == typeof(Object))
{
return;
}
// fields: all public fields
FieldInfo[] fields = clazz.GetFields();
foreach (FieldInfo field in fields)
{
fieldList.Add(field);
}
}
private void writeStructure(Object source)
{
List<PropertyInfo> propertyList = new List<PropertyInfo>();
allClassProperties(propertyList, source.GetType());
List<FieldInfo> fieldList = new List<FieldInfo>();
allClassFields(fieldList, source.GetType());
foreach (PropertyInfo field2 in propertyList)
{
try
{
Object fieldvalue = field2.GetValue(source, null);
writeObject(field2.Name, fieldvalue);
}
catch (Exception)
{
writeObject(field2.Name, "property write failed");
}
}
foreach (FieldInfo field2 in fieldList)
{
try
{
Object fieldvalue = field2.GetValue(source);
writeObject(field2.Name, fieldvalue);
}
catch (Exception)
{
writeObject(field2.Name, "field write failed");
}
}
}
private void writeObject(String fieldName, object fieldvalue)
{
if (fieldvalue == null)
{
return;
}
if (fieldvalue.GetType() == typeof(String))
{
writeString(fieldName, (String)fieldvalue);
}
else if (fieldvalue.GetType() == typeof(DateTime))
{
writeDate(fieldName, (DateTime)fieldvalue);
}
else if (fieldvalue.GetType() == typeof(bool) || fieldvalue.GetType() == typeof(Boolean))
{
if (((bool)fieldvalue)) { writeString(fieldName, "true"); } else { writeString(fieldName, "false"); }
}
else if (fieldvalue.GetType() == typeof(byte) || fieldvalue.GetType() == typeof(int) || fieldvalue.GetType() == typeof(Int16) || fieldvalue.GetType() == typeof(Int32)
|| fieldvalue.GetType() == typeof(Int64))
{
writeIntNumber(fieldName, (Object)fieldvalue);
}
else if (fieldvalue.GetType() == typeof(double) || fieldvalue.GetType() == typeof(float))
{
writeNumber(fieldName, (Object)fieldvalue);
}
else if (fieldvalue.GetType() == typeof(Double))
{
writeNumber(fieldName, (Object)fieldvalue);
}
else if (fieldvalue.GetType().IsArray)
{
writeArray(fieldName, fieldvalue);
}
else
{
// Strukturierten Wert schreiben
writeStart(fieldName, true);
writeStructure(fieldvalue);
writeEnd(fieldName, true, false);
}
}
private void writeDate(String fieldName, DateTime fieldvalue)
{
writeStart(fieldName, false);
writer.Append(fieldvalue.ToString("o"));
writeEnd(fieldName, false, false);
}
private void writeStart(string fieldName, bool endLineAndIndent)
{
startLine();
if (logXmlFormat)
{
writer.Append("<");
writer.Append(fieldName);
writer.Append(">");
}
else
{
writer.Append(fieldName);
writer.Append(": ");
}
if (endLineAndIndent)
{
endLine();
indent();
}
}
private void writeEnd(string fieldName, bool indenting, bool newLine)
{
if (logXmlFormat)
{
if (indenting)
{
unindent();
startLine();
}
writer.Append("</");
writer.Append(fieldName);
writer.Append(">");
endLine();
}
else
{
if (indenting)
{
unindent();
}
if (newLine)
{
endLine();
}
}
}
private void writeNumber(String fieldName, Object fieldvalue)
{
writeStart(fieldName, false);
writer.Append(fieldvalue.ToString());
writeEnd(fieldName, false, true);
}
private void writeIntNumber(String fieldName, Object fieldvalue)
{
writeStart(fieldName, false);
writer.Append(fieldvalue.ToString());
writeEnd(fieldName, false, true);
}
private void writeString(String fieldName, String value)
{
writeStart(fieldName, false);
writer.Append(value);
writeEnd(fieldName, false, true);
}
private void endLine()
{
if (formatting)
{
writer.Append("\n");
}
}
private void startLine()
{
if (formatting)
{
writer.Append(indentStrings[Math.Min(indentationLevel, MAX_INDENT_LEVEL)]);
}
}
}
}

View File

@@ -0,0 +1,17 @@
using System;
namespace com.itac.mes.tools
{
public class KeyValue
{
public string key
{
get;
set;
}
public string value
{
get;
set;
}
}
}

View File

@@ -0,0 +1,69 @@
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Text;
using log4net;
using log4net.Config;
namespace com.itac.mes.tools
{
public class LogHandler
{
private static Object lockObject = new Object();
protected static readonly ILog logger = LogManager.GetLogger(Constants.LOGGER);
private static TraceSource ts = new TraceSource(Constants.SERVICE_NAME, SourceLevels.All);
static LogHandler()
{
XmlConfigurator.Configure();
}
public static void addListener(TraceListener listener)
{
ts.Listeners.Add(listener);
}
public static void log(String loggerName, TraceEventType level, String message)
{
log(loggerName, level, message, null);
}
public static void log(String loggerName, TraceEventType level, String message, Exception e)
{
// alles wird geloggt, aber nur Error und Fatal an die TraceSource weiter gereicht
try
{
lock (lockObject)
{
switch (level)
{
case TraceEventType.Critical: ts.TraceEvent(level, 10, message);
ts.Flush();
logger.Fatal(message, e);
break;
case TraceEventType.Error: ts.TraceEvent(level, 10, message);
ts.Flush();
logger.Error(message, e);
break;
case TraceEventType.Information:
logger.Info(message, e);
break;
case TraceEventType.Verbose:
logger.Debug(message, e);
break;
case TraceEventType.Warning:
logger.Warn(message, e);
break;
default: logger.Info(message, e);
ts.TraceEvent(level, 10, message);
ts.Flush();
break;
}
}
}
catch (ThreadInterruptedException) { }
}
}
}

View File

@@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using com.itac.mes.tools;
namespace com.itac.mes.tools
{
public class MessageWriter
{
static int counter = 0;
bool xmlExport = false;
bool xmlLogging = false;
private HashSet<String> writeXmlForType;
/// <summary>
/// Writing the serialized content of the mesage to a file.
/// Before an instance is written its simple type name must be added to the writer <see cref="AddType"/>
/// If xmlExport is false no message will be serialized.
/// If xml Logging is false only the simple type name is printed to console.
/// </summary>
/// <param name="xmlExport"></param>
/// <param name="xmlLogging"></param>
public void init(bool xmlExport, bool xmlLogging)
{
try
{
this.xmlExport = xmlExport;
this.xmlLogging = xmlLogging;
// pruefen, dass das Ausgabeverzeichnis ./output existiert
bool exists = System.IO.Directory.Exists(@".\output");
if (!exists && xmlExport)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "xmlExport set to true, but output folder (./output) does not exist!");
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "flag xmlExport modified, is set to false now!");
xmlExport = false;
}
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Initialization failed! " + e.Message, e);
}
}
/// <summary>
///
/// </summary>
public void output(Object outputObject)
{
if (outputObject == null)
{
return;
}
DateTime starttime = DateTime.Now;
counter++;
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "start serializing message");
String typeName = outputObject.GetType().Name;
// bei Array-Typen die Klammern im Typnamen weglassen
if (typeName.EndsWith("[]"))
{
typeName = typeName.Substring(0, typeName.Length - 2);
}
String XmlizedString = null;
if (xmlLogging)
{
ItacXmlSerializer itacSerializer = new ItacXmlSerializer();
try
{
XmlizedString = itacSerializer.serialize(outputObject).ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex);
XmlizedString = "serializing data for " + typeName + " failed!";
}
}
else
{
XmlizedString = "<" + typeName + ">...";
}
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, XmlizedString);
if (xmlExport)
{
try
{
String fileName = counter + "_" + DateTime.Now.Ticks + "_" + typeName + ".xml";
string newPath = Path.Combine(@".\output", fileName);
bool writeFile = getWriteXmlForType().Contains(typeName);
if (writeFile && counter < 65535)
{
Stream fileStream = new FileStream(newPath, FileMode.Create, FileAccess.Write);
using (StreamWriter outfile = new StreamWriter(fileStream))
{
outfile.Write(XmlizedString);
outfile.Flush();
outfile.Close();
}
}
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "writing xml file failed for {0}" + typeName, e);
}
}
TimeSpan duration = DateTime.Now - starttime;
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "serializing message done in " + duration.Milliseconds + " millies");
}
private HashSet<string> getWriteXmlForType()
{
if (writeXmlForType == null)
{
writeXmlForType = new HashSet<String>();
}
return writeXmlForType;
}
public void AddType(string typeName)
{
if (writeXmlForType == null)
{
writeXmlForType = new HashSet<String>();
}
writeXmlForType.Add(typeName);
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("ItacTools")]
[assembly: AssemblyDescription("mes independent tools")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ItacTools")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("db6626c3-81a3-49f4-9117-b20c9b87a2c4")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using com.itac.mes.tools;
namespace com.itac.mes.tools
{
public class StatisticWorker
{
private DateTime startupTime = DateTime.Now;
private long count = 0;
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
private List<KeyValue> versionList;
public StatisticWorker()
{
Thread.CurrentThread.Name = "StatisticThread";
}
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Process process = Process.GetCurrentProcess();
ProcessThreadCollection threads = process.Threads;
TimeSpan upTime = DateTime.Now - startupTime;
string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
String message = String.Format("{0} Statistics\n", appName) +
String.Format(" {0,-21}: {1}\n", "Application started", startupTime.ToLocalTime()) +
String.Format(" {0,-21}: {1}\n", "Uptime", upTime) +
String.Format(" {0,-21}: {1}\n", "MachineName", process.MachineName) +
String.Format(" {0,-21}: {1}\n", "MainModule", process.MainModule) +
String.Format(" {0,-21}: {1,9:####0\\.###} Mb\n", "PrivateMemorySize64", process.PrivateMemorySize64 / 1024) +
String.Format(" {0,-21}: {1,9:####0\\.###} Mb\n", "PeakWorkingSet64", process.PeakWorkingSet64 / 1024) +
String.Format(" {0,-21}: {1,9:####0\\.###} Mb\n", "WorkingSet64", process.WorkingSet64 / 1024) +
String.Format(" {0,-21}: {1,9:####0\\.###} Mb\n", "MinWorkingSet", process.MinWorkingSet.ToInt64() / 1024) +
String.Format(" {0,-21}: {1,9:####0\\.###} Mb\n", "MaxWorkingSet", process.MaxWorkingSet.ToInt64() / 1024) +
String.Format(" {0,-21}: {1}\n", "TotalProcessorTime", process.TotalProcessorTime) +
String.Format(" {0,-21}: {1}\n", "UserProcessorTime", process.UserProcessorTime) +
String.Format(" {0,-21}: {1}\n", "Threads", threads.Count);
// jedes 10. Mal weitere Infos ausgeben
if ((count % 10) == 0)
{
if (versionList != null)
{
foreach (KeyValue va in versionList)
{
message += String.Format(" {0,-21}: {1}\n", va.key, va.value);
}
}
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, message);
// 1 Minute schlafen
Thread.Sleep(60000);
count++;
}
}
public void RequestStop()
{
_shouldStop = true;
}
public void setVersionList(List<KeyValue> versionList)
{
this.versionList = versionList;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB