13 Commits
Author SHA1 Message Date
BlubbFish cc579102cb [1.6.2] ProgrammLogger improved 2022-01-30 22:40:25 +01:00
BlubbFish e3d37988c9 [1.6.1] ProgrammLogger Fixed 2022-01-20 19:42:14 +01:00
BlubbFish 61f26e69af [1.6.0] HttpEndpoint added 2022-01-09 23:01:53 +01:00
BlubbFish 528dcabf59 make mirror on github.com 2021-08-22 00:12:41 +02:00
BlubbFish baed3c9e08 Add GetEvent so you can call events by string
Add OwnSingeton class
2021-04-10 01:18:21 +02:00
BlubbFish edb3069bb0 Make netcore as default, also using 3.1 now 2021-01-08 23:50:43 +01:00
BlubbFish a5249f8fac Update CmdArgs to have more flexibility 2020-05-22 13:20:47 +02:00
BlubbFish b4e17972b9 Add field helper 2019-12-25 23:48:26 +01:00
BlubbFish 65fdcdc12c add file Changelog.md 2019-12-01 17:54:32 +01:00
BlubbFish 69f5534523 prevent to display things double in console 2019-11-29 14:45:42 +01:00
BlubbFish 4296649dca ups 2019-11-24 20:10:26 +01:00
BlubbFish 126632b4c9 Some issues with core 2019-11-24 19:00:17 +01:00
BlubbFish 2b40c85203 Refactoring and add net core project 2019-11-24 18:29:02 +01:00
21 changed files with 1090 additions and 776 deletions
+188
View File
@@ -0,0 +1,188 @@
# Changelog
## 1.6.2 - 2022-01-30 - ProgrammLogger improved
### New Features
* ProgrammLogger can now have a path while init, so not need to move the file
* Make it possible that two instances can use the same logfile
* IniReader GetValue can now have a default that returns if no setting is found
### Bugfixes
### Changes
* Codingstyles
## 1.6.1 - 2022-01-20 - ProgrammLogger Fixed
### New Features
### Bugfixes
* Unhandled exception. System.IO.IOException: The file '/var/log/zwaybot/debug.log' already exists.
### Changes
## 1.6.0 - 2022-01-09 - HttpEndpoint added
### New Features
* Add HttpEndpoint
### Bugfixes
### Changes
* Change Readme that its link to the normal repo
* Codingstyles
* Fixing history
## 1.5.0 - 2021-04-10 - Add GetEvent so you can call events by string; Add OwnSingeton class
### New Features
* More allowed Chars for Chapters in inifile
* Add Contribution, Licence and readme
* Adding netcore
* Add changelog
* Filedhelper to helpter
* CmdArgs improvements
* Make netcore to default
* Add OwnSingleton
### Bugfixes
* WriteLine in Programmlogger sometimes make nonesense
* Writeline event are wrong
### Changes
* Remove the binary files
* Move all Classes to subfolder
* Codingstyles
## 1.4.0 - 2018-11-27 - Add Helper to Utils
### New Features
* Add Helper
### Bugfixes
### Changes
## 1.1.3 - 2018-10-02 - Improve CmdArgs
### New Features
* CmdArgs now throw extensions if there is something wrong
### Bugfixes
### Changes
## 1.1.2 - 2018-09-11 - Tiny Codingstyles
### New Features
### Bugfixes
### Changes
* Codingstyles
## 1.1.1 - 2018-05-29 - ProgrammLogger neets to cleanup
### New Features
* Delete the Mess behind
### Bugfixes
### Changes
## 1.1.0 - 2018-05-15 - ProgrammLogger
### New Features
* Add Programmlogger
### Bugfixes
### Changes
* Codingstyles
## 1.0.7.0 - 2018-05-08 - Yet another IniReader improvemnt round again
### New Features
### Bugfixes
### Changes
* Move searchpath to its own function
## 1.0.6.0 - 2017-12-22 - Yet another IniReader improvemnt round
### New Features
* Posibillity to add complete sections to an ini file
### Bugfixes
### Changes
## 1.0.5.2 - 2017-09-26 - And Improve IniReader again
### New Features
* IniReader returns the Sections with or without Brackets now
### Bugfixes
### Changes
## 1.0.5.1 - 2017-09-24 - Improve IniReader again
### New Features
### Bugfixes
* IniReader now supports umlaute
* IniReader matches with Brackets and without
### Changes
## 1.0.5.0 - 2017-08-09 - Improve IniReader
### New Features
* IniReader can now return a whole segemt
### Bugfixes
### Changes
## 1.0.4.1 - 2017-08-08 - Cleanup OwnView
### New Features
### Bugfixes
### Changes
* remove Init from OwnView
## 1.0.4.0 - 2017-04-30 - More Updater
### New Features
* continue Development of Updater
### Bugfixes
### Changes
## 1.0.3.2 - 2017-04-26 - Next Updater
### New Features
* continue Development of Updater
### Bugfixes
### Changes
## 1.0.3.1 - 2017-04-25 - EventArgsHelper
### New Features
* Add EventArgsHelper
### Bugfixes
### Changes
* Codingstyles
* Moves LogEventArgs to EventArgsHelper
* Moves UpdaterEventArgs to EventArgsHelper
## 1.0.2.6 - 2017-04-24 - Better Updater
### New Features
* Add Updater
* Add Disposable Interface
* Using LogEventArgs now for Logging
* Make UpdaterEventArgs as Child of EventArgs
* Updater now using Ownobject as Parent
* Add VersionsInfo to Updater
* Updater spawns a Background Task to Check for Updates
### Bugfixes
### Changes
## 1.0.2.5 - 2017-04-19 - Logging in OwnObject
### New Features
* Add Logging to OwnObject
### Bugfixes
* Avoid nullpointer exception in FileMutex
### Changes
* Codingstyles
## 1.0.2.3 - 2017-04-16 - OwnModel better
### New Features
* Add Remove observer on OwnModel
### Bugfixes
### Changes
* Codingstyles
## 1.0.2.2 - 2017-03-09 - Make it nice
### New Features
### Bugfixes
### Changes
* Codingstyles
## 1.0.2.1 - 2017-03-09 - Filemutex
### New Features
* Add Filemutex
### Bugfixes
* Filelogger backet on wrong pos
### Changes
## 1.0.0.1 - 2016-12-03 - Filelogger improvements
### New Features
* Check Directory and if not exist add it
* Now logs with timestamp
* Can select logdir
* Add Abstract dispose to OwnController
### Bugfixes
### Changes
## 1.0.0.0 - 2015-11-16 - Init
### New Features
* Add CmdArgs, FileLogger, IniReader, OwnController, OwnModel, OwnObject, OwnView,
### Bugfixes
### Changes
+2
View File
@@ -1,2 +1,4 @@
# BlubbFish.Utils (Utils) # BlubbFish.Utils (Utils)
Library containing helpfull utils Library containing helpfull utils
Maybe you find this Repo on Github. This is a mirror from [here](https://git.blubbfish.net/vs_utils/Utils).
+22
View File
@@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "Utils\Utils-4.7.1.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+25 -20
View File
@@ -1,20 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012 # Visual Studio Version 16
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "Utils\Utils.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}" VisualStudioVersion = 16.0.29215.179
EndProject MinimumVisualStudioVersion = 10.0.40219.1
Global Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "Utils\Utils.csproj", "{A289C67C-BC49-46A0-8657-B444C605079E}"
GlobalSection(SolutionConfigurationPlatforms) = preSolution EndProject
Debug|Any CPU = Debug|Any CPU Global
Release|Any CPU = Release|Any CPU GlobalSection(SolutionConfigurationPlatforms) = preSolution
EndGlobalSection Debug|Any CPU = Debug|Any CPU
GlobalSection(ProjectConfigurationPlatforms) = postSolution Release|Any CPU = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU EndGlobalSection
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU {A289C67C-BC49-46A0-8657-B444C605079E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU {A289C67C-BC49-46A0-8657-B444C605079E}.Debug|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection {A289C67C-BC49-46A0-8657-B444C605079E}.Release|Any CPU.ActiveCfg = Release|Any CPU
GlobalSection(SolutionProperties) = preSolution {A289C67C-BC49-46A0-8657-B444C605079E}.Release|Any CPU.Build.0 = Release|Any CPU
HideSolutionNode = FALSE EndGlobalSection
EndGlobalSection GlobalSection(SolutionProperties) = preSolution
EndGlobal HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A7224DC4-69F1-4273-BE78-3D9DC80A28C5}
EndGlobalSection
EndGlobal
+22 -8
View File
@@ -14,19 +14,25 @@ namespace BlubbFish.Utils
#region Classes #region Classes
public struct VaildArguments public struct VaildArguments
{ {
public VaildArguments(ArgLength length, Boolean required) public VaildArguments(ArgLength length, Boolean required, String @default = "", String description = "")
{ {
this.Required = required; this.Required = required;
this.Length = length; this.Length = length;
this.Description = description;
this.@Default = @default;
} }
public VaildArguments(ArgLength length) public VaildArguments(ArgLength length, String @default = "", String description = "")
{ {
this.Required = false; this.Required = false;
this.Length = length; this.Length = length;
this.Description = description;
this.@Default = @default;
} }
public ArgLength Length { get; private set; } public ArgLength Length { get; private set; }
public Boolean Required { get; private set; } public Boolean Required { get; private set; }
public String Description { get; private set; }
public String Default { get; private set; }
} }
private struct ArgTouple private struct ArgTouple
{ {
@@ -107,16 +113,18 @@ namespace BlubbFish.Utils
this.argList.Add(arg); this.argList.Add(arg);
} }
} }
foreach(KeyValuePair<String, VaildArguments> item in this.argsPosible) {
if(!this.HasArgumentType(item.Key) && item.Value.Length == ArgLength.Touple && item.Value.Default != "") {
this.argList.Add(new ArgTouple(item.Key, item.Value.Default));
}
}
} }
/// <summary> /// <summary>
/// Menge der angegebenen Komandozeilen-Argumente /// Menge der angegebenen Komandozeilen-Argumente
/// </summary> /// </summary>
/// <returns>Menge</returns> /// <returns>Menge</returns>
public Int32 GetArgsLength() public Int32 GetArgsLength() => this.argList.Count;
{
return this.argList.Count;
}
/// <summary> /// <summary>
/// Gibt zurück ob ein Argument angegeben wurde /// Gibt zurück ob ein Argument angegeben wurde
@@ -165,7 +173,10 @@ namespace BlubbFish.Utils
String opt = ""; String opt = "";
foreach (KeyValuePair<String, VaildArguments> item in this.argsPosible) { foreach (KeyValuePair<String, VaildArguments> item in this.argsPosible) {
if (item.Value.Required) { if (item.Value.Required) {
req += item.Key + " " + ((item.Value.Length == ArgLength.Touple) ? " [data]\n" : "\n"); req += item.Key + " " + ((item.Value.Length == ArgLength.Touple) ? (item.Value.Default != "" ? " " + item.Value.Default + "\n" : " [data]\n") : "\n");
if(item.Value.Description != "") {
req += "\t" + item.Value.Description + "\n";
}
} }
} }
if (req != "") { if (req != "") {
@@ -173,7 +184,10 @@ namespace BlubbFish.Utils
} }
foreach (KeyValuePair<String, VaildArguments> item in this.argsPosible) { foreach (KeyValuePair<String, VaildArguments> item in this.argsPosible) {
if (!item.Value.Required) { if (!item.Value.Required) {
opt += item.Key + " " + ((item.Value.Length == ArgLength.Touple) ? " [data]\n" : "\n"); opt += item.Key + " " + ((item.Value.Length == ArgLength.Touple) ? (item.Value.Default != "" ? " " + item.Value.Default + "\n" : " [data]\n") : "\n");
if (item.Value.Description != "") {
opt += "\t" + item.Value.Description + "\n";
}
} }
} }
if (opt != "") { if (opt != "") {
+1 -3
View File
@@ -11,9 +11,7 @@ namespace BlubbFish.Utils {
} }
public class UpdaterFailEventArgs : EventArgs { public class UpdaterFailEventArgs : EventArgs {
public UpdaterFailEventArgs(Exception e) { public UpdaterFailEventArgs(Exception e) => this.Except = e;
this.Except = e;
}
public Exception Except { get; private set; } public Exception Except { get; private set; }
} }
+6 -9
View File
@@ -9,7 +9,7 @@ namespace BlubbFish.Utils
{ {
public class FileLogger public class FileLogger
{ {
private static Dictionary<String, FileLogger> instances = new Dictionary<String, FileLogger>(); private static readonly Dictionary<String, FileLogger> instances = new Dictionary<String, FileLogger>();
private static String logDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; private static String logDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
private readonly StreamWriter file; private readonly StreamWriter file;
private FileLogger(String filename, Boolean append) private FileLogger(String filename, Boolean append)
@@ -18,7 +18,7 @@ namespace BlubbFish.Utils
if (!File.Exists(filename)) { if (!File.Exists(filename)) {
String folder = Path.GetDirectoryName(Path.GetFullPath(filename)); String folder = Path.GetDirectoryName(Path.GetFullPath(filename));
if (!Directory.Exists(folder)) { if (!Directory.Exists(folder)) {
Directory.CreateDirectory(folder); _ = Directory.CreateDirectory(folder);
} }
} }
this.file = new StreamWriter(filename, append, Encoding.UTF8) { this.file = new StreamWriter(filename, append, Encoding.UTF8) {
@@ -40,11 +40,11 @@ namespace BlubbFish.Utils
if (Directory.Exists(v)) { if (Directory.Exists(v)) {
logDir = v; logDir = v;
} else { } else {
Directory.CreateDirectory(v); _ = Directory.CreateDirectory(v);
logDir = v; logDir = v;
} }
if (logDir.Substring(logDir.Length - 1) != Path.DirectorySeparatorChar.ToString()) { if (logDir[^1..] != Path.DirectorySeparatorChar.ToString()) {
logDir = logDir + Path.DirectorySeparatorChar; logDir += Path.DirectorySeparatorChar;
} }
} }
@@ -59,9 +59,6 @@ namespace BlubbFish.Utils
this.file.WriteLine(text); this.file.WriteLine(text);
this.file.Flush(); this.file.Flush();
} }
public void SetLine(String text, DateTime d) public void SetLine(String text, DateTime d) => this.SetLine(d.ToString("[yyyy-MM-dd HH:mm:ss.ffff] ") + text);
{
this.SetLine(d.ToString("[yyyy-MM-dd HH:mm:ss.ffff] ") + text);
}
} }
} }
+5 -3
View File
@@ -25,7 +25,9 @@ namespace BlubbFish.Utils
public void SetName(String name) public void SetName(String name)
{ {
String path = AppDomain.CurrentDomain.BaseDirectory; String path = AppDomain.CurrentDomain.BaseDirectory;
this.filename = path + String.Join(String.Empty, Array.ConvertAll(new SHA512Managed().ComputeHash(Encoding.UTF8.GetBytes(name)), b => b.ToString("X2"))) + ".lock.txt"; SHA512Managed sha = new SHA512Managed();
this.filename = path + String.Join(String.Empty, Array.ConvertAll(sha.ComputeHash(Encoding.UTF8.GetBytes(name)), b => b.ToString("X2"))) + ".lock.txt";
sha.Dispose();
} }
public Boolean Create() public Boolean Create()
@@ -35,7 +37,7 @@ namespace BlubbFish.Utils
} }
this.file = new StreamWriter(this.filename); this.file = new StreamWriter(this.filename);
InitFile(); this.InitFile();
return File.Exists(this.filename) && this.file != null; return File.Exists(this.filename) && this.file != null;
} }
@@ -64,7 +66,7 @@ namespace BlubbFish.Utils
} }
public void Dispose() { public void Dispose() {
Dispose(true); this.Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }
+93 -98
View File
@@ -1,98 +1,93 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Reflection; using System.Reflection;
namespace BlubbFish.Utils { namespace BlubbFish.Utils {
public static class Helper { public static class Helper {
#region PropertyHelper #region PropertyHelper
public static Boolean HasProperty(this Object o, String type) { public static Boolean HasProperty(this Object o, String type) {
Type t = o.GetType(); Type t = o.GetType();
foreach (PropertyInfo item in t.GetProperties()) { foreach (PropertyInfo item in t.GetProperties()) {
if (item.Name == type) { if (item.Name == type) {
return true; return true;
} }
} }
return false; return false;
} }
public static Object GetProperty(this Object o, String name) { public static Object GetProperty(this Object o, String name) {
PropertyInfo prop = o.GetType().GetProperty(name); PropertyInfo prop = o.GetType().GetProperty(name);
if (prop.CanRead) { return prop.CanRead ? prop.GetValue(o) : null;
return prop.GetValue(o); }
}
return null; public static void SetProperty(this Object o, String name, String value) {
} PropertyInfo prop = o.GetType().GetProperty(name);
if (prop.CanWrite) {
public static void SetProperty(this Object o, String name, String value) { if (prop.PropertyType == typeof(Boolean) && Boolean.TryParse(value, out Boolean vb)) {
PropertyInfo prop = o.GetType().GetProperty(name); prop.SetValue(o, vb);
if (prop.CanWrite) { } else if (prop.PropertyType == typeof(Byte) && Byte.TryParse(value, out Byte v8)) {
if (prop.PropertyType == typeof(Boolean) && Boolean.TryParse(value, out Boolean vb)) { prop.SetValue(o, v8);
prop.SetValue(o, vb); } else if (prop.PropertyType == typeof(Int32) && Int32.TryParse(value, out Int32 v32)) {
} else if (prop.PropertyType == typeof(Byte) && Byte.TryParse(value, out Byte v8)) { prop.SetValue(o, v32);
prop.SetValue(o, v8); } else if (prop.PropertyType == typeof(Single) && Single.TryParse(value, out Single vs)) {
} else if (prop.PropertyType == typeof(Int32) && Int32.TryParse(value, out Int32 v32)) { prop.SetValue(o, vs);
prop.SetValue(o, v32); } else if (prop.PropertyType == typeof(Double) && Double.TryParse(value, out Double vd)) {
} else if (prop.PropertyType == typeof(Single) && Single.TryParse(value, out Single vs)) { prop.SetValue(o, vd);
prop.SetValue(o, vs); } else if (prop.PropertyType == typeof(Int64) && Int64.TryParse(value, out Int64 v64)) {
} else if (prop.PropertyType == typeof(Double) && Double.TryParse(value, out Double vd)) { prop.SetValue(o, v64);
prop.SetValue(o, vd); } else if (prop.PropertyType.BaseType == typeof(Enum)) {
} else if (prop.PropertyType == typeof(Int64) && Int64.TryParse(value, out Int64 v64)) { try {
prop.SetValue(o, v64); prop.SetValue(o, Enum.Parse(prop.PropertyType, value));
} else if (prop.PropertyType.BaseType == typeof(Enum)) { } catch (Exception) { }
try { }
prop.SetValue(o, Enum.Parse(prop.PropertyType, value)); }
} catch (Exception) { } }
} #endregion
}
} #region FieldHelper
#endregion public static Object GetField(this Object o, String name) {
FieldInfo field = o.GetType().GetField(name);
#region InterfaceHelper return field.IsPublic ? field.GetValue(o) : null;
public static Boolean HasInterface(this Type o, Type interf) { }
foreach (Type item in o.GetInterfaces()) {
if (item == interf) { public static Object GetField(this Type o, String name) {
return true; FieldInfo field = o.GetField(name);
} return field.IsPublic ? field.GetValue(o) : null;
} }
return false;
} public static T GetEvent<T>(this Object o, String name) {
FieldInfo field = o.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
public static Boolean HasAbstract(this Type o, Type type) { return (T)field?.GetValue(o);
if (o.BaseType == type) { }
return true; #endregion
}
return false; #region InterfaceHelper
} public static Boolean HasInterface(this Type o, Type interf) {
#endregion foreach (Type item in o.GetInterfaces()) {
if (item == interf) {
#region StringHelper return true;
public static String GetEnumDescription(Enum value) { }
FieldInfo fi = value.GetType().GetField(value.ToString()); }
return false;
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); }
if (attributes != null && attributes.Length > 0) { public static Boolean HasAbstract(this Type o, Type type) => o.BaseType == type;
return attributes[0].Description; #endregion
} else {
return value.ToString(); #region StringHelper
} public static String GetEnumDescription(Enum value) {
} FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
public static String ToUpperLower(this String s) { return attributes != null && attributes.Length > 0 ? attributes[0].Description : value.ToString();
if (s.Length == 0) { }
return "";
} public static String ToUpperLower(this String s) => s.Length == 0 ? "" : s.Length == 1 ? s.ToUpper() : s[0].ToString().ToUpper() + s[1..].ToLower();
if (s.Length == 1) {
return s.ToUpper(); public static void WriteError(String text) {
} Console.ForegroundColor = ConsoleColor.Red;
return s[0].ToString().ToUpper() + s.Substring(1).ToLower(); Console.Error.WriteLine("ERROR: " + text);
} Console.ResetColor();
}
public static void WriteError(String text) { #endregion
Console.ForegroundColor = ConsoleColor.Red; }
Console.Error.WriteLine("ERROR: " + text); }
Console.ResetColor();
}
#endregion
}
}
+59
View File
@@ -0,0 +1,59 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace BlubbFish.Utils {
public class HttpEndpoint {
private readonly HttpClient client = new HttpClient();
private readonly String server = "";
public enum RequestMethod {
GET,
POST,
PUT
}
public HttpEndpoint(String server, String auth = null) {
this.server = server;
if(auth != null) {
this.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(auth);
}
}
public HttpEndpoint(String server, (String scheme, String parameter) auth) {
this.server = server;
this.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(auth.scheme, auth.parameter);
}
public async Task<String> RequestString(String address, String json = "", Boolean withoutput = true, RequestMethod method = RequestMethod.GET) {
String ret = null;
try {
HttpResponseMessage response = null;
if(method == RequestMethod.POST || method == RequestMethod.PUT) {
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//content.Headers.Add("Content-Type", "application/json");
if(method == RequestMethod.POST) {
response = await this.client.PostAsync(this.server + address, content);
} else if(method == RequestMethod.PUT) {
response = await this.client.PutAsync(this.server + address, content);
}
content.Dispose();
} else if(method == RequestMethod.GET) {
response = await this.client.GetAsync(this.server + address);
}
if(!response.IsSuccessStatusCode) {
throw new Exception(response.StatusCode + ": " + response.ReasonPhrase);
}
if(withoutput && response != null) {
ret = await response.Content.ReadAsStringAsync();
}
} catch(Exception e) {
throw new WebException(String.Format("Error while opening resource: \"{0}\" Method {1} Data {2} Fehler {3}", this.server + address, method, json, e.Message));
}
return ret;
}
}
}
+257 -276
View File
@@ -1,276 +1,257 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace BlubbFish.Utils { namespace BlubbFish.Utils {
public class InIReader : IDisposable public class InIReader : IDisposable
{ {
private Dictionary<String, Dictionary<String, String>> inifile; private Dictionary<String, Dictionary<String, String>> inifile;
private readonly FileSystemWatcher k; private readonly FileSystemWatcher k;
private readonly String filename; private readonly String filename;
private static List<String> search_path = new List<String>() { private static readonly List<String> search_path = new List<String>() {
Directory.GetCurrentDirectory() Directory.GetCurrentDirectory()
}; };
private static Dictionary<String, InIReader> instances = new Dictionary<String, InIReader>(); private static readonly Dictionary<String, InIReader> instances = new Dictionary<String, InIReader>();
public static void SetSearchPath(List<String> directorys) { public static void SetSearchPath(List<String> directorys) => search_path.AddRange(directorys);
search_path.AddRange(directorys);
} public static Boolean ConfigExist(String filename) {
foreach (String path in search_path) {
public static Boolean ConfigExist(String filename) { if (File.Exists(path + Path.DirectorySeparatorChar + filename)) {
foreach (String path in search_path) { return true;
if (File.Exists(path + Path.DirectorySeparatorChar + filename)) { } else if (File.Exists(path + Path.DirectorySeparatorChar + filename + ".ini")) {
return true; return true;
} else if (File.Exists(path + Path.DirectorySeparatorChar + filename + ".ini")) { } else if (File.Exists(path + Path.DirectorySeparatorChar + filename + ".conf")) {
return true; return true;
} else if (File.Exists(path + Path.DirectorySeparatorChar + filename + ".conf")) { }
return true; }
} return false;
} }
return false;
} private InIReader(String filename) {
foreach (String path in search_path) {
private InIReader(String filename) if (File.Exists(path + Path.DirectorySeparatorChar + filename)) {
{ this.filename = path + Path.DirectorySeparatorChar + filename;
foreach (String path in search_path) { this.k = new FileSystemWatcher(path, filename);
if (File.Exists(path + Path.DirectorySeparatorChar + filename)) { break;
this.filename = path + Path.DirectorySeparatorChar + filename; } else if (File.Exists(path + Path.DirectorySeparatorChar + filename + ".ini")) {
this.k = new FileSystemWatcher(path, filename); this.filename = path + Path.DirectorySeparatorChar + filename + ".ini";
break; this.k = new FileSystemWatcher(path, filename + ".ini");
} else if (File.Exists(path + Path.DirectorySeparatorChar + filename + ".ini")) { break;
this.filename = path + Path.DirectorySeparatorChar + filename + ".ini"; } else if(File.Exists(path + Path.DirectorySeparatorChar + filename + ".conf")) {
this.k = new FileSystemWatcher(path, filename + ".ini"); this.filename = path + Path.DirectorySeparatorChar + filename + ".conf";
break; this.k = new FileSystemWatcher(path, filename + ".conf");
} else if(File.Exists(path + Path.DirectorySeparatorChar + filename + ".conf")) { break;
this.filename = path + Path.DirectorySeparatorChar + filename + ".conf"; }
this.k = new FileSystemWatcher(path, filename + ".conf"); }
break; if(this.filename == null) {
} throw new ArgumentException(filename + " not found!");
} }
if(this.filename == null) { this.k.Changed += new FileSystemEventHandler(this.ReadAgain);
throw new ArgumentException(filename + " not found!"); this.LoadFile();
} }
this.k.Changed += new FileSystemEventHandler(this.ReadAgain);
LoadFile(); /// <summary>
} /// Gibt eine InIReader-Instanz zu einer Datei zurück
/// </summary>
/// <summary> /// <param name="filename">Dateiname</param>
/// Gibt eine InIReader-Instanz zu einer Datei zurück /// <returns></returns>
/// </summary> public static InIReader GetInstance(String filename) {
/// <param name="filename">Dateiname</param> if (!instances.Keys.Contains(filename)) {
/// <returns></returns> instances.Add(filename, new InIReader(filename));
public static InIReader GetInstance(String filename) }
{ return instances[filename];
if (!instances.Keys.Contains(filename)) { }
instances.Add(filename, new InIReader(filename));
} private void ReadAgain(Object sender, EventArgs e) => this.LoadFile();
return instances[filename];
} private void LoadFile() {
this.inifile = new Dictionary<String, Dictionary<String, String>>();
private void ReadAgain(Object sender, EventArgs e) StreamReader file = new StreamReader(this.filename);
{ List<String> buf = new List<String>();
this.LoadFile(); String fline = "";
} while (fline != null) {
fline = file.ReadLine();
private void LoadFile() if (fline != null && fline.Length > 0 && fline.Substring(0, 1) != ";") {
{ buf.Add(fline);
this.inifile = new Dictionary<String, Dictionary<String, String>>(); }
StreamReader file = new StreamReader(this.filename); }
List<String> buf = new List<String>(); file.Close();
String fline = ""; Dictionary<String, String> sub = new Dictionary<String, String>();
while (fline != null) { String cap = "";
fline = file.ReadLine(); foreach (String line in buf) {
if (fline != null && fline.Length > 0 && fline.Substring(0, 1) != ";") { Match match = Regex.Match(line, @"^\[[a-zA-ZäöüÄÖÜ0-9\-\._/ ]+\]\w*$", RegexOptions.IgnoreCase);
buf.Add(fline); if (match.Success) {
} if (sub.Count != 0 && cap != "") {
} this.inifile.Add(cap, sub);
file.Close(); }
Dictionary<String, String> sub = new Dictionary<String, String>(); cap = line;
String cap = ""; sub = new Dictionary<String, String>();
foreach (String line in buf) { } else {
Match match = Regex.Match(line, @"^\[[a-zA-ZäöüÄÖÜ0-9\-\._/ ]+\]\w*$", RegexOptions.IgnoreCase); if (line != "" && cap != "") {
if (match.Success) { String key = line.Substring(0, line.IndexOf('='));
if (sub.Count != 0 && cap != "") { String value = line[(line.IndexOf('=') + 1)..];
this.inifile.Add(cap, sub); sub.Add(key, value);
} }
cap = line; }
sub = new Dictionary<String, String>(); }
} else { if (sub.Count != 0 && cap != "") {
if (line != "" && cap != "") { this.inifile.Add(cap, sub);
String key = line.Substring(0, line.IndexOf('=')); }
String value = line.Substring(line.IndexOf('=') + 1); }
sub.Add(key, value);
} /// <summary>
} /// Gibt eine Liste an Sektionen zurück
} /// </summary>
if (sub.Count != 0 && cap != "") { /// <param name="withBrackets">Default = true; false, wenn die Liste ohne Klammern sein soll.</param>
this.inifile.Add(cap, sub); /// <returns></returns>
} public List<String> GetSections(Boolean withBrackets = true)
} {
if(withBrackets) {
/// <summary> return this.inifile.Keys.ToList();
/// Gibt eine Liste an Sektionen zurück } else {
/// </summary> List<String> ret = new List<String>();
/// <param name="withBrackets">Default = true; false, wenn die Liste ohne Klammern sein soll.</param> foreach (String item in this.inifile.Keys) {
/// <returns></returns> ret.Add(item[1..^1]);
public List<String> GetSections(Boolean withBrackets = true) }
{ return ret;
if(withBrackets) { }
return this.inifile.Keys.ToList(); }
} else {
List<String> ret = new List<String>(); /// <summary>
foreach (String item in this.inifile.Keys) { /// Überschreibt eine InI-Datei mit der Kompletten neuen Configuration
ret.Add(item.Substring(1, item.Length - 2)); /// </summary>
} /// <param name="config">Neue Konfiguration</param>
return ret; public void SetSections(Dictionary<String, Dictionary<String, String>> config) {
} this.inifile.Clear();
} foreach (KeyValuePair<String, Dictionary<String, String>> item in config) {
String key = item.Key;
/// <summary> if(!key.StartsWith("[")) {
/// Überschreibt eine InI-Datei mit der Kompletten neuen Configuration key = "[" + key + "]";
/// </summary> }
/// <param name="config">Neue Konfiguration</param> if (Regex.Match(key, @"^\[[a-zA-ZäöüÄÖÜ0-9\-\._/ ]+\]\w*$", RegexOptions.IgnoreCase).Success) {
public void SetSections(Dictionary<String, Dictionary<String, String>> config) { this.inifile.Add(key, item.Value);
this.inifile.Clear(); }
foreach (KeyValuePair<String, Dictionary<String, String>> item in config) { }
String key = item.Key; this.Changed();
if(!key.StartsWith("[")) { }
key = "[" + key + "]";
} public Dictionary<String, String> GetSection(String section) => this.inifile.Keys.Contains(section) ?
if (Regex.Match(key, @"^\[[a-zA-ZäöüÄÖÜ0-9\-\._/ ]+\]\w*$", RegexOptions.IgnoreCase).Success) { this.inifile[section] : this.inifile.Keys.Contains("[" + section + "]") ?
this.inifile.Add(key, item.Value); this.inifile["[" + section + "]"] : new Dictionary<String, String>();
}
} /// <summary>
this.Changed(); /// Gibt einen einzelnen Wert zurück
} /// </summary>
/// <param name="section">Name der Sektion</param>
public Dictionary<String, String> GetSection(String section) { /// <param name="key">Name des Wertes</param>
if(this.inifile.Keys.Contains(section)) { /// <returns></returns>
return this.inifile[section]; public String GetValue(String section, String key, String @default = null) {
} if (!section.StartsWith("[")) {
if(this.inifile.Keys.Contains("["+section+"]")) { section = "[" + section + "]";
return this.inifile["[" + section + "]"]; }
} return this.inifile.Keys.Contains(section) && this.inifile[section].Keys.Contains(key) ? this.inifile[section][key] : @default;
return new Dictionary<String, String>(); }
}
/// <summary>
/// <summary> /// Setzt einen Wert in einer Sektion
/// Gibt einen einzelnen Wert zurück /// </summary>
/// </summary> /// <param name="section">Name der Sektion</param>
/// <param name="section">Name der Sektion</param> /// <param name="key">Name des Wertes</param>
/// <param name="key">Name des Wertes</param> /// <param name="value">Wert</param>
/// <returns></returns> public void SetValue(String section, String key, String value)
public String GetValue(String section, String key) {
{ if (!section.StartsWith("[")) {
if (!section.StartsWith("[")) { section = "[" + section + "]";
section = "[" + section + "]"; }
} if (this.inifile.Keys.Contains(section)) {
if (this.inifile.Keys.Contains(section)) { if (this.inifile[section].Keys.Contains(key)) {
if (this.inifile[section].Keys.Contains(key)) { this.inifile[section][key] = value;
return this.inifile[section][key]; } else {
} this.inifile[section].Add(key, value);
} }
return null; } else {
} Dictionary<String, String> sub = new Dictionary<String, String> {
{ key, value }
/// <summary> };
/// Setzt einen Wert in einer Sektion this.inifile.Add(section, sub);
/// </summary> }
/// <param name="section">Name der Sektion</param> this.Changed();
/// <param name="key">Name des Wertes</param> }
/// <param name="value">Wert</param>
public void SetValue(String section, String key, String value) private void Changed()
{ {
if (!section.StartsWith("[")) { this.k.Changed -= null;
section = "[" + section + "]"; this.SaveSettings();
} this.LoadFile();
if (this.inifile.Keys.Contains(section)) { this.k.Changed += new FileSystemEventHandler(this.ReadAgain);
if (this.inifile[section].Keys.Contains(key)) { }
this.inifile[section][key] = value;
} else { private void SaveSettings()
this.inifile[section].Add(key, value); {
} StreamWriter file = new StreamWriter(this.filename);
} else { file.BaseStream.SetLength(0);
Dictionary<String, String> sub = new Dictionary<String, String> { file.BaseStream.Flush();
{ key, value } _ = file.BaseStream.Seek(0, SeekOrigin.Begin);
}; foreach (KeyValuePair<String, Dictionary<String, String>> cap in this.inifile) {
this.inifile.Add(section, sub); file.WriteLine(cap.Key);
} foreach (KeyValuePair<String, String> sub in cap.Value) {
this.Changed(); file.WriteLine(sub.Key + "=" + sub.Value);
} }
file.WriteLine();
private void Changed() }
{ file.Flush();
this.k.Changed -= null; file.Close();
SaveSettings(); }
LoadFile();
this.k.Changed += new FileSystemEventHandler(this.ReadAgain); /// <summary>
} /// Fügt eine neue Sektion in der Ini-Datei ein.
/// </summary>
private void SaveSettings() /// <param name="name">Sektionsname</param>
{ /// <returns>true if added, false if error</returns>
StreamWriter file = new StreamWriter(this.filename); public Boolean AddSection(String name)
file.BaseStream.SetLength(0); {
file.BaseStream.Flush(); if (!name.StartsWith("[")) {
file.BaseStream.Seek(0, SeekOrigin.Begin); name = "[" + name + "]";
foreach (KeyValuePair<String, Dictionary<String, String>> cap in this.inifile) { }
file.WriteLine(cap.Key); if (this.inifile.Keys.Contains(name)) {
foreach (KeyValuePair<String, String> sub in cap.Value) { return false;
file.WriteLine(sub.Key + "=" + sub.Value); }
} this.inifile.Add(name, new Dictionary<String, String>());
file.WriteLine(); this.Changed();
} return true;
file.Flush(); }
file.Close();
} /// <summary>
/// Löscht eine Sektion inklusive Unterpunkte aus der Ini-Datei.
/// <summary> /// </summary>
/// Fügt eine neue Sektion in der Ini-Datei ein. /// <param name="name">Sektionsname</param>
/// </summary> /// <returns>true if removed, false if error</returns>
/// <param name="name">Sektionsname</param> public Boolean RemoveSection(String name)
/// <returns>true if added, false if error</returns> {
public Boolean AddSection(String name) if (!name.StartsWith("[")) {
{ name = "[" + name + "]";
if (!name.StartsWith("[")) { }
name = "[" + name + "]"; if (!this.inifile.Keys.Contains(name)) {
} return false;
if (this.inifile.Keys.Contains(name)) { }
return false; _ = this.inifile.Remove(name);
} this.Changed();
this.inifile.Add(name, new Dictionary<String, String>()); return false;
this.Changed(); }
return true;
} protected virtual void Dispose(Boolean disposing) {
if (disposing) {
/// <summary> this.k.Dispose();
/// 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 void Dispose() {
public Boolean RemoveSection(String name) this.Dispose(true);
{ GC.SuppressFinalize(this);
if (!name.StartsWith("[")) { }
name = "[" + name + "]"; }
} }
if (!this.inifile.Keys.Contains(name)) {
return false;
}
this.inifile.Remove(name);
this.Changed();
return false;
}
protected virtual void Dispose(Boolean disposing) {
if (disposing) {
this.k.Dispose();
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
+2 -13
View File
@@ -1,21 +1,10 @@
using System; namespace BlubbFish.Utils {
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 public abstract class OwnController
{ {
/// <summary> /// <summary>
/// Führt den Controller aus. /// Führt den Controller aus.
/// </summary> /// </summary>
public void Execute() public void Execute() => this.Init();
{
this.Init();
}
abstract protected void Init(); abstract protected void Init();
abstract public void Dispose(); abstract public void Dispose();
} }
+25 -40
View File
@@ -1,40 +1,25 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; namespace BlubbFish.Utils {
using System.Threading.Tasks; public abstract class OwnModel<T> where T : class
{
namespace BlubbFish.Utils private static readonly Lazy<T> _instance = new Lazy<T>(() => CreateInstanceOfT());
{ private readonly List<OwnView> observer = new List<OwnView>();
public abstract class OwnModel<T> where T : class public static T Instance => _instance.Value;
{ private static T CreateInstanceOfT() => Activator.CreateInstance(typeof(T), true) as T;
private static readonly Lazy<T> _instance = new Lazy<T>(() => CreateInstanceOfT());
private readonly List<OwnView> observer = new List<OwnView>(); public void SetObserver(OwnView view)
public static T Instance {
{ this.observer.Add(view);
get { view.Update();
return _instance.Value; }
}
} public void RemoveObserver(OwnView view) => _ = this.observer.Remove(view);
private static T CreateInstanceOfT() protected void Update() => this.observer.ForEach(delegate (OwnView view) {
{ view.Update();
return Activator.CreateInstance(typeof(T), true) as T; });
} abstract protected void Init();
abstract public void Dispose();
public void SetObserver(OwnView view) }
{ }
this.observer.Add(view);
view.Update();
}
public void RemoveObserver(OwnView view) {
this.observer.Remove(view);
}
protected void Update()
{
this.observer.ForEach(delegate (OwnView view) { view.Update(); });
}
abstract protected void Init();
abstract public void Dispose();
}
}
+14 -21
View File
@@ -21,21 +21,17 @@ namespace BlubbFish.Utils
/// Formates a LogMessage to a String /// Formates a LogMessage to a String
/// </summary> /// </summary>
/// <returns>Formated String</returns> /// <returns>Formated String</returns>
public override String ToString() { public override String ToString() => "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " " + this.Location + ", " + this.Message;
return "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " "+ this.Location + ", " + this.Message;
}
/// <summary> /// <summary>
/// Formates a LogMessage to a String /// Formates a LogMessage to a String
/// </summary> /// </summary>
/// <param name="classNames">Enables the output of the location</param> /// <param name="classNames">Enables the output of the location</param>
/// <param name="timeStamps">Enables the output of the date</param> /// <param name="timeStamps">Enables the output of the date</param>
/// <returns>Formated String</returns> /// <returns>Formated String</returns>
public String ToString(Boolean classNames, Boolean timeStamps) { public String ToString(Boolean classNames, Boolean timeStamps) => (timeStamps ? "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " " : "") + (classNames ? this.Location + ", " : "") + this.Message;
return (timeStamps ? "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " " : "") + (classNames ? this.Location + ", " : "") + this.Message;
}
} }
private List<LogObject> loglist = new List<LogObject>(); private readonly List<LogObject> loglist = new List<LogObject>();
public delegate void LogEvent(Object sender, LogEventArgs e); public delegate void LogEvent(Object sender, LogEventArgs e);
public enum LogLevel : Int32 { public enum LogLevel : Int32 {
@@ -72,10 +68,7 @@ namespace BlubbFish.Utils
/// <param name="location">Where the event arrives</param> /// <param name="location">Where the event arrives</param>
/// <param name="message">The logmessage itselfs</param> /// <param name="message">The logmessage itselfs</param>
/// <param name="level">Level of the message</param> /// <param name="level">Level of the message</param>
protected void AddLog(String location, String message, LogLevel level) protected void AddLog(String location, String message, LogLevel level) => this.AddLog(location, message, level, DateTime.Now);
{
this.AddLog(location, message, level, DateTime.Now);
}
/// <summary> /// <summary>
/// Put a message in the log /// Put a message in the log
@@ -87,20 +80,20 @@ namespace BlubbFish.Utils
protected void AddLog(String location, String message, LogLevel level, DateTime date) protected void AddLog(String location, String message, LogLevel level, DateTime date)
{ {
LogEventArgs e = new LogEventArgs(location, message, level, date); LogEventArgs e = new LogEventArgs(location, message, level, date);
if (EventDebug != null && level >= LogLevel.Debug) { if (level >= LogLevel.Debug) {
EventDebug(this, e); EventDebug?.Invoke(this, e);
} }
if (EventNotice != null && level >= LogLevel.Notice) { if (level >= LogLevel.Notice) {
EventNotice(this, e); EventNotice?.Invoke(this, e);
} }
if (EventInfo != null && level >= LogLevel.Info) { if (level >= LogLevel.Info) {
EventInfo(this, e); EventInfo?.Invoke(this, e);
} }
if (EventWarn != null && level >= LogLevel.Warn) { if (level >= LogLevel.Warn) {
EventWarn(this, e); EventWarn?.Invoke(this, e);
} }
if (EventError != null && level >= LogLevel.Error) { if (level >= LogLevel.Error) {
EventError(this, e); EventError?.Invoke(this, e);
} }
EventLog?.Invoke(this, e); EventLog?.Invoke(this, e);
+11
View File
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BlubbFish.Utils {
public abstract class OwnSingeton<T> where T : class {
private static readonly Lazy<T> _instance = new Lazy<T>(() => CreateInstanceOfT());
public static T Instance => _instance.Value;
private static T CreateInstanceOfT() => Activator.CreateInstance(typeof(T), true) as T;
}
}
+1 -7
View File
@@ -1,10 +1,4 @@
using System; namespace BlubbFish.Utils {
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlubbFish.Utils {
public abstract class OwnView { public abstract class OwnView {
protected OwnView() { } protected OwnView() { }
+175 -170
View File
@@ -1,170 +1,175 @@
using System; using System;
using System.IO; using System.IO;
using System.Reflection; using System.Runtime.InteropServices;
using System.Security; using System.Text;
using System.Security.Permissions;
using System.Text; namespace BlubbFish.Utils {
public class ProgramLogger {
namespace BlubbFish.Utils { private FileWriter fw;
public class ProgramLogger { private ConsoleWriter stdout;
private FileWriter fw; private ConsoleWriter errout;
private ConsoleWriter stdout; private String loggerfile;
private ConsoleWriter errout;
private String loggerfile; public ProgramLogger(String path = null) {
this.loggerfile = path ?? Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "output.log";
public ProgramLogger() { this.Init(this.loggerfile);
this.loggerfile = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "output.log"; this.AttachToFw();
this.Init(this.loggerfile); this.SetOutputs();
this.AttachToFw(); }
this.SetOutputs();
} private void SetOutputs() {
Console.SetOut(this.stdout);
private void SetOutputs() { Console.SetError(this.errout);
Console.SetOut(this.stdout); }
Console.SetError(this.errout);
} private void Init(String file) {
if(!this.IsWritable(file)) {
private void Init(String file) { Console.Error.WriteLine("Cannot write to " + file);
if(!this.IsWritable(file)) { throw new ArgumentException("Cannot write to " + file);
Console.Error.WriteLine("Cannot write to " + file); }
throw new ArgumentException("Cannot write to " + file); this.fw = new FileWriter(FileWriter.GetFileSteam(file, false));
} this.stdout = new ConsoleWriter(Console.Out, ConsoleWriterEventArgs.ConsoleType.Info);
this.fw = new FileWriter(file); this.errout = new ConsoleWriter(Console.Error, ConsoleWriterEventArgs.ConsoleType.Error);
this.stdout = new ConsoleWriter(Console.Out, ConsoleWriterEventArgs.ConsoleType.Info); }
this.errout = new ConsoleWriter(Console.Error, ConsoleWriterEventArgs.ConsoleType.Error);
} private Boolean IsWritable(String filename) {
try {
private Boolean IsWritable(String filename) { using FileStream fstream = new FileStream(filename, FileMode.Append);
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); using TextWriter writer = new StreamWriter(fstream);
PermissionSet p = new PermissionSet(PermissionState.None); writer.Write("");
p.AddPermission(writePermission); } catch (UnauthorizedAccessException) {
if (!p.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return false;
return false; }
} return true;
try { }
using (FileStream fstream = new FileStream(filename, FileMode.Append))
using (TextWriter writer = new StreamWriter(fstream)) { public void SetPath(String file) {
writer.Write(""); if(file == null) {
} return;
} catch (UnauthorizedAccessException) { }
return false; if (!this.IsWritable(file)) {
} Console.Error.WriteLine("Cannot write to " + file);
return true; throw new ArgumentException("Cannot write to " + file);
} }
this.DisattachToFw();
public void SetPath(String file) { this.fw.Close();
if(file == null) { if(new FileInfo(this.loggerfile).Length > 0) {
return; if(File.Exists(file)) {
} this.FileCopy(this.loggerfile, file);
if (!this.IsWritable(file)) { File.Delete(this.loggerfile);
Console.Error.WriteLine("Cannot write to " + file); } else {
throw new ArgumentException("Cannot write to " + file); File.Move(this.loggerfile, file);
} }
this.DisattachToFw(); } else {
this.fw.Close(); File.Delete(this.loggerfile);
if(new FileInfo(this.loggerfile).Length > 0) { }
File.Move(this.loggerfile, file); this.loggerfile = file;
} else { this.fw = new FileWriter(FileWriter.GetFileSteam(this.loggerfile, true));
File.Delete(this.loggerfile); this.AttachToFw();
} }
this.loggerfile = file;
this.fw = new FileWriter(this.loggerfile); public void Dispose() {
this.AttachToFw(); this.DisattachToFw();
} this.fw.Dispose();
}
private void DisattachToFw() {
this.stdout.WriteEvent -= this.fw.Write; private void FileCopy(String source, String target) {
this.stdout.WriteLineEvent -= this.fw.WriteLine; using FileStream fread = new FileStream(source, FileMode.Open);
this.errout.WriteEvent -= this.fw.WriteLine; using FileStream fwrite = new FileStream(target, FileMode.Create);
this.errout.WriteLineEvent -= this.fw.WriteLine; using TextReader reader = new StreamReader(fread);
} using TextWriter writer = new StreamWriter(fwrite);
private void AttachToFw() {
this.stdout.WriteEvent += this.fw.Write; writer.Write(reader.ReadToEnd());
this.stdout.WriteLineEvent += this.fw.WriteLine; writer.Flush();
this.errout.WriteEvent += this.fw.WriteLine; writer.Close();
this.errout.WriteLineEvent += this.fw.WriteLine; reader.Close();
} }
}
private void DisattachToFw() {
internal class FileWriter : StreamWriter { this.stdout.WriteEvent -= this.fw.Write;
private Boolean newline = true; this.stdout.WriteLineEvent -= this.fw.WriteLine;
public FileWriter(String path) : base(path) { this.errout.WriteEvent -= this.fw.Write;
} this.errout.WriteLineEvent -= this.fw.WriteLine;
}
public override Encoding Encoding { get { return Encoding.UTF8; } } private void AttachToFw() {
public override Boolean AutoFlush { get { return true; } set { base.AutoFlush = value; } } this.stdout.WriteEvent += this.fw.Write;
this.stdout.WriteLineEvent += this.fw.WriteLine;
private void Write(String value, TextWriter origstream, ConsoleWriterEventArgs.ConsoleType type) { this.errout.WriteEvent += this.fw.Write;
String text = ""; this.errout.WriteLineEvent += this.fw.WriteLine;
if (this.newline) { }
text = "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value; }
this.newline = false;
} else { internal class FileWriter : StreamWriter {
text = value; private Boolean newline = true;
} public FileWriter(FileStream fs) : base(fs) {
origstream.Write(text); }
base.Write(text);
base.Flush(); public static FileStream GetFileSteam(String path, Boolean append) => File.Open(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? FileShare.Write : FileShare.ReadWrite);
}
public override Encoding Encoding => Encoding.UTF8;
private void WriteLine(String value, TextWriter origstream, ConsoleWriterEventArgs.ConsoleType type) { public override Boolean AutoFlush { get => true; set => base.AutoFlush = value; }
String text = "";
if (this.newline) { private void Write(String value, TextWriter origstream, ConsoleWriterEventArgs.ConsoleType type) {
text = "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value; String text;
} else { if (this.newline) {
text = value; text = "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value;
} this.newline = false;
this.newline = true; } else {
origstream.WriteLine(text); text = value;
base.WriteLine(text); }
base.Flush(); origstream.Write(text);
} base.Write(text);
base.Flush();
internal void Write(Object sender, ConsoleWriterEventArgs e) { }
this.Write(e.Value, e.Writer, e.StreamType);
} private void WriteLine(String value, TextWriter origstream, ConsoleWriterEventArgs.ConsoleType type) {
String text = this.newline ? "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value : value;
internal void WriteLine(Object sender, ConsoleWriterEventArgs e) { this.newline = true;
this.WriteLine(e.Value, e.Writer, e.StreamType); origstream.WriteLine(text);
} base.WriteLine(text);
} base.Flush();
}
internal class ConsoleWriterEventArgs : EventArgs {
public String Value { get; private set; } internal void Write(Object sender, ConsoleWriterEventArgs e) => this.Write(e.Value, e.Writer, e.StreamType);
public TextWriter Writer { get; private set; }
public ConsoleType StreamType { get; private set; } internal void WriteLine(Object sender, ConsoleWriterEventArgs e) => this.WriteLine(e.Value, e.Writer, e.StreamType);
}
public enum ConsoleType {
Info, internal class ConsoleWriterEventArgs : EventArgs {
Error public String Value { get; private set; }
} public TextWriter Writer { get; private set; }
public ConsoleType StreamType { get; private set; }
public ConsoleWriterEventArgs(String value, TextWriter writer, ConsoleType type) {
this.Value = value; public enum ConsoleType {
this.Writer = writer; Info,
this.StreamType = type; Error
} }
}
public ConsoleWriterEventArgs(String value, TextWriter writer, ConsoleType type) {
internal class ConsoleWriter : TextWriter { this.Value = value;
private readonly TextWriter stream; this.Writer = writer;
private readonly ConsoleWriterEventArgs.ConsoleType streamtype; this.StreamType = type;
}
public ConsoleWriter(TextWriter writer, ConsoleWriterEventArgs.ConsoleType type) { }
this.stream = writer;
this.streamtype = type; internal class ConsoleWriter : TextWriter {
} private readonly TextWriter stream;
private readonly ConsoleWriterEventArgs.ConsoleType streamtype;
public override Encoding Encoding { get { return Encoding.UTF8; } }
public override void Write(String value) { public ConsoleWriter(TextWriter writer, ConsoleWriterEventArgs.ConsoleType type) {
this.WriteEvent?.Invoke(this, new ConsoleWriterEventArgs(value, this.stream, this.streamtype)); this.stream = writer;
base.Write(value); this.streamtype = type;
} }
public override void WriteLine(String value) {
this.WriteLineEvent?.Invoke(this, new ConsoleWriterEventArgs(value, this.stream, this.streamtype)); public override Encoding Encoding => Encoding.UTF8;
base.WriteLine(value);
} public override void Write(String value) => this.WriteEvent?.Invoke(this, new ConsoleWriterEventArgs(value, this.stream, this.streamtype));
public event EventHandler<ConsoleWriterEventArgs> WriteEvent; //base.Write(value);
public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent;
} public override void WriteLine(String value) => this.WriteLineEvent?.Invoke(this, new ConsoleWriterEventArgs(value, this.stream, this.streamtype));
} //base.WriteLine(value);
public event EventHandler<ConsoleWriterEventArgs> WriteEvent;
public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent;
}
}
+45 -40
View File
@@ -1,40 +1,45 @@
using System.Reflection; #if !NETCOREAPP
using System.Runtime.CompilerServices; using System.Reflection;
using System.Runtime.InteropServices; using System.Resources;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // Allgemeine Informationen über eine Assembly werden über die folgenden
// die mit einer Assembly verknüpft sind. // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
[assembly: AssemblyTitle("Utils")] // die mit einer Assembly verknüpft sind.
[assembly: AssemblyDescription("")] [assembly: AssemblyTitle("Utils")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("Provides useful classes for other projects")]
[assembly: AssemblyCompany("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Utils")] [assembly: AssemblyCompany("BlubbFish")]
[assembly: AssemblyCopyright("Copyright © 2014 - 02.10.2018")] [assembly: AssemblyProduct("Utils")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © BlubbFish 2014 - 10.04.2021")]
[assembly: AssemblyCulture("")] [assembly: AssemblyTrademark("BlubbFish")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar [assembly: NeutralResourcesLanguage("de-DE")]
// 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)] // 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
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: Guid("6f20376a-5c71-4979-9932-13c105d1c6e6")] [assembly: ComVisible(false)]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // 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")]
// Hauptversion
// Nebenversion // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
// Buildnummer //
// Revision // Hauptversion
// // Nebenversion
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // Buildnummer
// übernehmen, indem Sie "*" eingeben: // Revision
// [assembly: AssemblyVersion("1.0.*")] //
[assembly: AssemblyVersion("1.4.0")] // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
[assembly: AssemblyFileVersion("1.4.0")] // übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
/** [assembly: AssemblyVersion("1.5.0")]
* 1.4.0 Add Helper to Utils [assembly: AssemblyFileVersion("1.5.0")]
*/ #endif
/**
* 1.5.0 Add GetEvent so you can call events by string; Add OwnSingeton class
* 1.4.0 Add Helper to Utils
*/
+5 -2
View File
@@ -58,7 +58,7 @@ namespace BlubbFish.Utils {
while (this.t.ThreadState == ThreadState.Running) { } while (this.t.ThreadState == ThreadState.Running) { }
if(exceuteUpdate) { if(exceuteUpdate) {
if(File.Exists("update.bat")) { if(File.Exists("update.bat")) {
System.Diagnostics.Process.Start("update.bat"); _ = System.Diagnostics.Process.Start("update.bat");
} }
} }
} }
@@ -90,6 +90,7 @@ namespace BlubbFish.Utils {
xml.Flush(); xml.Flush();
file.Flush(); file.Flush();
file.Close(); file.Close();
xml.Close();
} }
/// <summary> /// <summary>
@@ -114,7 +115,9 @@ namespace BlubbFish.Utils {
Thread.Sleep(1000); Thread.Sleep(1000);
try { try {
Stream stream = WebRequest.Create(this.url + "version.xml").GetResponse().GetResponseStream(); Stream stream = WebRequest.Create(this.url + "version.xml").GetResponse().GetResponseStream();
String content = new StreamReader(stream).ReadToEnd(); StreamReader sr = new StreamReader(stream);
String content = sr.ReadToEnd();
sr.Close();
Boolean update = false; Boolean update = false;
XmlDocument doc = new XmlDocument(); XmlDocument doc = new XmlDocument();
doc.LoadXml(content); doc.LoadXml(content);
+72
View File
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.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.7.1</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>
</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="EventArgsHelper.cs" />
<Compile Include="FileLogger.cs" />
<Compile Include="FileMutex.cs" />
<Compile Include="Helper.cs" />
<Compile Include="InIReader.cs" />
<Compile Include="OwnController.cs" />
<Compile Include="OwnModel.cs" />
<Compile Include="OwnObject.cs" />
<Compile Include="OwnView.cs" />
<Compile Include="ProgramLogger.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Updater.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\CHANGELOG.md" />
<Content Include="..\CONTRIBUTING.md" />
<Content Include="..\LICENSE" />
<Content Include="..\README.md" />
</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>
+60 -66
View File
@@ -1,66 +1,60 @@
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk">
<Project ToolsVersion="12.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>
<PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <AssemblyName>Utils</AssemblyName>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <RootNamespace>BlubbFish.Utils</RootNamespace>
<ProjectGuid>{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}</ProjectGuid> <Description>Provides useful classes for other projects</Description>
<OutputType>Library</OutputType> <Company>BlubbFish</Company>
<AppDesignerFolder>Properties</AppDesignerFolder> <Authors>BlubbFish</Authors>
<RootNamespace>BlubbFish.Utils</RootNamespace> <PackageId>Utils.BlubbFish</PackageId>
<AssemblyName>Utils</AssemblyName> <Copyright>Copyright © BlubbFish 2014 - 30.01.2022</Copyright>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion> <Version>1.6.2</Version>
<FileAlignment>512</FileAlignment> <NeutralLanguage>de-DE</NeutralLanguage>
<TargetFrameworkProfile /> <PackageLicenseFile>LICENSE</PackageLicenseFile>
</PropertyGroup> <PackageProjectUrl>http://git.blubbfish.net/vs_utils/Utils</PackageProjectUrl>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <RepositoryUrl>http://git.blubbfish.net/vs_utils/Utils.git</RepositoryUrl>
<DebugSymbols>true</DebugSymbols> <RepositoryType>git</RepositoryType>
<DebugType>full</DebugType> <PackageReleaseNotes>
<Optimize>false</Optimize> 1.6.2 - 2022-01-30 - ProgrammLogger improved
<OutputPath>bin\Debug\</OutputPath> 1.6.1 - 2022-01-20 - ProgrammLogger Fixed
<DefineConstants>DEBUG;TRACE</DefineConstants> 1.6.0 - 2022-01-09 - HttpEndpoint added
<ErrorReport>prompt</ErrorReport> 1.5.0 - 2021-04-10 - Add GetEvent so you can call events by string; Add OwnSingeton class
<WarningLevel>4</WarningLevel> 1.4.0 - 2018-11-27 - Add Helper to Utils
</PropertyGroup> 1.1.3 - 2018-10-02 - Improve CmdArgs
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> 1.1.2 - 2018-09-11 - Tiny Codingstyles
<DebugType>pdbonly</DebugType> 1.1.1 - 2018-05-29 - ProgrammLogger neets to cleanup
<Optimize>true</Optimize> 1.1.0 - 2018-05-15 - ProgrammLogger
<OutputPath>bin\Release\</OutputPath> 1.0.7.0 - 2018-05-08 - Yet another IniReader improvemnt round again
<DefineConstants>TRACE</DefineConstants> 1.0.6.0 - 2017-12-22 - Yet another IniReader improvemnt round
<ErrorReport>prompt</ErrorReport> 1.0.5.2 - 2017-09-26 - And Improve IniReader again
<WarningLevel>4</WarningLevel> 1.0.5.1 - 2017-09-24 - Improve IniReader again
</PropertyGroup> 1.0.5.0 - 2017-08-09 - Improve IniReader
<ItemGroup> 1.0.4.1 - 2017-08-08 - Cleanup OwnView
<Reference Include="System" /> 1.0.4.0 - 2017-04-30 - More Updater
<Reference Include="System.Core" /> 1.0.3.2 - 2017-04-26 - Next Updater
<Reference Include="System.Windows.Forms" /> 1.0.3.1 - 2017-04-25 - EventArgsHelper
<Reference Include="System.Xml.Linq" /> 1.0.2.6 - 2017-04-24 - Better Updater
<Reference Include="System.Data.DataSetExtensions" /> 1.0.2.5 - 2017-04-19 - Logging in OwnObject
<Reference Include="Microsoft.CSharp" /> 1.0.2.3 - 2017-04-16 - OwnModel better
<Reference Include="System.Data" /> 1.0.2.2 - 2017-03-09 - Make it nice
<Reference Include="System.Xml" /> 1.0.2.1 - 2017-03-09 - Filemutex
</ItemGroup> 1.0.0.1 - 2016-12-03 - Filelogger improvements
<ItemGroup> 1.0.0.0 - 2015-11-16 - Init
<Compile Include="CmdArgs.cs" /> </PackageReleaseNotes>
<Compile Include="EventArgsHelper.cs" /> </PropertyGroup>
<Compile Include="FileLogger.cs" />
<Compile Include="FileMutex.cs" /> <ItemGroup>
<Compile Include="Helper.cs" /> <Content Include="../CHANGELOG.md" />
<Compile Include="InIReader.cs" /> <Content Include="../CONTRIBUTING.md" />
<Compile Include="OwnController.cs" /> <Content Include="../LICENSE" />
<Compile Include="OwnModel.cs" /> <Content Include="../README.md" />
<Compile Include="OwnObject.cs" /> </ItemGroup>
<Compile Include="OwnView.cs" /> <ItemGroup>
<Compile Include="ProgramLogger.cs" /> <None Include="..\LICENSE">
<Compile Include="Properties\AssemblyInfo.cs" /> <Pack>True</Pack>
<Compile Include="Updater.cs" /> <PackagePath></PackagePath>
</ItemGroup> </None>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </ItemGroup>
<!-- 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. </Project>
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>