Utils hinzugefügt

This commit is contained in:
BlubbFish 2015-11-15 23:38:57 +00:00
commit e87188e460
10 changed files with 695 additions and 0 deletions

201
CmdArgs.cs Normal file
View File

@ -0,0 +1,201 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlubbFish.Utils
{
public class CmdArgs
{
public enum ArgLength
{
Single,
Touple
}
#region Classes
public class VaildArguments
{
public VaildArguments(ArgLength length, bool required)
{
this.Required = required;
this.Length = length;
}
public VaildArguments(ArgLength length)
{
this.Required = false;
this.Length = length;
}
public ArgLength Length { get; private set; }
public bool Required { get; private set; }
}
private class ArgTouple
{
public ArgTouple(string type, string data)
{
this.type = type;
this.data = data;
}
public ArgTouple(string type)
{
this.type = type;
}
public string type { get; private set; }
public string data { get; private set; }
internal void setData(string data)
{
if (data != "")
this.data = data;
}
}
#endregion
private string[] args;
private List<ArgTouple> argList;
private Dictionary<string, VaildArguments> argsPosible = new Dictionary<string, VaildArguments>();
private static CmdArgs instances = null;
private bool isSetArguments = false;
private CmdArgs()
{
}
/// <summary>
/// Gibt eine Instanz der Klasse zurück
/// </summary>
/// <returns>Klasse</returns>
public static CmdArgs getInstance()
{
if (instances == null)
{
instances = new CmdArgs();
}
return instances;
}
/// <summary>
/// Übernimmt die Argumente für die Klasse
/// </summary>
/// <param name="arguments">Mögliche Komandozeilenargumente</param>
/// <param name="args">Tatsächliche Komandozeilenargumente</param>
public void setArguments(Dictionary<string, VaildArguments> arguments, string[] args)
{
this.args = args;
if (!this.isSetArguments)
{
this.isSetArguments = true;
this.argsPosible = arguments;
this.Init();
}
}
private void Init()
{
this.argList = new List<ArgTouple>();
for (int i = 0; i < this.args.Length; i++)
{
if (this.argsPosible.Keys.Contains(args[i]))
{
ArgTouple arg = new ArgTouple(args[i]);
if (argsPosible[args[i]].Length == ArgLength.Touple)
{
if (args.Length > i + 1)
{
arg.setData(args[++i]);
}
else
{
throw new ArgumentException();
}
}
this.argList.Add(arg);
}
}
}
/// <summary>
/// Menge der angegebenen Komandozeilen-Argumente
/// </summary>
/// <returns>Menge</returns>
public int GetArgsLength()
{
return this.argList.Count;
}
/// <summary>
/// Gibt zurück ob ein Argument angegeben wurde
/// </summary>
/// <param name="name">Name des Arguments</param>
/// <returns>true wenn angegeben</returns>
public bool HasArgumentType(string name)
{
foreach (ArgTouple t in this.argList)
{
if (t.type == name)
return true;
}
return false;
}
/// <summary>
/// Gibt den Inhalt des angegeben Arguments zurück, nur bei zweiteiligen Argumenten möglich
/// </summary>
/// <param name="name">Name des Arguments</param>
/// <returns>Inhalt des Arguments oder ArgumentNullException</returns>
public string GetArgumentData(string name)
{
foreach (ArgTouple t in this.argList)
{
if (t.type == name && t.data != null)
return t.data;
else
{
throw new ArgumentNullException();
}
}
return null;
}
public bool HasAllRequiredArguments()
{
foreach (KeyValuePair<string, VaildArguments> item in this.argsPosible)
{
if (item.Value.Required && !this.HasArgumentType(item.Key))
{
return false;
}
}
return true;
}
public string getUsageList(string name)
{
string ret = "Usage: "+name+" Parameter\nParameter:\n";
string req ="";
string opt = "";
foreach (KeyValuePair<string, VaildArguments> item in this.argsPosible)
{
if (item.Value.Required)
{
req += item.Key+" "+((item.Value.Length == ArgLength.Touple)?" [data]\n":"\n");
}
}
if (req != "")
{
ret += "Benötigte Parameter:\n" + req;
}
foreach (KeyValuePair<string, VaildArguments> item in this.argsPosible)
{
if (!item.Value.Required)
{
opt += item.Key + " " + ((item.Value.Length == ArgLength.Touple) ? " [data]\n" : "\n");
}
}
if (opt != "")
{
ret += "Optionale Parameter:\n" + opt;
}
return ret;
}
}
}

47
FileLogger.cs Normal file
View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace BlubbFish.Utils
{
public class FileLogger
{
private static Dictionary<string, FileLogger> instances = new Dictionary<string, FileLogger>();
private StreamWriter file;
private FileLogger(string filename, bool append)
{
if (!File.Exists(filename))
{
string folder = Path.GetDirectoryName(Path.GetFullPath(filename));
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
}
this.file = new StreamWriter(filename, append, Encoding.UTF8);
this.file.AutoFlush = true;
}
public static FileLogger getInstance(string filename, bool append)
{
if (!instances.Keys.Contains(filename))
{
instances.Add(filename, new FileLogger(filename, append));
}
return instances[filename];
}
public void setArray(string[] text)
{
this.file.Write(String.Join(file.NewLine, text) + file.NewLine);
this.file.Flush();
}
public void setLine(string text)
{
this.file.WriteLine(text);
this.file.Flush();
}
}
}

198
InIReader.cs Normal file
View File

@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BlubbFish.Utils
{
public class InIReader
{
private Dictionary<string, Dictionary<string, string>> cont;
private FileSystemWatcher k = new FileSystemWatcher(Directory.GetCurrentDirectory(), "*.ini");
private string filename;
private static Dictionary<string, InIReader> instances = new Dictionary<string, InIReader>();
private InIReader(string filename)
{
this.filename = filename;
k.Changed += new FileSystemEventHandler(this.readAgain);
loadFile();
}
public static InIReader getInstance(string filename)
{
if (!instances.Keys.Contains(filename))
{
instances.Add(filename, new InIReader(filename));
}
return instances[filename];
}
private void readAgain(object sender, EventArgs e)
{
this.loadFile();
}
private void loadFile()
{
this.cont = new Dictionary<string, Dictionary<string, string>>();
StreamReader file = new StreamReader(this.filename);
List<String> buf = new List<string>();
string fline = "";
while (fline != null)
{
fline = file.ReadLine();
if (fline != null && fline.Length > 0 && fline.Substring(0,1) != ";")
buf.Add(fline);
}
file.Close();
Dictionary<string, string> sub = new Dictionary<string, string>();
string cap = "";
foreach (string line in buf)
{
Match match = Regex.Match(line, @"^\[[a-zA-Z0-9\-_ ]+\]\w*$", RegexOptions.IgnoreCase);
if (match.Success)
{
if (sub.Count != 0 && cap != "")
{
this.cont.Add(cap, sub);
}
cap = line;
sub = new Dictionary<string, string>();
}
else
{
if (line != "" && cap != "")
{
string key = line.Substring(0, line.IndexOf('='));
string value = line.Substring(line.IndexOf('=') + 1);
sub.Add(key, value);
}
}
}
if (sub.Count != 0 && cap != "")
{
this.cont.Add(cap, sub);
}
}
public List<String> getSections()
{
return cont.Keys.ToList<String>();
}
public String getValue(String section, String key)
{
if (!section.StartsWith("["))
{
section = "[" + section + "]";
}
if (cont.Keys.Contains(section))
{
if (cont[section].Keys.Contains(key))
{
return cont[section][key];
}
}
return null;
}
public void SetValue(string section, string key, string value)
{
if (!section.StartsWith("["))
{
section = "[" + section + "]";
}
if (cont.Keys.Contains(section))
{
if (cont[section].Keys.Contains(key))
{
cont[section][key] = value;
}
else
{
cont[section].Add(key, value);
}
}
else
{
Dictionary<string, string> sub = new Dictionary<string, string>();
sub.Add(key, value);
cont.Add(section, sub);
}
this.changed();
}
private void changed()
{
k.Changed -= null;
saveSettings();
loadFile();
k.Changed += new FileSystemEventHandler(this.readAgain);
}
private void saveSettings()
{
StreamWriter file = new StreamWriter(this.filename);
file.BaseStream.SetLength(0);
file.BaseStream.Flush();
file.BaseStream.Seek(0, SeekOrigin.Begin);
foreach (KeyValuePair<string, Dictionary<string, string>> cap in this.cont)
{
file.WriteLine(cap.Key);
foreach (KeyValuePair<string, string> sub in cap.Value)
{
file.WriteLine(sub.Key + "=" + sub.Value);
}
file.WriteLine();
}
file.Flush();
file.Close();
}
/// <summary>
/// Fügt eine neue Sektion in der Ini-Datei ein.
/// </summary>
/// <param name="name">Sektionsname</param>
/// <returns>true if added, false if error</returns>
public bool addSection(string name)
{
if (!name.StartsWith("["))
{
name = "[" + name + "]";
}
if (this.cont.Keys.Contains(name))
{
return false;
}
this.cont.Add(name, new Dictionary<string, string>());
this.changed();
return true;
}
/// <summary>
/// Löscht eine Sektion inklusive Unterpunkte aus der Ini-Datei.
/// </summary>
/// <param name="name">Sektionsname</param>
/// <returns>true if removed, false if error</returns>
public bool removeSection(string name)
{
if (!name.StartsWith("["))
{
name = "[" + name + "]";
}
if (!this.cont.Keys.Contains(name))
{
return false;
}
this.cont.Remove(name);
this.changed();
return false;
}
}
}

21
OwnController.cs Normal file
View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlubbFish.Utils
{
public abstract class OwnController
{
/// <summary>
/// Führt den Controller aus.
/// </summary>
public void execute()
{
this.init();
}
abstract protected void init();
}
}

36
OwnModel.cs Normal file
View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlubbFish.Utils
{
public abstract class OwnModel<T> where T : class
{
private static readonly Lazy<T> _instance = new Lazy<T>(() => CreateInstanceOfT());
private List<OwnView> observer = new List<OwnView>();
public static T Instance
{
get
{
return _instance.Value;
}
}
private static T CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
}
public void setObserver(OwnView tray)
{
this.observer.Add(tray);
tray.update();
}
protected void update()
{
this.observer.ForEach(delegate(OwnView tray) { tray.update(); });
}
abstract protected void init();
}
}

72
OwnObject.cs Normal file
View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlubbFish.Utils {
abstract public class OwnObject {
private List<Tuple<DateTime, string, string, LogLevel>> loglist = new List<Tuple<DateTime, string, string, LogLevel>>();
public delegate void LogEvent(string location, string message, LogLevel level, DateTime date);
public enum LogLevel : int {
Debug = 1,
Notice = 2,
Info = 4,
Warn = 8,
Error = 16
}
public event LogEvent eventDebug;
public event LogEvent eventNotice;
public event LogEvent eventInfo;
public event LogEvent eventWarn;
public event LogEvent eventError;
public event LogEvent EventLog;
/// <summary>
/// Get the Complete Log
/// </summary>
public List<string> getLog(LogLevel level, bool classNames, bool timeStamps) {
List<string> ret = new List<string>();
foreach(Tuple<DateTime, string, string, LogLevel> t in this.loglist) {
if(t.Item4 >= level) {
ret.Add(logToString(t.Item2, t.Item3, t.Item4, t.Item1, classNames, timeStamps));
}
}
return ret;
}
/// <summary>
/// Formates a LogMessage to a String
/// </summary>
public static string logToString(string location, string message, LogLevel level, DateTime date, bool classNames, bool timeStamps) {
return (timeStamps ? "[" + date.ToString("R") + "]: "+level.ToString()+" " : "") + (classNames ? location + ", " : "") + message;
}
protected void addLog(string location, string message, LogLevel level) {
this.addLog(location, message, level, DateTime.Now);
}
protected void addLog(string location, string message, LogLevel level, DateTime date) {
if(eventDebug != null && level >= LogLevel.Debug) {
eventDebug(location, message, level, date);
}
if(eventNotice != null && level >= LogLevel.Notice) {
eventNotice(location, message, level, date);
}
if(eventInfo != null && level >= LogLevel.Info) {
eventInfo(location, message, level, date);
}
if(eventWarn != null && level >= LogLevel.Warn) {
eventWarn(location, message, level, date);
}
if(eventError != null && level >= LogLevel.Error) {
eventError(location, message, level, date);
}
if(EventLog != null) {
EventLog(location, message, level, date);
}
this.loglist.Add(new Tuple<DateTime, string, string, LogLevel>(date, location, message, level));
}
}
}

24
OwnView.cs Normal file
View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlubbFish.Utils
{
public abstract class OwnView
{
/// <summary>
/// Called if the Oberver (Model) updates its View
/// </summary>
abstract public void update();
/// <summary>
/// Called if view is viewed
/// </summary>
abstract protected void init();
/// <summary>
/// Called if Form is Disposed
/// </summary>
abstract public void Dispose();
}
}

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 mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Utils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Utils")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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 zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("6f20376a-5c71-4979-9932-13c105d1c6e6")]
// 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")]

60
Utils.csproj Normal file
View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.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>{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BlubbFish.Utils</RootNamespace>
<AssemblyName>Utils</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</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>
</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>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CmdArgs.cs" />
<Compile Include="FileLogger.cs" />
<Compile Include="InIReader.cs" />
<Compile Include="OwnController.cs" />
<Compile Include="OwnModel.cs" />
<Compile Include="OwnObject.cs" />
<Compile Include="OwnView.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</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>

BIN
bin/Release/Utils.dll Normal file

Binary file not shown.