From 2b40c8520372a331ddea70ac13bdf916da210c06 Mon Sep 17 00:00:00 2001 From: BlubbFish Date: Sun, 24 Nov 2019 18:29:02 +0100 Subject: [PATCH] Refactoring and add net core project --- Utils/CmdArgs.cs | 5 +--- Utils/EventArgsHelper.cs | 4 +-- Utils/FileLogger.cs | 13 ++++----- Utils/FileMutex.cs | 8 ++++-- Utils/Helper.cs | 30 +++----------------- Utils/InIReader.cs | 47 +++++++++++--------------------- Utils/OwnController.cs | 15 ++-------- Utils/OwnModel.cs | 29 +++++--------------- Utils/OwnObject.cs | 35 ++++++++++-------------- Utils/OwnView.cs | 8 +----- Utils/ProgramLogger.cs | 39 +++++++------------------- Utils/Properties/AssemblyInfo.cs | 9 +++--- Utils/Updater.cs | 7 +++-- Utils/Utils_Core.csproj | 9 ++++++ Utils_Core.sln | 25 +++++++++++++++++ 15 files changed, 110 insertions(+), 173 deletions(-) create mode 100644 Utils/Utils_Core.csproj create mode 100644 Utils_Core.sln diff --git a/Utils/CmdArgs.cs b/Utils/CmdArgs.cs index ffb1b97..0bf0df1 100644 --- a/Utils/CmdArgs.cs +++ b/Utils/CmdArgs.cs @@ -113,10 +113,7 @@ namespace BlubbFish.Utils /// Menge der angegebenen Komandozeilen-Argumente /// /// Menge - public Int32 GetArgsLength() - { - return this.argList.Count; - } + public Int32 GetArgsLength() => this.argList.Count; /// /// Gibt zurück ob ein Argument angegeben wurde diff --git a/Utils/EventArgsHelper.cs b/Utils/EventArgsHelper.cs index b87fd6f..c4e2875 100644 --- a/Utils/EventArgsHelper.cs +++ b/Utils/EventArgsHelper.cs @@ -11,9 +11,7 @@ namespace BlubbFish.Utils { } public class UpdaterFailEventArgs : EventArgs { - public UpdaterFailEventArgs(Exception e) { - this.Except = e; - } + public UpdaterFailEventArgs(Exception e) => this.Except = e; public Exception Except { get; private set; } } diff --git a/Utils/FileLogger.cs b/Utils/FileLogger.cs index 3b04fca..327c77d 100644 --- a/Utils/FileLogger.cs +++ b/Utils/FileLogger.cs @@ -9,7 +9,7 @@ namespace BlubbFish.Utils { public class FileLogger { - private static Dictionary instances = new Dictionary(); + private static readonly Dictionary instances = new Dictionary(); private static String logDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; private readonly StreamWriter file; private FileLogger(String filename, Boolean append) @@ -18,7 +18,7 @@ namespace BlubbFish.Utils if (!File.Exists(filename)) { String folder = Path.GetDirectoryName(Path.GetFullPath(filename)); if (!Directory.Exists(folder)) { - Directory.CreateDirectory(folder); + _ = Directory.CreateDirectory(folder); } } this.file = new StreamWriter(filename, append, Encoding.UTF8) { @@ -40,11 +40,11 @@ namespace BlubbFish.Utils if (Directory.Exists(v)) { logDir = v; } else { - Directory.CreateDirectory(v); + _ = Directory.CreateDirectory(v); logDir = v; } if (logDir.Substring(logDir.Length - 1) != Path.DirectorySeparatorChar.ToString()) { - logDir = logDir + Path.DirectorySeparatorChar; + logDir += Path.DirectorySeparatorChar; } } @@ -59,9 +59,6 @@ namespace BlubbFish.Utils this.file.WriteLine(text); this.file.Flush(); } - public void SetLine(String text, DateTime d) - { - this.SetLine(d.ToString("[yyyy-MM-dd HH:mm:ss.ffff] ") + text); - } + public void SetLine(String text, DateTime d) => this.SetLine(d.ToString("[yyyy-MM-dd HH:mm:ss.ffff] ") + text); } } diff --git a/Utils/FileMutex.cs b/Utils/FileMutex.cs index 567b753..b77eaad 100644 --- a/Utils/FileMutex.cs +++ b/Utils/FileMutex.cs @@ -25,7 +25,9 @@ namespace BlubbFish.Utils public void SetName(String name) { 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() @@ -35,7 +37,7 @@ namespace BlubbFish.Utils } this.file = new StreamWriter(this.filename); - InitFile(); + this.InitFile(); return File.Exists(this.filename) && this.file != null; } @@ -64,7 +66,7 @@ namespace BlubbFish.Utils } public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } } diff --git a/Utils/Helper.cs b/Utils/Helper.cs index 01f14c4..f6ffcd9 100644 --- a/Utils/Helper.cs +++ b/Utils/Helper.cs @@ -17,10 +17,7 @@ namespace BlubbFish.Utils { public static Object GetProperty(this Object o, String name) { PropertyInfo prop = o.GetType().GetProperty(name); - if (prop.CanRead) { - return prop.GetValue(o); - } - return null; + return prop.CanRead ? prop.GetValue(o) : null; } public static void SetProperty(this Object o, String name, String value) { @@ -57,36 +54,17 @@ namespace BlubbFish.Utils { return false; } - public static Boolean HasAbstract(this Type o, Type type) { - if (o.BaseType == type) { - return true; - } - return false; - } + public static Boolean HasAbstract(this Type o, Type type) => o.BaseType == type; #endregion #region StringHelper public static String GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); - DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); - - if (attributes != null && attributes.Length > 0) { - return attributes[0].Description; - } else { - return value.ToString(); - } + return attributes != null && attributes.Length > 0 ? attributes[0].Description : value.ToString(); } - public static String ToUpperLower(this String s) { - if (s.Length == 0) { - return ""; - } - if (s.Length == 1) { - return s.ToUpper(); - } - return s[0].ToString().ToUpper() + s.Substring(1).ToLower(); - } + public static String ToUpperLower(this String s) => s.Length == 0 ? "" : s.Length == 1 ? s.ToUpper() : s[0].ToString().ToUpper() + s.Substring(1).ToLower(); public static void WriteError(String text) { Console.ForegroundColor = ConsoleColor.Red; diff --git a/Utils/InIReader.cs b/Utils/InIReader.cs index d20f1f2..1561d72 100644 --- a/Utils/InIReader.cs +++ b/Utils/InIReader.cs @@ -10,15 +10,13 @@ namespace BlubbFish.Utils { private Dictionary> inifile; private readonly FileSystemWatcher k; private readonly String filename; - private static List search_path = new List() { + private static readonly List search_path = new List() { Directory.GetCurrentDirectory() }; - private static Dictionary instances = new Dictionary(); + private static readonly Dictionary instances = new Dictionary(); - public static void SetSearchPath(List directorys) { - search_path.AddRange(directorys); - } + public static void SetSearchPath(List directorys) => search_path.AddRange(directorys); public static Boolean ConfigExist(String filename) { foreach (String path in search_path) { @@ -54,7 +52,7 @@ namespace BlubbFish.Utils { throw new ArgumentException(filename + " not found!"); } this.k.Changed += new FileSystemEventHandler(this.ReadAgain); - LoadFile(); + this.LoadFile(); } /// @@ -70,10 +68,7 @@ namespace BlubbFish.Utils { return instances[filename]; } - private void ReadAgain(Object sender, EventArgs e) - { - this.LoadFile(); - } + private void ReadAgain(Object sender, EventArgs e) => this.LoadFile(); private void LoadFile() { @@ -123,7 +118,7 @@ namespace BlubbFish.Utils { } else { List ret = new List(); foreach (String item in this.inifile.Keys) { - ret.Add(item.Substring(1, item.Length - 2)); + ret.Add(item[1..^1]); } return ret; } @@ -147,15 +142,9 @@ namespace BlubbFish.Utils { this.Changed(); } - public Dictionary GetSection(String section) { - if(this.inifile.Keys.Contains(section)) { - return this.inifile[section]; - } - if(this.inifile.Keys.Contains("["+section+"]")) { - return this.inifile["[" + section + "]"]; - } - return new Dictionary(); - } + public Dictionary GetSection(String section) => this.inifile.Keys.Contains(section) ? + this.inifile[section] : this.inifile.Keys.Contains("[" + section + "]") ? + this.inifile["[" + section + "]"] : new Dictionary(); /// /// Gibt einen einzelnen Wert zurück @@ -168,12 +157,7 @@ namespace BlubbFish.Utils { if (!section.StartsWith("[")) { section = "[" + section + "]"; } - if (this.inifile.Keys.Contains(section)) { - if (this.inifile[section].Keys.Contains(key)) { - return this.inifile[section][key]; - } - } - return null; + return this.inifile.Keys.Contains(section) && this.inifile[section].Keys.Contains(key) ? this.inifile[section][key] : null; } /// @@ -205,8 +189,8 @@ namespace BlubbFish.Utils { private void Changed() { this.k.Changed -= null; - SaveSettings(); - LoadFile(); + this.SaveSettings(); + this.LoadFile(); this.k.Changed += new FileSystemEventHandler(this.ReadAgain); } @@ -215,7 +199,7 @@ namespace BlubbFish.Utils { StreamWriter file = new StreamWriter(this.filename); file.BaseStream.SetLength(0); file.BaseStream.Flush(); - file.BaseStream.Seek(0, SeekOrigin.Begin); + _ = file.BaseStream.Seek(0, SeekOrigin.Begin); foreach (KeyValuePair> cap in this.inifile) { file.WriteLine(cap.Key); foreach (KeyValuePair sub in cap.Value) { @@ -258,10 +242,11 @@ namespace BlubbFish.Utils { if (!this.inifile.Keys.Contains(name)) { return false; } - this.inifile.Remove(name); + _ = this.inifile.Remove(name); this.Changed(); return false; } + protected virtual void Dispose(Boolean disposing) { if (disposing) { this.k.Dispose(); @@ -269,7 +254,7 @@ namespace BlubbFish.Utils { } public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } } diff --git a/Utils/OwnController.cs b/Utils/OwnController.cs index 385827e..f7b76b0 100644 --- a/Utils/OwnController.cs +++ b/Utils/OwnController.cs @@ -1,21 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; - -namespace BlubbFish.Utils -{ +namespace BlubbFish.Utils { public abstract class OwnController { /// /// Führt den Controller aus. /// - public void Execute() - { - this.Init(); - } + public void Execute() => this.Init(); abstract protected void Init(); abstract public void Dispose(); } diff --git a/Utils/OwnModel.cs b/Utils/OwnModel.cs index d856c0f..17277d4 100644 --- a/Utils/OwnModel.cs +++ b/Utils/OwnModel.cs @@ -1,25 +1,13 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace BlubbFish.Utils -{ +namespace BlubbFish.Utils { public abstract class OwnModel where T : class { private static readonly Lazy _instance = new Lazy(() => CreateInstanceOfT()); private readonly List observer = new List(); - public static T Instance - { - get { - return _instance.Value; - } - } - private static T CreateInstanceOfT() - { - return Activator.CreateInstance(typeof(T), true) as T; - } + public static T Instance => _instance.Value; + private static T CreateInstanceOfT() => Activator.CreateInstance(typeof(T), true) as T; public void SetObserver(OwnView view) { @@ -27,13 +15,10 @@ namespace BlubbFish.Utils view.Update(); } - public void RemoveObserver(OwnView view) { - this.observer.Remove(view); - } - protected void Update() - { - this.observer.ForEach(delegate (OwnView 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(); } diff --git a/Utils/OwnObject.cs b/Utils/OwnObject.cs index 7a6c661..901c208 100644 --- a/Utils/OwnObject.cs +++ b/Utils/OwnObject.cs @@ -21,21 +21,17 @@ namespace BlubbFish.Utils /// Formates a LogMessage to a String /// /// Formated String - public override String ToString() { - return "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " "+ this.Location + ", " + this.Message; - } + public override String ToString() => "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " " + this.Location + ", " + this.Message; /// /// Formates a LogMessage to a String /// /// Enables the output of the location /// Enables the output of the date /// Formated String - public String ToString(Boolean classNames, Boolean timeStamps) { - return (timeStamps ? "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " " : "") + (classNames ? this.Location + ", " : "") + this.Message; - } + public String ToString(Boolean classNames, Boolean timeStamps) => (timeStamps ? "[" + this.Date.ToString("R") + "]: " + this.Level.ToString() + " " : "") + (classNames ? this.Location + ", " : "") + this.Message; } - private List loglist = new List(); + private readonly List loglist = new List(); public delegate void LogEvent(Object sender, LogEventArgs e); public enum LogLevel : Int32 { @@ -72,10 +68,7 @@ namespace BlubbFish.Utils /// Where the event arrives /// The logmessage itselfs /// Level of the 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) => this.AddLog(location, message, level, DateTime.Now); /// /// Put a message in the log @@ -87,20 +80,20 @@ namespace BlubbFish.Utils protected void AddLog(String location, String message, LogLevel level, DateTime date) { LogEventArgs e = new LogEventArgs(location, message, level, date); - if (EventDebug != null && level >= LogLevel.Debug) { - EventDebug(this, e); + if (level >= LogLevel.Debug) { + EventDebug?.Invoke(this, e); } - if (EventNotice != null && level >= LogLevel.Notice) { - EventNotice(this, e); + if (level >= LogLevel.Notice) { + EventNotice?.Invoke(this, e); } - if (EventInfo != null && level >= LogLevel.Info) { - EventInfo(this, e); + if (level >= LogLevel.Info) { + EventInfo?.Invoke(this, e); } - if (EventWarn != null && level >= LogLevel.Warn) { - EventWarn(this, e); + if (level >= LogLevel.Warn) { + EventWarn?.Invoke(this, e); } - if (EventError != null && level >= LogLevel.Error) { - EventError(this, e); + if (level >= LogLevel.Error) { + EventError?.Invoke(this, e); } EventLog?.Invoke(this, e); diff --git a/Utils/OwnView.cs b/Utils/OwnView.cs index bd30612..c938f73 100644 --- a/Utils/OwnView.cs +++ b/Utils/OwnView.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace BlubbFish.Utils { +namespace BlubbFish.Utils { public abstract class OwnView { protected OwnView() { } diff --git a/Utils/ProgramLogger.cs b/Utils/ProgramLogger.cs index 4f297b2..dc4c89e 100644 --- a/Utils/ProgramLogger.cs +++ b/Utils/ProgramLogger.cs @@ -1,8 +1,5 @@ using System; using System.IO; -using System.Reflection; -using System.Security; -using System.Security.Permissions; using System.Text; namespace BlubbFish.Utils { @@ -35,17 +32,10 @@ namespace BlubbFish.Utils { } private Boolean IsWritable(String filename) { - FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); - PermissionSet p = new PermissionSet(PermissionState.None); - p.AddPermission(writePermission); - if (!p.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { - return false; - } try { - using (FileStream fstream = new FileStream(filename, FileMode.Append)) - using (TextWriter writer = new StreamWriter(fstream)) { - writer.Write(""); - } + using FileStream fstream = new FileStream(filename, FileMode.Append); + using TextWriter writer = new StreamWriter(fstream); + writer.Write(""); } catch (UnauthorizedAccessException) { return false; } @@ -91,11 +81,11 @@ namespace BlubbFish.Utils { public FileWriter(String path) : base(path) { } - public override Encoding Encoding { get { return Encoding.UTF8; } } - public override Boolean AutoFlush { get { return true; } set { base.AutoFlush = value; } } + public override Encoding Encoding => Encoding.UTF8; + public override Boolean AutoFlush { get => true; set => base.AutoFlush = value; } private void Write(String value, TextWriter origstream, ConsoleWriterEventArgs.ConsoleType type) { - String text = ""; + String text; if (this.newline) { text = "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value; this.newline = false; @@ -108,25 +98,16 @@ namespace BlubbFish.Utils { } private void WriteLine(String value, TextWriter origstream, ConsoleWriterEventArgs.ConsoleType type) { - String text = ""; - if (this.newline) { - text = "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value; - } else { - text = value; - } + String text = this.newline ? "[" + DateTime.Now.ToString("o") + "]-" + type.ToString() + ": " + value : value; this.newline = true; origstream.WriteLine(text); base.WriteLine(text); base.Flush(); } - internal void Write(Object sender, ConsoleWriterEventArgs e) { - this.Write(e.Value, e.Writer, e.StreamType); - } + internal void Write(Object sender, ConsoleWriterEventArgs e) => this.Write(e.Value, e.Writer, e.StreamType); - internal void WriteLine(Object sender, ConsoleWriterEventArgs e) { - this.WriteLine(e.Value, e.Writer, e.StreamType); - } + internal void WriteLine(Object sender, ConsoleWriterEventArgs e) => this.WriteLine(e.Value, e.Writer, e.StreamType); } internal class ConsoleWriterEventArgs : EventArgs { @@ -155,7 +136,7 @@ namespace BlubbFish.Utils { this.streamtype = type; } - public override Encoding Encoding { get { return Encoding.UTF8; } } + public override Encoding Encoding => Encoding.UTF8; public override void Write(String value) { this.WriteEvent?.Invoke(this, new ConsoleWriterEventArgs(value, this.stream, this.streamtype)); base.Write(value); diff --git a/Utils/Properties/AssemblyInfo.cs b/Utils/Properties/AssemblyInfo.cs index 76c47c8..d456bd3 100644 --- a/Utils/Properties/AssemblyInfo.cs +++ b/Utils/Properties/AssemblyInfo.cs @@ -1,18 +1,19 @@ using System.Reflection; -using System.Runtime.CompilerServices; +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, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("Utils")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyDescription("Provides useful classes for other projects")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] +[assembly: AssemblyCompany("BlubbFish")] [assembly: AssemblyProduct("Utils")] [assembly: AssemblyCopyright("Copyright © 2014 - 02.10.2018")] -[assembly: AssemblyTrademark("")] +[assembly: AssemblyTrademark("BlubbFish")] [assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("de-DE")] // 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 diff --git a/Utils/Updater.cs b/Utils/Updater.cs index fc4eb0e..aedd0d2 100644 --- a/Utils/Updater.cs +++ b/Utils/Updater.cs @@ -58,7 +58,7 @@ namespace BlubbFish.Utils { while (this.t.ThreadState == ThreadState.Running) { } if(exceuteUpdate) { 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(); file.Flush(); file.Close(); + xml.Close(); } /// @@ -114,7 +115,9 @@ namespace BlubbFish.Utils { Thread.Sleep(1000); try { 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; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); diff --git a/Utils/Utils_Core.csproj b/Utils/Utils_Core.csproj new file mode 100644 index 0000000..455e564 --- /dev/null +++ b/Utils/Utils_Core.csproj @@ -0,0 +1,9 @@ + + + + netcoreapp3.0 + Utils + BlubbFish.Utils + + + diff --git a/Utils_Core.sln b/Utils_Core.sln new file mode 100644 index 0000000..ea29322 --- /dev/null +++ b/Utils_Core.sln @@ -0,0 +1,25 @@ + +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_Core.csproj", "{A289C67C-BC49-46A0-8657-B444C605079E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A289C67C-BC49-46A0-8657-B444C605079E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A289C67C-BC49-46A0-8657-B444C605079E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A289C67C-BC49-46A0-8657-B444C605079E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A289C67C-BC49-46A0-8657-B444C605079E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A7224DC4-69F1-4273-BE78-3D9DC80A28C5} + EndGlobalSection +EndGlobal