From 1b49c54822dc0e2e0e8b1f8f7b8647763fd06965 Mon Sep 17 00:00:00 2001 From: Pilzinsel64 Date: Wed, 5 Jun 2024 19:15:32 +0200 Subject: [PATCH] code optimization --- .../SimpleHistory/ObjectAction.vb | 1 - .../SimpleHistory/SimpleHistory.vb | 4 +- .../AutoSaveConfigurationManager.cs | 157 +++--- Pilz.Configuration/ConfigurationManager.cs | 17 +- .../ConfigurationManagerList.cs | 163 ++++--- Pilz.Configuration/ConfigurationSerializer.cs | 243 +++++----- Pilz.Configuration/IChildSettings.cs | 9 +- Pilz.Configuration/ISettings.cs | 13 +- Pilz.Configuration/ISettingsIdentifier.cs | 13 +- Pilz.Configuration/ISettingsManager.cs | 15 +- Pilz.Configuration/Settings.cs | 52 +- Pilz.Configuration/SettingsManager.cs | 239 +++++---- Pilz.Configuration/SimpleConfiguration.cs | 187 ++++---- Pilz.Cryptography/Helpers.cs | 68 ++- Pilz.Cryptography/ICrypter.cs | 15 +- Pilz.Cryptography/IUniquieID.cs | 22 +- Pilz.Cryptography/IUniquieIDHost.cs | 17 +- .../UniquieIDStringJsonConverter.cs | 47 +- Pilz.Cryptography/Properties/AssemblyInfo.cs | 4 +- Pilz.Cryptography/SecureString.cs | 137 +++--- .../SecureStringJsonConverter.cs | 51 +- Pilz.Cryptography/SimpleStringCrypter.cs | 129 ++--- Pilz.Cryptography/UniquieID.cs | 243 +++++----- Pilz.Cryptography/UniquieIDGenerationMode.cs | 15 +- .../Camera/Camera.vb | 1 - .../Preview/ModelPreview.vb | 28 +- .../Rendering/BoundingBox.vb | 13 +- .../Rendering/ContentPipe.vb | 18 +- .../Rendering/Renderer.vb | 7 +- Pilz.Drawing/HelpfulDrawingFunctions.vb | 1 - Pilz.Gaming.Minecraft/Utils.cs | 59 ++- Pilz.IO/EmbeddedFilesContainer.cs | 285 ++++++----- Pilz.IO/EventArgs/DataEventargs.cs | 17 +- Pilz.IO/Extensions.cs | 29 +- Pilz.IO/FileLocker.cs | 211 ++++---- Pilz.IO/ManagedPipes/ManagedPipe.cs | 103 ++-- Pilz.IO/ManagedPipes/ManagedPipeClient.cs | 139 +++--- Pilz.IO/ManagedPipes/ManagedPipeServer.cs | 193 ++++---- Pilz.IO/Properties/AssemblyInfo.cs | 1 - Pilz.LicenseHelper/AsposeModifyInMemory.cs | 277 ++++++----- Pilz.LicenseHelper/Properties/AssemblyInfo.cs | 4 +- .../FileRetention/FilesRetentionClient.cs | 66 ++- .../Apps/FileRetention/Model/RetentionRule.cs | 52 +- .../FileRetention/Model/RetentionRuleInfo.cs | 66 ++- .../FileRetention/Model/RetentionTimeAfter.cs | 15 +- .../FileRetention/Model/RetentionTimeUnit.cs | 19 +- .../FileRetention/Ocs/OcsDataRetentionRule.cs | 28 +- .../Ocs/OcsResponseDataEntryRetention.cs | 36 +- .../FileRetention/Ocs/OcsResponseRetention.cs | 15 +- .../FileRetention/OcsApiFilesRetention.cs | 49 +- .../Client/Apps/Tables/Model/Column.cs | 210 ++++---- .../Tables/Model/ColumnSelectionOption.cs | 20 +- .../Client/Apps/Tables/Model/ColumnSubtype.cs | 17 +- .../Client/Apps/Tables/Model/ColumnType.cs | 19 +- .../Client/Apps/Tables/Model/Columns.cs | 11 +- .../Client/Apps/Tables/Model/Row.cs | 40 +- .../Client/Apps/Tables/Model/RowData.cs | 20 +- .../Client/Apps/Tables/Model/RowSimple.cs | 11 +- .../Client/Apps/Tables/Model/RowUpdate.cs | 16 +- .../Client/Apps/Tables/Model/Rows.cs | 11 +- .../Client/Apps/Tables/Model/RowsSimple.cs | 11 +- .../Client/Apps/Tables/OcsApiTables.cs | 127 +++-- .../Client/Apps/Tables/TablesClient.cs | 118 +++-- .../Client/ClientBase.cs | 28 +- .../Client/Cloud/CloudClient.cs | 46 +- .../Cloud/Model/UserBackendCapabilities.cs | 28 +- .../Client/Cloud/Model/UserInfo.cs | 236 +++++---- .../Client/Cloud/Model/UserQuota.cs | 52 +- .../Client/Cloud/Ocs/OcsResponseDataUser.cs | 152 +++--- .../Client/Cloud/Ocs/OcsResponseUser.cs | 15 +- .../Client/Cloud/OcsApiCloud.cs | 26 +- .../Client/Core/OcsApiCore.cs | 42 +- .../LoginFlowV2/Ocs/OcsResponseLoginFlowV2.cs | 54 +-- .../Ocs/OcsResponseLoginFlowV2Credentials.cs | 42 +- .../Client/LoginFlowV2/OcsApiLoginFlowV2.cs | 46 +- .../Extensions.cs | 61 ++- .../NextcloudClient.cs | 287 +++++------ .../NextcloudLogin.cs | 59 +-- .../OCS/GetOcsApiAuthCredentailsEventArgs.cs | 17 +- .../OCS/OcsApi.cs | 380 ++++++++------- .../OCS/OcsApiAuthCredentials.cs | 24 +- .../OCS/OcsApiBase.cs | 19 +- .../OCS/OcsApiResponse.cs | 17 +- .../OCS/OcsApiUrlPath.cs | 39 +- .../OCS/OcsData.cs | 11 +- .../OCS/Responses/IOcsResponse.cs | 11 +- .../OCS/Responses/IOcsResponseData.cs | 11 +- .../OCS/Responses/IOcsResponseMeta.cs | 11 +- .../OCS/Responses/OcsResponse.cs | 36 +- .../OCS/Responses/OcsResponseData.cs | 11 +- .../OCS/Responses/OcsResponseDataArray.cs | 11 +- .../OCS/Responses/OcsResponseDataEntry.cs | 11 +- .../OCS/Responses/OcsResponseMeta.cs | 24 +- Pilz.Networking/ConnectionManagerBase.vb | 1 + Pilz.Networking/TCPManager.vb | 14 +- Pilz.Networking/UDPManager.vb | 14 +- .../Extensions.cs | 212 ++++---- .../PluginModule.cs | 48 +- .../PluginModuleUI.cs | 23 +- Pilz.Plugins.Advanced.UI/FeatureInsertMode.cs | 65 ++- .../FeatureInsertPosition.cs | 21 +- Pilz.Plugins.Advanced.UI/PluginModule.cs | 82 ++-- .../FeaturePrioritization.cs | 17 +- .../IPluginFeatureProvider.cs | 27 +- .../IPluginFeaturesProvider.cs | 13 +- Pilz.Plugins.Advanced/PluginFeature.cs | 99 ++-- .../PluginFeatureController.cs | 454 +++++++++--------- Pilz.Plugins.Advanced/PluginFunction.cs | 79 ++- .../PluginFunctionParameter.cs | 11 +- .../PluginFunctionSimpleParamter.cs | 19 +- Pilz.Plugins.Advanced/PluginModuleBase.cs | 21 +- Pilz.Plugins/IPlugin.cs | 9 +- Pilz.Plugins/IPluginLateInitialization.cs | 13 +- Pilz.Plugins/PluginLoadContext.cs | 50 +- Pilz.Plugins/PluginLoadInfo.cs | 22 +- Pilz.Plugins/PluginLoadStatus.cs | 23 +- Pilz.Plugins/PluginManager.cs | 14 +- Pilz.Plugins/PluginManagerT.cs | 373 +++++++------- Pilz.Plugins/PluginRuntimeInfo.cs | 11 +- Pilz.Plugins/PluginRuntimeInfoT.cs | 22 +- Pilz.Plugins/PluginStatus.cs | 19 +- .../FileParser/Aspose3DLoader.vb | 2 +- .../FileParser/AssimpLoader.vb | 1 + Pilz.Simple3DFileParser/FileParser/Obj.vb | 1 + Pilz.Simple3DFileParser/Model/Object3D.vb | 3 +- Pilz.Simple3DFileParser/Other/Extensions.vb | 3 +- Pilz.Simple3DFileParser/Other/LoaderModule.vb | 10 +- Pilz.UI.Telerik.SymbolFactory/Extensions.cs | 30 +- Pilz.UI.Telerik.SymbolFactory/SvgImageSize.cs | 19 +- .../SymbolFactory.cs | 124 +++-- Pilz.UI.Telerik/Dialogs/DialogBase.Statics.cs | 146 +++--- Pilz.UI.Telerik/Dialogs/DialogBase.cs | 53 +- .../Dialogs/DialogClosedEventArgs.cs | 22 +- .../Dialogs/DialogLoadingEventArgs.cs | 23 +- Pilz.UI.Telerik/Dialogs/FlyoutBase.Statics.cs | 167 +++---- Pilz.UI.Telerik/Dialogs/FlyoutBase.cs | 166 +++---- .../Dialogs/FlyoutClosedEventArgs.cs | 18 +- .../Dialogs/FlyoutCreatedEventArgs.cs | 21 +- Pilz.UI.Telerik/Dialogs/ILoadContent.cs | 13 +- Pilz.UI/Highlighter.vb | 14 +- .../PaintingControl/DefaultDrawMethodes.vb | 1 + .../EventArgs/PaintingObjectEventArgs.vb | 15 +- .../EventArgs/PaintingObjectPaintEventArgs.vb | 13 +- .../IPaintingObjectContainer.vb | 4 +- Pilz.UI/PaintingControl/LineCapProps.vb | 4 +- Pilz.UI/PaintingControl/PaintingControl.vb | 2 +- Pilz.UI/PaintingControl/PaintingObject.vb | 4 +- .../PaintingControl/PaintingObjectResizing.vb | 3 - Pilz.Win32/Internals/IconFactory.vb | 19 +- Pilz.Win32/Mapped/NativeFileInfo.vb | 1 + Pilz/Runtime/RuntimeInformationsEx.vb | 88 ++-- 151 files changed, 4124 insertions(+), 4673 deletions(-) diff --git a/Pilz.Collections/SimpleHistory/ObjectAction.vb b/Pilz.Collections/SimpleHistory/ObjectAction.vb index 7861237..5af9e86 100644 --- a/Pilz.Collections/SimpleHistory/ObjectAction.vb +++ b/Pilz.Collections/SimpleHistory/ObjectAction.vb @@ -1,5 +1,4 @@ Imports System.Reflection -Imports System.Runtime.InteropServices Namespace SimpleHistory diff --git a/Pilz.Collections/SimpleHistory/SimpleHistory.vb b/Pilz.Collections/SimpleHistory/SimpleHistory.vb index 872a76b..1277754 100644 --- a/Pilz.Collections/SimpleHistory/SimpleHistory.vb +++ b/Pilz.Collections/SimpleHistory/SimpleHistory.vb @@ -1,6 +1,4 @@ -Imports System.Reflection - -Namespace SimpleHistory +Namespace SimpleHistory Public Class HistoryStack diff --git a/Pilz.Configuration/AutoSaveConfigurationManager.cs b/Pilz.Configuration/AutoSaveConfigurationManager.cs index 75461d7..0b590cf 100644 --- a/Pilz.Configuration/AutoSaveConfigurationManager.cs +++ b/Pilz.Configuration/AutoSaveConfigurationManager.cs @@ -1,87 +1,86 @@ using System; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public class AutoSaveConfigurationManager : ConfigurationManager { - public class AutoSaveConfigurationManager : ConfigurationManager + private bool addedHandler = false; + private bool enableAutoSave = false; + private string _ConfigFilePath = string.Empty; + private bool _AutoLoadConfigOnAccess = false; + + public string ConfigFilePath { - private bool addedHandler = false; - private bool enableAutoSave = false; - private string _ConfigFilePath = string.Empty; - private bool _AutoLoadConfigOnAccess = false; - - public string ConfigFilePath + get => _ConfigFilePath; + set { - get => _ConfigFilePath; - set - { - _ConfigFilePath = value; - if (AutoLoadConfigOnAccess) - Load(); - } - } - - public bool AutoLoadConfigOnAccess - { - get => _AutoLoadConfigOnAccess; - set - { - _AutoLoadConfigOnAccess = value; - if (value) - Load(); - } - } - - public bool AutoSaveConfigOnExit - { - get => enableAutoSave; - set - { - if (enableAutoSave != value) - { - enableAutoSave = value; - if (enableAutoSave) - AddAutoSaveHandler(); - else - RemoveAutoSaveHandler(); - } - } - } - - private void AddAutoSaveHandler() - { - if (!addedHandler) - { - AppDomain.CurrentDomain.ProcessExit += AutoSaveSettingsOnExit; - addedHandler = true; - } - } - - private void RemoveAutoSaveHandler() - { - AppDomain.CurrentDomain.ProcessExit -= AutoSaveSettingsOnExit; - addedHandler = false; - } - - private void AutoSaveSettingsOnExit(object sender, EventArgs e) - { - Save(); - } - - private void Save() - { - if (!string.IsNullOrEmpty(ConfigFilePath) && Configuration is not null) - Configuration.WriteToFile(ConfigFilePath); - } - - private void Load() - { - if (!string.IsNullOrEmpty(ConfigFilePath)) - Configuration.ReadFromFile(ConfigFilePath); - } - - ~AutoSaveConfigurationManager() - { - RemoveAutoSaveHandler(); + _ConfigFilePath = value; + if (AutoLoadConfigOnAccess) + Load(); } } + + public bool AutoLoadConfigOnAccess + { + get => _AutoLoadConfigOnAccess; + set + { + _AutoLoadConfigOnAccess = value; + if (value) + Load(); + } + } + + public bool AutoSaveConfigOnExit + { + get => enableAutoSave; + set + { + if (enableAutoSave != value) + { + enableAutoSave = value; + if (enableAutoSave) + AddAutoSaveHandler(); + else + RemoveAutoSaveHandler(); + } + } + } + + private void AddAutoSaveHandler() + { + if (!addedHandler) + { + AppDomain.CurrentDomain.ProcessExit += AutoSaveSettingsOnExit; + addedHandler = true; + } + } + + private void RemoveAutoSaveHandler() + { + AppDomain.CurrentDomain.ProcessExit -= AutoSaveSettingsOnExit; + addedHandler = false; + } + + private void AutoSaveSettingsOnExit(object sender, EventArgs e) + { + Save(); + } + + private void Save() + { + if (!string.IsNullOrEmpty(ConfigFilePath) && Configuration is not null) + Configuration.WriteToFile(ConfigFilePath); + } + + private void Load() + { + if (!string.IsNullOrEmpty(ConfigFilePath)) + Configuration.ReadFromFile(ConfigFilePath); + } + + ~AutoSaveConfigurationManager() + { + RemoveAutoSaveHandler(); + } } \ No newline at end of file diff --git a/Pilz.Configuration/ConfigurationManager.cs b/Pilz.Configuration/ConfigurationManager.cs index eca8da5..c06960e 100644 --- a/Pilz.Configuration/ConfigurationManager.cs +++ b/Pilz.Configuration/ConfigurationManager.cs @@ -1,12 +1,11 @@ -namespace Pilz.Configuration -{ - public abstract class ConfigurationManager - { - public SimpleConfiguration Configuration { get; private set; } +namespace Pilz.Configuration; - internal void SetConfiguration(SimpleConfiguration configuration) - { - Configuration = configuration; - } +public abstract class ConfigurationManager +{ + public SimpleConfiguration Configuration { get; private set; } + + internal void SetConfiguration(SimpleConfiguration configuration) + { + Configuration = configuration; } } \ No newline at end of file diff --git a/Pilz.Configuration/ConfigurationManagerList.cs b/Pilz.Configuration/ConfigurationManagerList.cs index ada1eca..6d935cd 100644 --- a/Pilz.Configuration/ConfigurationManagerList.cs +++ b/Pilz.Configuration/ConfigurationManagerList.cs @@ -1,88 +1,87 @@ -using System.Collections; +using Pilz.GeneralEventArgs; +using System.Collections; using System.Collections.Generic; -using Pilz.GeneralEventArgs; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public class ConfigurationManagerList : IList { - public class ConfigurationManagerList : IList + public event GettingParentManagerEventHandler GettingParentManager; + + public delegate void GettingParentManagerEventHandler(object sender, GetValueEventArgs e); + + private readonly List myList = new List(); + + private object GetParentManager() { - public event GettingParentManagerEventHandler GettingParentManager; - - public delegate void GettingParentManagerEventHandler(object sender, GetValueEventArgs e); - - private readonly List myList = new List(); - - private object GetParentManager() - { - var args = new GetValueEventArgs(); - GettingParentManager?.Invoke(this, args); - return args.Value; - } - - public ConfigurationManager this[int index] - { - get => myList[index]; - set => myList[index] = value; - } - - public int Count => myList.Count; - - public bool IsReadOnly => false; - - public void Insert(int index, ConfigurationManager item) - { - myList.Insert(index, item); - item.SetConfiguration((SimpleConfiguration)GetParentManager()); - } - - public void RemoveAt(int index) - { - - } - - public void Add(ConfigurationManager item) - { - item.SetConfiguration((SimpleConfiguration)GetParentManager()); - } - - public void Clear() - { - foreach (ConfigurationManager item in myList) - item.SetConfiguration(null); - myList.Clear(); - } - - public void CopyTo(ConfigurationManager[] array, int arrayIndex) - { - myList.CopyTo(array, arrayIndex); - } - - public int IndexOf(ConfigurationManager item) - { - return myList.IndexOf(item); - } - - public bool Contains(ConfigurationManager item) - { - return myList.Contains(item); - } - - public bool Remove(ConfigurationManager item) - { - item.SetConfiguration(null); - return myList.Remove(item); - } - - public IEnumerator GetEnumerator() - { - return (IEnumerator)IEnumerable_GetEnumerator(); - } - - private IEnumerator IEnumerable_GetEnumerator() - { - return myList.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() => IEnumerable_GetEnumerator(); + var args = new GetValueEventArgs(); + GettingParentManager?.Invoke(this, args); + return args.Value; } + + public ConfigurationManager this[int index] + { + get => myList[index]; + set => myList[index] = value; + } + + public int Count => myList.Count; + + public bool IsReadOnly => false; + + public void Insert(int index, ConfigurationManager item) + { + myList.Insert(index, item); + item.SetConfiguration((SimpleConfiguration)GetParentManager()); + } + + public void RemoveAt(int index) + { + + } + + public void Add(ConfigurationManager item) + { + item.SetConfiguration((SimpleConfiguration)GetParentManager()); + } + + public void Clear() + { + foreach (ConfigurationManager item in myList) + item.SetConfiguration(null); + myList.Clear(); + } + + public void CopyTo(ConfigurationManager[] array, int arrayIndex) + { + myList.CopyTo(array, arrayIndex); + } + + public int IndexOf(ConfigurationManager item) + { + return myList.IndexOf(item); + } + + public bool Contains(ConfigurationManager item) + { + return myList.Contains(item); + } + + public bool Remove(ConfigurationManager item) + { + item.SetConfiguration(null); + return myList.Remove(item); + } + + public IEnumerator GetEnumerator() + { + return (IEnumerator)IEnumerable_GetEnumerator(); + } + + private IEnumerator IEnumerable_GetEnumerator() + { + return myList.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() => IEnumerable_GetEnumerator(); } \ No newline at end of file diff --git a/Pilz.Configuration/ConfigurationSerializer.cs b/Pilz.Configuration/ConfigurationSerializer.cs index b1b7c4c..748e696 100644 --- a/Pilz.Configuration/ConfigurationSerializer.cs +++ b/Pilz.Configuration/ConfigurationSerializer.cs @@ -1,139 +1,138 @@ -using System.IO; -using Newtonsoft.Json; +using Newtonsoft.Json; using Pilz.GeneralEventArgs; +using System.IO; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public static class ConfigurationSerializer { - public static class ConfigurationSerializer + public static event GettingJsonSerializerEventHandler GettingJsonSerializer; + + public delegate void GettingJsonSerializerEventHandler(object instance, GetValueEventArgs e); + + private static JsonSerializer GetJsonSerializer(SimpleConfiguration instance) { - public static event GettingJsonSerializerEventHandler GettingJsonSerializer; + var args = new GetValueEventArgs(JsonSerializer.CreateDefault()); + GettingJsonSerializer?.Invoke(instance, args); + return args.Value; + } - public delegate void GettingJsonSerializerEventHandler(object instance, GetValueEventArgs e); + /// + /// Writes the given instance to a string and return it. + /// + /// The configuration instance that should be serialized. + /// The content of the configuration instance as string. + public static string WriteToString(SimpleConfiguration instance) + { + var tw = new StringWriter(); + GetJsonSerializer(instance).Serialize(tw, instance); + string txt = tw.ToString(); + tw.Close(); + return txt; + } - private static JsonSerializer GetJsonSerializer(SimpleConfiguration instance) - { - var args = new GetValueEventArgs(JsonSerializer.CreateDefault()); - GettingJsonSerializer?.Invoke(instance, args); - return args.Value; - } + /// + /// Write the given instance to a given stream. + /// + /// The configuration instance that should be serialized. + /// The stream where the content should be written to. + public static void WriteToStream(SimpleConfiguration instance, Stream stream) + { + var sr = new StreamWriter(stream); + sr.Write(WriteToString(instance)); + } - /// - /// Writes the given instance to a string and return it. - /// - /// The configuration instance that should be serialized. - /// The content of the configuration instance as string. - public static string WriteToString(SimpleConfiguration instance) - { - var tw = new StringWriter(); - GetJsonSerializer(instance).Serialize(tw, instance); - string txt = tw.ToString(); - tw.Close(); - return txt; - } + /// + /// Writes the given instance to the given filePath as text file. + /// + /// The configuration instance that should be serialized. + /// The file path where the content should be written to. The file will be created or overwritten. + public static void WriteToFile(SimpleConfiguration instance, string filePath) + { + var fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); + WriteToStream(instance, fs); + fs.Close(); + } - /// - /// Write the given instance to a given stream. - /// - /// The configuration instance that should be serialized. - /// The stream where the content should be written to. - public static void WriteToStream(SimpleConfiguration instance, Stream stream) - { - var sr = new StreamWriter(stream); - sr.Write(WriteToString(instance)); - } + /// + /// Reads a configuratin from the given string and returns an instance of it. + /// + /// The type of the configuration class to instance. + /// The content of the configuration as string. + /// + public static T ReadFromString(string content) where T : SimpleConfiguration + { + var sr = new StringReader(content); + T instance = (T)GetJsonSerializer(null).Deserialize(sr, typeof(T)); + sr.Close(); + return instance; + } - /// - /// Writes the given instance to the given filePath as text file. - /// - /// The configuration instance that should be serialized. - /// The file path where the content should be written to. The file will be created or overwritten. - public static void WriteToFile(SimpleConfiguration instance, string filePath) - { - var fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); - WriteToStream(instance, fs); - fs.Close(); - } + /// + /// Read a configuration from the given string and put them to the given instance. + /// + /// The instance to populate with the configuration. + /// The content of the configuration as string. + public static void ReadFromString(SimpleConfiguration instance, string content) + { + var sr = new StringReader(content); + GetJsonSerializer(null).Populate(sr, content); + sr.Close(); + } - /// - /// Reads a configuratin from the given string and returns an instance of it. - /// - /// The type of the configuration class to instance. - /// The content of the configuration as string. - /// - public static T ReadFromString(string content) where T : SimpleConfiguration - { - var sr = new StringReader(content); - T instance = (T)GetJsonSerializer(null).Deserialize(sr, typeof(T)); - sr.Close(); - return instance; - } + /// + /// Reads a configuratin from the given string and returns an instance of it. + /// + /// The type of the configuration class to instance. + /// The stream with the content of the configuration. + /// + public static T ReadFromStream(Stream stream) where T : SimpleConfiguration + { + return ReadFromString(GetContentOfStream(stream)); + } - /// - /// Read a configuration from the given string and put them to the given instance. - /// - /// The instance to populate with the configuration. - /// The content of the configuration as string. - public static void ReadFromString(SimpleConfiguration instance, string content) - { - var sr = new StringReader(content); - GetJsonSerializer(null).Populate(sr, content); - sr.Close(); - } + /// + /// Read a configuration from the given string and put them to the given instance. + /// + /// The instance to populate with the configuration. + /// The stream with the content of the configuration. + public static void ReadFromStream(SimpleConfiguration instance, Stream stream) + { + ReadFromString(instance, GetContentOfStream(stream)); + } - /// - /// Reads a configuratin from the given string and returns an instance of it. - /// - /// The type of the configuration class to instance. - /// The stream with the content of the configuration. - /// - public static T ReadFromStream(Stream stream) where T : SimpleConfiguration - { - return ReadFromString(GetContentOfStream(stream)); - } + /// + /// Reads a configuratin from the given string and returns an instance of it. + /// + /// The type of the configuration class to instance. + /// The path to the file with the content of the configuration. + /// + public static T ReadFromFile(string filePath) where T : SimpleConfiguration + { + return ReadFromString(GetContentOfFile(filePath)); + } - /// - /// Read a configuration from the given string and put them to the given instance. - /// - /// The instance to populate with the configuration. - /// The stream with the content of the configuration. - public static void ReadFromStream(SimpleConfiguration instance, Stream stream) - { - ReadFromString(instance, GetContentOfStream(stream)); - } + /// + /// Read a configuration from the given string and put them to the given instance. + /// + /// The instance to populate with the configuration. + /// The path to the file with the content of the configuration. + public static void ReadFromFile(SimpleConfiguration instance, string filePath) + { + ReadFromString(instance, GetContentOfFile(filePath)); + } - /// - /// Reads a configuratin from the given string and returns an instance of it. - /// - /// The type of the configuration class to instance. - /// The path to the file with the content of the configuration. - /// - public static T ReadFromFile(string filePath) where T : SimpleConfiguration - { - return ReadFromString(GetContentOfFile(filePath)); - } + private static string GetContentOfStream(Stream stream) + { + var sr = new StreamReader(stream); + return sr.ReadToEnd(); + } - /// - /// Read a configuration from the given string and put them to the given instance. - /// - /// The instance to populate with the configuration. - /// The path to the file with the content of the configuration. - public static void ReadFromFile(SimpleConfiguration instance, string filePath) - { - ReadFromString(instance, GetContentOfFile(filePath)); - } - - private static string GetContentOfStream(Stream stream) - { - var sr = new StreamReader(stream); - return sr.ReadToEnd(); - } - - private static string GetContentOfFile(string filePath) - { - var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); - string content = GetContentOfStream(fs); - fs.Close(); - return content; - } + private static string GetContentOfFile(string filePath) + { + var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); + string content = GetContentOfStream(fs); + fs.Close(); + return content; } } \ No newline at end of file diff --git a/Pilz.Configuration/IChildSettings.cs b/Pilz.Configuration/IChildSettings.cs index b4e7c23..7d4c3a3 100644 --- a/Pilz.Configuration/IChildSettings.cs +++ b/Pilz.Configuration/IChildSettings.cs @@ -1,7 +1,6 @@ -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public interface IChildSettings { - public interface IChildSettings - { - void Reset(); - } + void Reset(); } \ No newline at end of file diff --git a/Pilz.Configuration/ISettings.cs b/Pilz.Configuration/ISettings.cs index 2a17462..e84394f 100644 --- a/Pilz.Configuration/ISettings.cs +++ b/Pilz.Configuration/ISettings.cs @@ -1,11 +1,10 @@ using System.Collections.Generic; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public interface ISettings { - public interface ISettings - { - IReadOnlyCollection Childs { get; } - T Get() where T : IChildSettings, ISettingsIdentifier; - void Reset(); - } + IReadOnlyCollection Childs { get; } + T Get() where T : IChildSettings, ISettingsIdentifier; + void Reset(); } \ No newline at end of file diff --git a/Pilz.Configuration/ISettingsIdentifier.cs b/Pilz.Configuration/ISettingsIdentifier.cs index 1c1384d..2794f49 100644 --- a/Pilz.Configuration/ISettingsIdentifier.cs +++ b/Pilz.Configuration/ISettingsIdentifier.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Configuration; -namespace Pilz.Configuration +public interface ISettingsIdentifier { - public interface ISettingsIdentifier - { - static abstract string Identifier { get; } - } + static abstract string Identifier { get; } } diff --git a/Pilz.Configuration/ISettingsManager.cs b/Pilz.Configuration/ISettingsManager.cs index cc4591b..6acce0e 100644 --- a/Pilz.Configuration/ISettingsManager.cs +++ b/Pilz.Configuration/ISettingsManager.cs @@ -1,11 +1,10 @@  -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public interface ISettingsManager { - public interface ISettingsManager - { - ISettings Instance { get; } - void Save(); - void Load(); - void Reset(); - } + ISettings Instance { get; } + void Save(); + void Load(); + void Reset(); } \ No newline at end of file diff --git a/Pilz.Configuration/Settings.cs b/Pilz.Configuration/Settings.cs index bf193fe..ccc31fe 100644 --- a/Pilz.Configuration/Settings.cs +++ b/Pilz.Configuration/Settings.cs @@ -1,37 +1,35 @@ -using System; +using Newtonsoft.Json; +using System; using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public class Settings : ISettings { - public class Settings : ISettings + [JsonProperty(nameof(Settings))] + protected readonly Dictionary mySettings = []; + + [JsonIgnore] + public IReadOnlyCollection Childs => mySettings.Values; + + public T Get() where T : IChildSettings, ISettingsIdentifier { - [JsonProperty(nameof(Settings))] - protected readonly Dictionary mySettings = []; + if (mySettings.TryGetValue(T.Identifier, out IChildSettings valueExisting) && valueExisting is T settingsExisting) + return settingsExisting; - [JsonIgnore] - public IReadOnlyCollection Childs => mySettings.Values; - - public T Get() where T : IChildSettings, ISettingsIdentifier + if (Activator.CreateInstance() is T settingsNew) { - if (mySettings.TryGetValue(T.Identifier, out IChildSettings valueExisting) && valueExisting is T settingsExisting) - return settingsExisting; - - if (Activator.CreateInstance() is T settingsNew) - { - settingsNew.Reset(); - mySettings.Add(T.Identifier, settingsNew); - return settingsNew; - } - - return default; + settingsNew.Reset(); + mySettings.Add(T.Identifier, settingsNew); + return settingsNew; } - public void Reset() - { - foreach (var s in mySettings.Values) - s.Reset(); - } + return default; + } + + public void Reset() + { + foreach (var s in mySettings.Values) + s.Reset(); } } \ No newline at end of file diff --git a/Pilz.Configuration/SettingsManager.cs b/Pilz.Configuration/SettingsManager.cs index 1615b5b..b4e5f0b 100644 --- a/Pilz.Configuration/SettingsManager.cs +++ b/Pilz.Configuration/SettingsManager.cs @@ -1,142 +1,139 @@ -using System; -using System.Collections.Generic; +using Newtonsoft.Json; +using System; using System.IO; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public class SettingsManager : ISettingsManager { - public class SettingsManager : ISettingsManager + public event EventHandler AutoSavingSettings; + public event EventHandler SavingSettings; + public event EventHandler SavedSettings; + public event EventHandler OnSerializationError; + + protected ISettings defaultInstance = null; + protected bool enableAutoSave = false; + protected bool addedHandler = false; + + public string ConfigFilePath { get; set; } + + public ISettings Instance { - public event EventHandler AutoSavingSettings; - public event EventHandler SavingSettings; - public event EventHandler SavedSettings; - public event EventHandler OnSerializationError; - - protected ISettings defaultInstance = null; - protected bool enableAutoSave = false; - protected bool addedHandler = false; - - public string ConfigFilePath { get; set; } - - public ISettings Instance + get { - get - { - if (defaultInstance is null) - Load(); - return defaultInstance; - } + if (defaultInstance is null) + Load(); + return defaultInstance; } + } - public bool AutoSaveOnExit + public bool AutoSaveOnExit + { + get => enableAutoSave; + set { - get => enableAutoSave; - set + if (enableAutoSave != value) { - if (enableAutoSave != value) + enableAutoSave = value; + if (enableAutoSave) { - enableAutoSave = value; - if (enableAutoSave) - { - if (!addedHandler) - AddAutoSaveHandler(); - } - else - { - if (addedHandler) - RemoveAutoSaveHandler(); - } + if (!addedHandler) + AddAutoSaveHandler(); + } + else + { + if (addedHandler) + RemoveAutoSaveHandler(); } } } + } - public SettingsManager() + public SettingsManager() + { + } + + public SettingsManager(string fileName, bool autoSaveOnExit) : this() + { + ConfigFilePath = fileName; + AutoSaveOnExit = autoSaveOnExit; + } + + protected void AddAutoSaveHandler() + { + AppDomain.CurrentDomain.ProcessExit += AutoSaveSettingsOnExit; + addedHandler = true; + } + + protected void RemoveAutoSaveHandler() + { + AppDomain.CurrentDomain.ProcessExit -= AutoSaveSettingsOnExit; + addedHandler = false; + } + + private void AutoSaveSettingsOnExit(object sender, EventArgs e) + { + AutoSavingSettings?.Invoke(this, new EventArgs()); + Save(); + } + + public void Save() + { + if (!string.IsNullOrEmpty(ConfigFilePath) && defaultInstance is not null) + SaveInternal(); + } + + public void Load() + { + if (!string.IsNullOrEmpty(ConfigFilePath) && File.Exists(ConfigFilePath)) + LoadInternal(); + else + CreateNewInstance(); + } + + public void Reset() + { + Instance.Reset(); + } + + protected virtual void CreateNewInstance() + { + defaultInstance = new Settings(); + defaultInstance.Reset(); + } + + protected virtual void LoadInternal() + { + defaultInstance = JsonConvert.DeserializeObject(File.ReadAllText(ConfigFilePath), CreateJsonSerializerSettings()); + } + + protected virtual void SaveInternal() + { + SavingSettings?.Invoke(this, EventArgs.Empty); + File.WriteAllText(ConfigFilePath, JsonConvert.SerializeObject(defaultInstance, CreateJsonSerializerSettings())); + SavedSettings?.Invoke(this, EventArgs.Empty); + } + + protected virtual JsonSerializerSettings CreateJsonSerializerSettings() + { + return new JsonSerializerSettings() { - } + Formatting = Formatting.Indented, + TypeNameHandling = TypeNameHandling.Auto, + Error = JsonSerializer_OnError, + }; + } - public SettingsManager(string fileName, bool autoSaveOnExit) : this() - { - ConfigFilePath = fileName; - AutoSaveOnExit = autoSaveOnExit; - } + protected virtual void JsonSerializer_OnError(object sender, ErrorEventArgs e) + { + const string errorResolvingType = "Error resolving type specified in JSON"; - protected void AddAutoSaveHandler() - { - AppDomain.CurrentDomain.ProcessExit += AutoSaveSettingsOnExit; - addedHandler = true; - } + // Invoke event + OnSerializationError?.Invoke(sender, e); - protected void RemoveAutoSaveHandler() - { - AppDomain.CurrentDomain.ProcessExit -= AutoSaveSettingsOnExit; - addedHandler = false; - } - - private void AutoSaveSettingsOnExit(object sender, EventArgs e) - { - AutoSavingSettings?.Invoke(this, new EventArgs()); - Save(); - } - - public void Save() - { - if (!string.IsNullOrEmpty(ConfigFilePath) && defaultInstance is not null) - SaveInternal(); - } - - public void Load() - { - if (!string.IsNullOrEmpty(ConfigFilePath) && File.Exists(ConfigFilePath)) - LoadInternal(); - else - CreateNewInstance(); - } - - public void Reset() - { - Instance.Reset(); - } - - protected virtual void CreateNewInstance() - { - defaultInstance = new Settings(); - defaultInstance.Reset(); - } - - protected virtual void LoadInternal() - { - defaultInstance = JsonConvert.DeserializeObject(File.ReadAllText(ConfigFilePath), CreateJsonSerializerSettings()); - } - - protected virtual void SaveInternal() - { - SavingSettings?.Invoke(this, EventArgs.Empty); - File.WriteAllText(ConfigFilePath, JsonConvert.SerializeObject(defaultInstance, CreateJsonSerializerSettings())); - SavedSettings?.Invoke(this, EventArgs.Empty); - } - - protected virtual JsonSerializerSettings CreateJsonSerializerSettings() - { - return new JsonSerializerSettings() - { - Formatting = Formatting.Indented, - TypeNameHandling = TypeNameHandling.Auto, - Error = JsonSerializer_OnError, - }; - } - - protected virtual void JsonSerializer_OnError(object sender, ErrorEventArgs e) - { - const string errorResolvingType = "Error resolving type specified in JSON"; - - // Invoke event - OnSerializationError?.Invoke(sender, e); - - // Handle ourself - if (!e.ErrorContext.Handled && e.ErrorContext.Error is JsonSerializationException serializationException && serializationException.Message.StartsWith(errorResolvingType)) - e.ErrorContext.Handled = true; - } + // Handle ourself + if (!e.ErrorContext.Handled && e.ErrorContext.Error is JsonSerializationException serializationException && serializationException.Message.StartsWith(errorResolvingType)) + e.ErrorContext.Handled = true; } } \ No newline at end of file diff --git a/Pilz.Configuration/SimpleConfiguration.cs b/Pilz.Configuration/SimpleConfiguration.cs index 655e252..3aad7fa 100644 --- a/Pilz.Configuration/SimpleConfiguration.cs +++ b/Pilz.Configuration/SimpleConfiguration.cs @@ -1,110 +1,109 @@ -using System.IO; -using Newtonsoft.Json; +using Newtonsoft.Json; using Pilz.GeneralEventArgs; +using System.IO; -namespace Pilz.Configuration +namespace Pilz.Configuration; + +public class SimpleConfiguration { - public class SimpleConfiguration + [JsonIgnore] + public readonly ConfigurationManagerList Managers = new ConfigurationManagerList(); + + public SimpleConfiguration() { - [JsonIgnore] - public readonly ConfigurationManagerList Managers = new ConfigurationManagerList(); + Managers.GettingParentManager += Managers_GettingParentManager; + } - public SimpleConfiguration() - { - Managers.GettingParentManager += Managers_GettingParentManager; - } + private void Managers_GettingParentManager(object sender, GetValueEventArgs e) + { + if (ReferenceEquals(sender, Managers)) + e.Value = this; + } - private void Managers_GettingParentManager(object sender, GetValueEventArgs e) - { - if (ReferenceEquals(sender, Managers)) - e.Value = this; - } + /// + /// Writes this instance to a string and return it. + /// + /// The content of the configuration instance as string. + public string WriteToString() + { + return ConfigurationSerializer.WriteToString(this); + } - /// - /// Writes this instance to a string and return it. - /// - /// The content of the configuration instance as string. - public string WriteToString() - { - return ConfigurationSerializer.WriteToString(this); - } + /// + /// Write this instance to a given stream. + /// + /// The stream where the content should be written to. + public void WriteToStream(Stream stream) + { + ConfigurationSerializer.WriteToStream(this, stream); + } - /// - /// Write this instance to a given stream. - /// - /// The stream where the content should be written to. - public void WriteToStream(Stream stream) - { - ConfigurationSerializer.WriteToStream(this, stream); - } + /// + /// Writes this instance to the given filePath as text file. + /// + /// The file path where the content should be written to. The file will be created or overwritten. + public void WriteToFile(string filePath) + { + ConfigurationSerializer.WriteToFile(this, filePath); + } - /// - /// Writes this instance to the given filePath as text file. - /// - /// The file path where the content should be written to. The file will be created or overwritten. - public void WriteToFile(string filePath) - { - ConfigurationSerializer.WriteToFile(this, filePath); - } + /// + /// Reads a configuratin from the given string and returns an instance of it. + /// + /// The type of the configuration class to instance. + /// The content of the configuration as string. + /// + public static T ReadFromString(string content) where T : SimpleConfiguration + { + return ConfigurationSerializer.ReadFromString(content); + } - /// - /// Reads a configuratin from the given string and returns an instance of it. - /// - /// The type of the configuration class to instance. - /// The content of the configuration as string. - /// - public static T ReadFromString(string content) where T : SimpleConfiguration - { - return ConfigurationSerializer.ReadFromString(content); - } + /// + /// Read a configuration from the given string and put them to this instance. + /// + /// The content of the configuration as string. + public void ReadFromString(string content) + { + ConfigurationSerializer.ReadFromString(this, content); + } - /// - /// Read a configuration from the given string and put them to this instance. - /// - /// The content of the configuration as string. - public void ReadFromString(string content) - { - ConfigurationSerializer.ReadFromString(this, content); - } + /// + /// Reads a configuratin from the given string and returns an instance of it. + /// + /// The type of the configuration class to instance. + /// The stream with the content of the configuration. + /// + public static T ReadFromStream(Stream stream) where T : SimpleConfiguration + { + return ConfigurationSerializer.ReadFromStream(stream); + } - /// - /// Reads a configuratin from the given string and returns an instance of it. - /// - /// The type of the configuration class to instance. - /// The stream with the content of the configuration. - /// - public static T ReadFromStream(Stream stream) where T : SimpleConfiguration - { - return ConfigurationSerializer.ReadFromStream(stream); - } + /// + /// Read a configuration from the given string and put them to this instance. + /// + /// The stream with the content of the configuration. + public void ReadFromStream(Stream stream) + { + ConfigurationSerializer.ReadFromStream(this, stream); + } - /// - /// Read a configuration from the given string and put them to this instance. - /// - /// The stream with the content of the configuration. - public void ReadFromStream(Stream stream) - { - ConfigurationSerializer.ReadFromStream(this, stream); - } + /// + /// Reads a configuratin from the given string and returns an instance of it. + /// + /// The type of the configuration class to instance. + /// The path to the file with the content of the configuration. + /// + public static T ReadFromFile(string filePath) where T : SimpleConfiguration + { + return ConfigurationSerializer.ReadFromFile(filePath); + } - /// - /// Reads a configuratin from the given string and returns an instance of it. - /// - /// The type of the configuration class to instance. - /// The path to the file with the content of the configuration. - /// - public static T ReadFromFile(string filePath) where T : SimpleConfiguration - { - return ConfigurationSerializer.ReadFromFile(filePath); - } - - /// - /// Read a configuration from the given string and put them to this instance. - /// - /// The path to the file with the content of the configuration. - public void ReadFromFile(string filePath) - { - ConfigurationSerializer.ReadFromFile(this, filePath); - } + /// + /// Read a configuration from the given string and put them to this instance. + /// + /// The path to the file with the content of the configuration. + public void ReadFromFile(string filePath) + { + ConfigurationSerializer.ReadFromFile(this, filePath); } } \ No newline at end of file diff --git a/Pilz.Cryptography/Helpers.cs b/Pilz.Cryptography/Helpers.cs index 55eeb26..f37e252 100644 --- a/Pilz.Cryptography/Helpers.cs +++ b/Pilz.Cryptography/Helpers.cs @@ -1,55 +1,51 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; using System.Management; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; -namespace Pilz.Cryptography +namespace Pilz.Cryptography; + +[EditorBrowsable(EditorBrowsableState.Never)] +public static class Helpers { - [EditorBrowsable(EditorBrowsableState.Never)] - public static class Helpers + private static string clientSecret = null; + + public static string CalculateClientSecret() { - private static string clientSecret = null; - - public static string CalculateClientSecret() + // Try getting serial number of C drive + if (clientSecret == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - // Try getting serial number of C drive - if (clientSecret == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + ManagementObjectSearcher searcher = new("SELECT * FROM Win32_PhysicalMedia"); + string sn = null; + + foreach (var entry in searcher.Get()) { - ManagementObjectSearcher searcher = new("SELECT * FROM Win32_PhysicalMedia"); - string sn = null; - - foreach (var entry in searcher.Get()) - { - if (entry is ManagementObject wmi_HD && string.IsNullOrEmpty(sn) && wmi_HD["SerialNumber"] != null) - sn = wmi_HD["SerialNumber"].ToString()?.Trim(); - } - - clientSecret = sn; + if (entry is ManagementObject wmi_HD && string.IsNullOrEmpty(sn) && wmi_HD["SerialNumber"] != null) + sn = wmi_HD["SerialNumber"].ToString()?.Trim(); } - // Fallback to Mashine name - clientSecret ??= Environment.MachineName; - - return clientSecret; + clientSecret = sn; } - public static string GenerateUniquieID(string var) - { - var sn = CalculateClientSecret(); - var dateTime = DateTime.UtcNow.ToString("yyyyMMddHHmmssfffffff"); - var type = typeof(T).ToString(); - var together = sn + dateTime + type + var; + // Fallback to Mashine name + clientSecret ??= Environment.MachineName; - var md5 = MD5.Create(); - var hash = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(together))).Replace("-", string.Empty); - md5.Dispose(); + return clientSecret; + } - return hash; - } + public static string GenerateUniquieID(string var) + { + var sn = CalculateClientSecret(); + var dateTime = DateTime.UtcNow.ToString("yyyyMMddHHmmssfffffff"); + var type = typeof(T).ToString(); + var together = sn + dateTime + type + var; + + var md5 = MD5.Create(); + var hash = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(together))).Replace("-", string.Empty); + md5.Dispose(); + + return hash; } } diff --git a/Pilz.Cryptography/ICrypter.cs b/Pilz.Cryptography/ICrypter.cs index f126915..1d03d98 100644 --- a/Pilz.Cryptography/ICrypter.cs +++ b/Pilz.Cryptography/ICrypter.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Cryptography; -namespace Pilz.Cryptography +public interface ICrypter { - public interface ICrypter - { - string Encrypt(string plainValue); - string Decrypt(string encryptedValue); - } + string Encrypt(string plainValue); + string Decrypt(string encryptedValue); } diff --git a/Pilz.Cryptography/IUniquieID.cs b/Pilz.Cryptography/IUniquieID.cs index b5ffa1d..ebc4e40 100644 --- a/Pilz.Cryptography/IUniquieID.cs +++ b/Pilz.Cryptography/IUniquieID.cs @@ -1,18 +1,14 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Text; -namespace Pilz.Cryptography +namespace Pilz.Cryptography; + +[JsonConverter(typeof(Json.Converters.UniquieIDStringJsonConverter))] +public interface IUniquieID { - [JsonConverter(typeof(Json.Converters.UniquieIDStringJsonConverter))] - public interface IUniquieID - { - bool HasID { get; } - string ID { get; } + bool HasID { get; } + string ID { get; } - void GenerateIfNull(); - void Generate(); - bool Equals(object obj); - } + void GenerateIfNull(); + void Generate(); + bool Equals(object obj); } diff --git a/Pilz.Cryptography/IUniquieIDHost.cs b/Pilz.Cryptography/IUniquieIDHost.cs index d391edb..4eb1cf0 100644 --- a/Pilz.Cryptography/IUniquieIDHost.cs +++ b/Pilz.Cryptography/IUniquieIDHost.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace Pilz.Cryptography; -namespace Pilz.Cryptography +/// +/// Can be implemented on objects that provides an UniquieID. +/// +public interface IUniquieIDHost { - /// - /// Can be implemented on objects that provides an UniquieID. - /// - public interface IUniquieIDHost - { - UniquieID ID { get; } - } + UniquieID ID { get; } } diff --git a/Pilz.Cryptography/Json.Converters/UniquieIDStringJsonConverter.cs b/Pilz.Cryptography/Json.Converters/UniquieIDStringJsonConverter.cs index 0afabc9..8266bbd 100644 --- a/Pilz.Cryptography/Json.Converters/UniquieIDStringJsonConverter.cs +++ b/Pilz.Cryptography/Json.Converters/UniquieIDStringJsonConverter.cs @@ -1,38 +1,35 @@ using Newtonsoft.Json; using Pilz.Cryptography; using System; -using System.Collections.Generic; -using System.Text; -namespace Pilz.Json.Converters +namespace Pilz.Json.Converters; + +public class UniquieIDStringJsonConverter : JsonConverter { - public class UniquieIDStringJsonConverter : JsonConverter + public static bool EnableCheckForDepricatedTypes { get; set; } = true; + + public override bool CanConvert(Type objectType) { - public static bool EnableCheckForDepricatedTypes { get; set; } = true; + return typeof(IUniquieID).IsAssignableFrom(objectType); + } - public override bool CanConvert(Type objectType) - { - return typeof(IUniquieID).IsAssignableFrom(objectType); - } + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + var idString = serializer.Deserialize(reader); + UniquieID id; - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - var idString = serializer.Deserialize(reader); - UniquieID id; + if (existingValue is UniquieID existingID && (!EnableCheckForDepricatedTypes || existingID.GetType() == typeof(UniquieID))) + id = existingID; + else + id = new UniquieID(); - if (existingValue is UniquieID existingID && (!EnableCheckForDepricatedTypes || existingID.GetType() == typeof(UniquieID))) - id = existingID; - else - id = new UniquieID(); + id.ID = idString; - id.ID = idString; + return id; + } - return id; - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - serializer.Serialize(writer, ((UniquieID)value).ID); - } + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + serializer.Serialize(writer, ((UniquieID)value).ID); } } diff --git a/Pilz.Cryptography/Properties/AssemblyInfo.cs b/Pilz.Cryptography/Properties/AssemblyInfo.cs index 23e20a3..0cd8a25 100644 --- a/Pilz.Cryptography/Properties/AssemblyInfo.cs +++ b/Pilz.Cryptography/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von diff --git a/Pilz.Cryptography/SecureString.cs b/Pilz.Cryptography/SecureString.cs index 56b3a65..88f4e8f 100644 --- a/Pilz.Cryptography/SecureString.cs +++ b/Pilz.Cryptography/SecureString.cs @@ -1,78 +1,73 @@ using Newtonsoft.Json; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Cryptography +namespace Pilz.Cryptography; + +[JsonConverter(typeof(Json.Converters.SecureStringJsonConverter))] +public class SecureString { - [JsonConverter(typeof(Json.Converters.SecureStringJsonConverter))] - public class SecureString + public static ICrypter DefaultCrypter { get; set; } + public ICrypter Crypter { get; set; } + public string EncryptedValue { get; set; } + public string Value { - public static ICrypter DefaultCrypter { get; set; } - public ICrypter Crypter { get; set; } - public string EncryptedValue { get; set; } - public string Value - { - get => GetCrypter()?.Decrypt(EncryptedValue); - set => EncryptedValue = GetCrypter().Encrypt(value); - } - - [JsonConstructor] - private SecureString(JsonConstructorAttribute dummyAttribute) - { - } - - public SecureString() : - this(string.Empty, true) - { - } - - public SecureString(string value, bool isEncrypted) : - this(value, isEncrypted, null) - { - } - - public SecureString(string value, bool isEncrypted, ICrypter crypter) - { - Crypter = crypter; - - if (isEncrypted) - EncryptedValue = value; - else - Value = value; - } - - private ICrypter GetCrypter() - { - if (Crypter == null) - { - if (DefaultCrypter == null) - DefaultCrypter = new SimpleStringCrypter(string.Empty); - Crypter = DefaultCrypter; - } - return Crypter; - } - - public override string ToString() => Value; - - public override bool Equals(object obj) - { - var @string = obj as SecureString; - return @string != null && - EncryptedValue == @string.EncryptedValue; - } - - public override int GetHashCode() - { - return -2303024 + EqualityComparer.Default.GetHashCode(EncryptedValue); - } - - public static implicit operator string(SecureString value) => value?.Value; - public static implicit operator SecureString(string value) => new SecureString(value, false); - - public static bool operator ==(SecureString left, SecureString right) => left?.EncryptedValue == right?.EncryptedValue; - public static bool operator !=(SecureString left, SecureString right) => left?.EncryptedValue != right?.EncryptedValue; + get => GetCrypter()?.Decrypt(EncryptedValue); + set => EncryptedValue = GetCrypter().Encrypt(value); } + + [JsonConstructor] + private SecureString(JsonConstructorAttribute dummyAttribute) + { + } + + public SecureString() : + this(string.Empty, true) + { + } + + public SecureString(string value, bool isEncrypted) : + this(value, isEncrypted, null) + { + } + + public SecureString(string value, bool isEncrypted, ICrypter crypter) + { + Crypter = crypter; + + if (isEncrypted) + EncryptedValue = value; + else + Value = value; + } + + private ICrypter GetCrypter() + { + if (Crypter == null) + { + if (DefaultCrypter == null) + DefaultCrypter = new SimpleStringCrypter(string.Empty); + Crypter = DefaultCrypter; + } + return Crypter; + } + + public override string ToString() => Value; + + public override bool Equals(object obj) + { + var @string = obj as SecureString; + return @string != null && + EncryptedValue == @string.EncryptedValue; + } + + public override int GetHashCode() + { + return -2303024 + EqualityComparer.Default.GetHashCode(EncryptedValue); + } + + public static implicit operator string(SecureString value) => value?.Value; + public static implicit operator SecureString(string value) => new SecureString(value, false); + + public static bool operator ==(SecureString left, SecureString right) => left?.EncryptedValue == right?.EncryptedValue; + public static bool operator !=(SecureString left, SecureString right) => left?.EncryptedValue != right?.EncryptedValue; } diff --git a/Pilz.Cryptography/SecureStringJsonConverter.cs b/Pilz.Cryptography/SecureStringJsonConverter.cs index 3d4a2ab..089a4ba 100644 --- a/Pilz.Cryptography/SecureStringJsonConverter.cs +++ b/Pilz.Cryptography/SecureStringJsonConverter.cs @@ -1,41 +1,34 @@ using Newtonsoft.Json; using Pilz.Cryptography; using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Json.Converters +namespace Pilz.Json.Converters; + +public class SecureStringJsonConverter : JsonConverter { - public class SecureStringJsonConverter : JsonConverter + public override bool CanConvert(Type objectType) { - public override bool CanConvert(Type objectType) + return typeof(SecureString).IsAssignableFrom(objectType); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + var idString = serializer.Deserialize(reader); + SecureString id; + + if (existingValue is SecureString) { - return typeof(SecureString).IsAssignableFrom(objectType); + id = (SecureString)existingValue; + id.EncryptedValue = idString; } + else + id = new SecureString(idString, true); - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - var idString = serializer.Deserialize(reader); - SecureString id; + return id; + } - if (existingValue is SecureString) - { - id = (SecureString)existingValue; - id.EncryptedValue = idString; - } - else - id = new SecureString(idString, true); - - return id; - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - serializer.Serialize(writer, ((SecureString)value).EncryptedValue); - } + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + serializer.Serialize(writer, ((SecureString)value).EncryptedValue); } } diff --git a/Pilz.Cryptography/SimpleStringCrypter.cs b/Pilz.Cryptography/SimpleStringCrypter.cs index 3b08c9e..b4a4203 100644 --- a/Pilz.Cryptography/SimpleStringCrypter.cs +++ b/Pilz.Cryptography/SimpleStringCrypter.cs @@ -1,80 +1,91 @@ using System; -using System.Collections.Generic; +using System.IO; + +/* Nicht gemergte Änderung aus Projekt "Pilz.Cryptography (net6.0)" +Vor: using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; using System.IO; +Nach: +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +*/ +using System.Security.Cryptography; +using System.Text; -namespace Pilz.Cryptography +namespace Pilz.Cryptography; + +public class SimpleStringCrypter : ICrypter { - public class SimpleStringCrypter : ICrypter + private readonly TripleDES TripleDes; + public Encoding TextEncoding { get; private set; } = Encoding.Default; + + public SimpleStringCrypter() : this(string.Empty) { - private readonly TripleDES TripleDes; - public Encoding TextEncoding { get; private set; } = Encoding.Default; + } - public SimpleStringCrypter() : this(string.Empty) - { - } + public SimpleStringCrypter(string key) : this(key, Encoding.Default) + { + } - public SimpleStringCrypter(string key) : this(key, Encoding.Default) - { - } + public SimpleStringCrypter(string key, Encoding textEncoding) + { + TextEncoding = textEncoding; + TripleDes = TripleDES.Create(); + TripleDes.Key = TruncateHash(key, TripleDes.KeySize / 8); + TripleDes.IV = TruncateHash(string.Empty, TripleDes.BlockSize / 8); + } - public SimpleStringCrypter(string key, Encoding textEncoding) - { - TextEncoding = textEncoding; - TripleDes = TripleDES.Create(); - TripleDes.Key = TruncateHash(key,TripleDes.KeySize / 8); - TripleDes.IV = TruncateHash(string.Empty, TripleDes.BlockSize / 8); - } + private byte[] TruncateHash(string key, int length) + { + SHA1 sha1CryptoServiceProvider = SHA1.Create(); + var bytes = TextEncoding.GetBytes(key); + var array = sha1CryptoServiceProvider.ComputeHash(bytes); - private byte[] TruncateHash(string key, int length) - { - SHA1 sha1CryptoServiceProvider = SHA1.Create(); - var bytes = TextEncoding.GetBytes(key); - var array = sha1CryptoServiceProvider.ComputeHash(bytes); + var output = new byte[length]; + var lowerLength = Math.Min(array.Length, output.Length); - var output = new byte[length]; - var lowerLength = Math.Min(array.Length, output.Length); - - for (int i = 0; i < lowerLength; i++) - output[i] = array[i]; + for (int i = 0; i < lowerLength; i++) + output[i] = array[i]; - return output; - } + return output; + } - private string EncryptData(string plaintext) - { - var bytes = TextEncoding.GetBytes(plaintext); - using var memoryStream = new MemoryStream(); - using var cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateEncryptor(), CryptoStreamMode.Write); - cryptoStream.Write(bytes, 0, bytes.Length); - cryptoStream.FlushFinalBlock(); - return Convert.ToBase64String(memoryStream.ToArray()); - } + private string EncryptData(string plaintext) + { + var bytes = TextEncoding.GetBytes(plaintext); + using var memoryStream = new MemoryStream(); + using var cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(bytes, 0, bytes.Length); + cryptoStream.FlushFinalBlock(); + return Convert.ToBase64String(memoryStream.ToArray()); + } - private string DecryptData(string encryptedtext) - { - var array = Convert.FromBase64String(encryptedtext); - using var memoryStream = new MemoryStream(); - using var cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateDecryptor(), CryptoStreamMode.Write); - cryptoStream.Write(array, 0, array.Length); - cryptoStream.FlushFinalBlock(); - return TextEncoding.GetString(memoryStream.ToArray()); - } + private string DecryptData(string encryptedtext) + { + var array = Convert.FromBase64String(encryptedtext); + using var memoryStream = new MemoryStream(); + using var cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write(array, 0, array.Length); + cryptoStream.FlushFinalBlock(); + return TextEncoding.GetString(memoryStream.ToArray()); + } - public string Encrypt(string plainValue) - { - return EncryptData(plainValue ?? string.Empty); - } + public string Encrypt(string plainValue) + { + return EncryptData(plainValue ?? string.Empty); + } - public string Decrypt(string encryptedValue) - { - if (string.IsNullOrEmpty(encryptedValue)) - return string.Empty; - else - return DecryptData(encryptedValue); - } + public string Decrypt(string encryptedValue) + { + if (string.IsNullOrEmpty(encryptedValue)) + return string.Empty; + else + return DecryptData(encryptedValue); } } diff --git a/Pilz.Cryptography/UniquieID.cs b/Pilz.Cryptography/UniquieID.cs index 6cbb0c7..2f03a02 100644 --- a/Pilz.Cryptography/UniquieID.cs +++ b/Pilz.Cryptography/UniquieID.cs @@ -1,135 +1,130 @@ using Newtonsoft.Json; using System; using System.Collections.Generic; -using System.Management; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; -namespace Pilz.Cryptography +namespace Pilz.Cryptography; + +[JsonConverter(typeof(Json.Converters.UniquieIDStringJsonConverter))] +public class UniquieID : IUniquieID { - [JsonConverter(typeof(Json.Converters.UniquieIDStringJsonConverter))] - public class UniquieID : IUniquieID + protected static ulong currentSimpleID = 0; + + [JsonProperty(nameof(ID))] + protected string _iD; + + [JsonIgnore] + public virtual bool SimpleMode { get; } + + [JsonIgnore] + public virtual bool GenerateOnGet { get; } + + [JsonIgnore] + public virtual bool HasID => !string.IsNullOrEmpty(_iD); + + [JsonIgnore] + public virtual string ID { - protected static ulong currentSimpleID = 0; - - [JsonProperty(nameof(ID))] - protected string _iD; - - [JsonIgnore] - public virtual bool SimpleMode { get; } - - [JsonIgnore] - public virtual bool GenerateOnGet { get; } - - [JsonIgnore] - public virtual bool HasID => !string.IsNullOrEmpty(_iD); - - [JsonIgnore] - public virtual string ID + get { - get - { - if (GenerateOnGet) - GenerateIfNull(); - return _iD; - } - internal set - => _iD = value; - } - - public UniquieID() : this(UniquieIDGenerationMode.None) - { - } - - public UniquieID(UniquieIDGenerationMode mode) : this(mode, false) - { - } - - public UniquieID(UniquieIDGenerationMode mode, bool simpleMode) - { - SimpleMode = simpleMode; - - if (mode == UniquieIDGenerationMode.GenerateOnInit) + if (GenerateOnGet) GenerateIfNull(); - else if (mode == UniquieIDGenerationMode.GenerateOnGet) - GenerateOnGet = true; + return _iD; } - - [Obsolete] - public UniquieID(bool autoGenerate) : this(autoGenerate ? UniquieIDGenerationMode.GenerateOnInit : UniquieIDGenerationMode.None) - { - } - - public virtual void Generate() - { - if (SimpleMode) - ID = GenerateSimple(); - else - ID = GenerateDefault(); - } - - protected virtual string GenerateSimple() - { - return new Random().Next().ToString() + DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + currentSimpleID++.ToString(); - } - - protected virtual string GenerateDefault() - { - return Helpers.GenerateUniquieID(currentSimpleID++.ToString()); - } - - public virtual void GenerateIfNull() - { - if (!HasID) Generate(); - } - - public override string ToString() - { - return ID; - } - - public override int GetHashCode() - { - return -1430039477 + EqualityComparer.Default.GetHashCode(_iD); - } - - public override bool Equals(object obj) - { - if (obj is UniquieID iD) - { - if (ReferenceEquals(obj, iD)) - return true; - else - { - var leftHasID = iD.HasID; - var rightHasID = HasID; - - if (!leftHasID && iD.GenerateOnGet) - { - iD.Generate(); - leftHasID = iD.HasID; - } - - if (!rightHasID && GenerateOnGet) - { - Generate(); - rightHasID = HasID; - } - - if (leftHasID && rightHasID) - return _iD.Equals(iD._iD); - } - } - - return base.Equals(obj); - } - - public static implicit operator string(UniquieID id) => id.ID; - public static implicit operator UniquieID(string id) => new UniquieID() { ID = id }; - public static implicit operator UniquieID(int id) => new UniquieID() { ID = Convert.ToString(id) }; - - public static bool operator ==(UniquieID left, UniquieID right) => left.ID.Equals(right.ID); - public static bool operator !=(UniquieID left, UniquieID right) => !left.ID.Equals(right.ID); + internal set + => _iD = value; } + + public UniquieID() : this(UniquieIDGenerationMode.None) + { + } + + public UniquieID(UniquieIDGenerationMode mode) : this(mode, false) + { + } + + public UniquieID(UniquieIDGenerationMode mode, bool simpleMode) + { + SimpleMode = simpleMode; + + if (mode == UniquieIDGenerationMode.GenerateOnInit) + GenerateIfNull(); + else if (mode == UniquieIDGenerationMode.GenerateOnGet) + GenerateOnGet = true; + } + + [Obsolete] + public UniquieID(bool autoGenerate) : this(autoGenerate ? UniquieIDGenerationMode.GenerateOnInit : UniquieIDGenerationMode.None) + { + } + + public virtual void Generate() + { + if (SimpleMode) + ID = GenerateSimple(); + else + ID = GenerateDefault(); + } + + protected virtual string GenerateSimple() + { + return new Random().Next().ToString() + DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + currentSimpleID++.ToString(); + } + + protected virtual string GenerateDefault() + { + return Helpers.GenerateUniquieID(currentSimpleID++.ToString()); + } + + public virtual void GenerateIfNull() + { + if (!HasID) Generate(); + } + + public override string ToString() + { + return ID; + } + + public override int GetHashCode() + { + return -1430039477 + EqualityComparer.Default.GetHashCode(_iD); + } + + public override bool Equals(object obj) + { + if (obj is UniquieID iD) + { + if (ReferenceEquals(obj, iD)) + return true; + else + { + var leftHasID = iD.HasID; + var rightHasID = HasID; + + if (!leftHasID && iD.GenerateOnGet) + { + iD.Generate(); + leftHasID = iD.HasID; + } + + if (!rightHasID && GenerateOnGet) + { + Generate(); + rightHasID = HasID; + } + + if (leftHasID && rightHasID) + return _iD.Equals(iD._iD); + } + } + + return base.Equals(obj); + } + + public static implicit operator string(UniquieID id) => id.ID; + public static implicit operator UniquieID(string id) => new UniquieID() { ID = id }; + public static implicit operator UniquieID(int id) => new UniquieID() { ID = Convert.ToString(id) }; + + public static bool operator ==(UniquieID left, UniquieID right) => left.ID.Equals(right.ID); + public static bool operator !=(UniquieID left, UniquieID right) => !left.ID.Equals(right.ID); } diff --git a/Pilz.Cryptography/UniquieIDGenerationMode.cs b/Pilz.Cryptography/UniquieIDGenerationMode.cs index d7f0c34..7a93c2a 100644 --- a/Pilz.Cryptography/UniquieIDGenerationMode.cs +++ b/Pilz.Cryptography/UniquieIDGenerationMode.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace Pilz.Cryptography; -namespace Pilz.Cryptography +public enum UniquieIDGenerationMode { - public enum UniquieIDGenerationMode - { - None, - GenerateOnGet, - GenerateOnInit - } + None, + GenerateOnGet, + GenerateOnInit } diff --git a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Camera/Camera.vb b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Camera/Camera.vb index 8d56858..e87f868 100644 --- a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Camera/Camera.vb +++ b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Camera/Camera.vb @@ -1,6 +1,5 @@ Imports System.Windows.Forms -Imports OpenTK Imports OpenTK.Mathematics Namespace CameraN diff --git a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Preview/ModelPreview.vb b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Preview/ModelPreview.vb index 1558dbf..c07dad3 100644 --- a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Preview/ModelPreview.vb +++ b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Preview/ModelPreview.vb @@ -1,16 +1,32 @@ Imports System.Drawing + +' Nicht gemergte Änderung aus Projekt "Pilz.Drawing.Drawing3D.OpenGLFactory (net6.0-windows)" +' Vor: +' Imports System.Windows.Forms +' Imports Pilz.Drawing.Drawing3D.OpenGLFactory.CameraN +' Nach: +' Imports System.Windows.Forms +' +' Imports OpenTK +' Imports OpenTK.Graphics.OpenGL +' Imports OpenTK.Mathematics +' Imports OpenTK.WinForms +' +' Imports Pilz.Drawing.Drawing3D.OpenGLFactory.CameraN Imports System.Windows.Forms -Imports Pilz.Drawing.Drawing3D.OpenGLFactory.CameraN -Imports Pilz.Drawing.Drawing3D.OpenGLFactory.RenderingN -Imports OpenTK + Imports OpenTK.Graphics.OpenGL -Imports Pilz.S3DFileParser -Imports Point = System.Drawing.Point -Imports Color = System.Drawing.Color Imports OpenTK.Mathematics Imports OpenTK.WinForms + +Imports Pilz.Drawing.Drawing3D.OpenGLFactory.CameraN +Imports Pilz.Drawing.Drawing3D.OpenGLFactory.RenderingN +Imports Pilz.S3DFileParser Imports Pilz.Win32.Mapped +Imports Color = System.Drawing.Color +Imports Point = System.Drawing.Point + Namespace PreviewN Public Class ModelPreview diff --git a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/BoundingBox.vb b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/BoundingBox.vb index edbd8d4..708afe6 100644 --- a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/BoundingBox.vb +++ b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/BoundingBox.vb @@ -1,5 +1,14 @@ -Imports System.Drawing -Imports OpenTK + +' Nicht gemergte Änderung aus Projekt "Pilz.Drawing.Drawing3D.OpenGLFactory (net6.0-windows)" +' Vor: +' Imports System.Drawing +' Imports OpenTK +' Nach: +' Imports System.Drawing +' +' Imports OpenTK +Imports System.Drawing + Imports OpenTK.Graphics.OpenGL Namespace RenderingN diff --git a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/ContentPipe.vb b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/ContentPipe.vb index fa197ef..0fe7ef9 100644 --- a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/ContentPipe.vb +++ b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/ContentPipe.vb @@ -1,8 +1,18 @@ -Imports System -Imports OpenTK -Imports OpenTK.Graphics.OpenGL -Imports System.Drawing +' Nicht gemergte Änderung aus Projekt "Pilz.Drawing.Drawing3D.OpenGLFactory (net6.0-windows)" +' Vor: +' Imports OpenTK +' Imports OpenTK.Graphics.OpenGL +' Imports System.Drawing +' Nach: +' Imports System.Drawing +' Imports System.Drawing.Imaging +' +' Imports OpenTK +.Drawing Imports System.Drawing.Imaging + +Imports OpenTK.Graphics.OpenGL + Imports Bitmap = System.Drawing.Bitmap Namespace RenderingN diff --git a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/Renderer.vb b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/Renderer.vb index db4a921..7adba81 100644 --- a/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/Renderer.vb +++ b/Pilz.Drawing.Drawing3D.OpenGLRenderer/Rendering/Renderer.vb @@ -1,9 +1,4 @@ -Imports System.Drawing -Imports System.Threading -Imports System.Windows.Forms - -Imports OpenTK -Imports OpenTK.Graphics.OpenGL +Imports OpenTK.Graphics.OpenGL Imports OpenTK.Mathematics Imports Pilz.S3DFileParser diff --git a/Pilz.Drawing/HelpfulDrawingFunctions.vb b/Pilz.Drawing/HelpfulDrawingFunctions.vb index 5fb2c28..aedafa4 100644 --- a/Pilz.Drawing/HelpfulDrawingFunctions.vb +++ b/Pilz.Drawing/HelpfulDrawingFunctions.vb @@ -1,5 +1,4 @@ Imports System.Drawing -Imports System.Drawing.Drawing2D Public Module HelpfulDrawingFunctions diff --git a/Pilz.Gaming.Minecraft/Utils.cs b/Pilz.Gaming.Minecraft/Utils.cs index e81dcd4..c3addd1 100644 --- a/Pilz.Gaming.Minecraft/Utils.cs +++ b/Pilz.Gaming.Minecraft/Utils.cs @@ -1,43 +1,42 @@ using System.Security.Cryptography; using System.Text; -namespace Pilz.Gaming.Minecraft +namespace Pilz.Gaming.Minecraft; + +public static class Utils { - public static class Utils + public static string GetUUID(string value) { - public static string GetUUID(string value) - { - using var md5 = MD5.Create(); + using var md5 = MD5.Create(); - //extracted from the java code: - //new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name)); - byte[] data = md5.ComputeHash(Encoding.ASCII.GetBytes(value)); - //set the version to 3 -> Name based md5 hash - data[6] = Convert.ToByte(data[6] & 0x0f | 0x30); - //IETF variant - data[8] = Convert.ToByte(data[8] & 0x3f | 0x80); + //extracted from the java code: + //new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name)); + byte[] data = md5.ComputeHash(Encoding.ASCII.GetBytes(value)); + //set the version to 3 -> Name based md5 hash + data[6] = Convert.ToByte(data[6] & 0x0f | 0x30); + //IETF variant + data[8] = Convert.ToByte(data[8] & 0x3f | 0x80); - //example: 069a79f4-44e9-4726-a5be-fca90e38aaf5 - var striped = Convert.ToHexString(data); - var components = new string[] { - striped[..].Remove(8), - striped[8..].Remove(4), - striped[12..].Remove(4), - striped[16..].Remove(4), - striped[20..] - }; + //example: 069a79f4-44e9-4726-a5be-fca90e38aaf5 + var striped = Convert.ToHexString(data); + var components = new string[] { + striped[..].Remove(8), + striped[8..].Remove(4), + striped[12..].Remove(4), + striped[16..].Remove(4), + striped[20..] + }; - return string.Join('-', components).ToLower(); - } + return string.Join('-', components).ToLower(); + } - public static string GetPlayerUUID(string username, bool offlineMode) - { - using var md5 = MD5.Create(); + public static string GetPlayerUUID(string username, bool offlineMode) + { + using var md5 = MD5.Create(); - if (!offlineMode) - throw new NotSupportedException("Getting player's online UUID via the Mojang API is not supported at this time."); + if (!offlineMode) + throw new NotSupportedException("Getting player's online UUID via the Mojang API is not supported at this time."); - return GetUUID("OfflinePlayer:" + username); - } + return GetUUID("OfflinePlayer:" + username); } } diff --git a/Pilz.IO/EmbeddedFilesContainer.cs b/Pilz.IO/EmbeddedFilesContainer.cs index f10d0ce..424680e 100644 --- a/Pilz.IO/EmbeddedFilesContainer.cs +++ b/Pilz.IO/EmbeddedFilesContainer.cs @@ -3,172 +3,169 @@ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; -using System.Linq; -using System.Text; using System.Threading.Tasks; -namespace Pilz.IO +namespace Pilz.IO; + +public class EmbeddedFilesContainer { - public class EmbeddedFilesContainer + [JsonProperty("CompressedFiles")] + private readonly Dictionary compressedFiles = new Dictionary(); + + /// + /// Returns the names of all embedded files. + /// + [JsonIgnore] + public IEnumerable AllFileNames { - [JsonProperty("CompressedFiles")] - private readonly Dictionary compressedFiles = new Dictionary(); + get => compressedFiles.Keys; + } - /// - /// Returns the names of all embedded files. - /// - [JsonIgnore] - public IEnumerable AllFileNames - { - get => compressedFiles.Keys; - } + /// + /// Embeds a file to this container. + /// + /// The name how it should be called in this container. + /// The file path to the file that should be embedded. + /// Returns a that defines if the file as been embedded successfully. + public Task AddFileAsync(string fileName, string filePath) + { + return Task.Run(() => AddFile(fileName, filePath)); + } - /// - /// Embeds a file to this container. - /// - /// The name how it should be called in this container. - /// The file path to the file that should be embedded. - /// Returns a that defines if the file as been embedded successfully. - public Task AddFileAsync(string fileName, string filePath) - { - return Task.Run(() => AddFile(fileName, filePath)); - } - - /// - /// Embeds a file to this container. - /// - /// The name how it should be called in this container. - /// The file path to the file that should be embedded. - /// Returns a that defines if the file as been embedded successfully. - public bool AddFile(string fileName, string filePath) - { - bool success; - FileStream fs = null; - MemoryStream compressed = null; + /// + /// Embeds a file to this container. + /// + /// The name how it should be called in this container. + /// The file path to the file that should be embedded. + /// Returns a that defines if the file as been embedded successfully. + public bool AddFile(string fileName, string filePath) + { + bool success; + FileStream fs = null; + MemoryStream compressed = null; #if !DEBUG - try - { + try + { #endif - fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); - compressed = new MemoryStream(); - using (var compressor = new DeflateStream(compressed, CompressionLevel.Optimal, true)) - fs.CopyTo(compressor); - success = true; + fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); + compressed = new MemoryStream(); + using (var compressor = new DeflateStream(compressed, CompressionLevel.Optimal, true)) + fs.CopyTo(compressor); + success = true; #if !DEBUG - } - catch (Exception) - { - success = false; - } + } + catch (Exception) + { + success = false; + } #endif - if (success) - { - var compressedBytes = compressed.ToArray(); - if (compressedFiles.ContainsKey(fileName)) - compressedFiles[fileName] = compressedBytes; - else - compressedFiles.Add(fileName, compressedBytes); - } - - compressed?.Close(); - fs?.Close(); - - return success; - } - - /// - /// Removes a file from this container. - /// - /// The name how the file is called. - public void RemoveFile(string fileName) + if (success) { + var compressedBytes = compressed.ToArray(); if (compressedFiles.ContainsKey(fileName)) - compressedFiles.Remove(fileName); + compressedFiles[fileName] = compressedBytes; + else + compressedFiles.Add(fileName, compressedBytes); } - /// - /// Checks if the given file exists in this container. - /// - /// The name how the file is called. - /// Returns if the given file exists in this container. - public bool HasFile(string fileName) + compressed?.Close(); + fs?.Close(); + + return success; + } + + /// + /// Removes a file from this container. + /// + /// The name how the file is called. + public void RemoveFile(string fileName) + { + if (compressedFiles.ContainsKey(fileName)) + compressedFiles.Remove(fileName); + } + + /// + /// Checks if the given file exists in this container. + /// + /// The name how the file is called. + /// Returns if the given file exists in this container. + public bool HasFile(string fileName) + { + return compressedFiles.ContainsKey(fileName); + } + + /// + /// Gets a file from this container as stream. + /// + /// The name how the file is called. + /// Returns a stream of the file with the given name. + public Task GetStreamAsync(string fileName) + { + return Task.Run(() => GetStream(fileName)); + } + + /// + /// Gets a file from this container as stream. + /// + /// The name how the file is called. + /// Returns a stream of the file with the given name. + public Stream GetStream(string fileName) + { + Stream decompressed = null; + + if (compressedFiles.ContainsKey(fileName)) { - return compressedFiles.ContainsKey(fileName); + decompressed = new MemoryStream(); + DecompressToStream(decompressed, compressedFiles[fileName]); } - /// - /// Gets a file from this container as stream. - /// - /// The name how the file is called. - /// Returns a stream of the file with the given name. - public Task GetStreamAsync(string fileName) + return decompressed; + } + + /// + /// Saves a given file to the users temp directory. + /// + /// The name how the file is called. + /// Returns the file path to the temp file. + public Task GetLocalFilePathAsync(string fileName) + { + return Task.Run(() => GetLocalFilePath(fileName)); + } + + + /// + /// Saves a given file to the users temp directory. + /// + /// The name how the file is called. + /// Returns the file path to the temp file. + public string GetLocalFilePath(string fileName) + { + string filePath = string.Empty; + + if (compressedFiles.ContainsKey(fileName)) { - return Task.Run(() => GetStream(fileName)); + filePath = Path.GetTempFileName(); + + if (Path.HasExtension(fileName)) + filePath = Path.ChangeExtension(filePath, Path.GetExtension(fileName)); + + var decompressed = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); + DecompressToStream(decompressed, compressedFiles[fileName]); + decompressed.Flush(); + decompressed.Close(); } - /// - /// Gets a file from this container as stream. - /// - /// The name how the file is called. - /// Returns a stream of the file with the given name. - public Stream GetStream(string fileName) - { - Stream decompressed = null; + return filePath; + } - if (compressedFiles.ContainsKey(fileName)) - { - decompressed = new MemoryStream(); - DecompressToStream(decompressed, compressedFiles[fileName]); - } - - return decompressed; - } - - /// - /// Saves a given file to the users temp directory. - /// - /// The name how the file is called. - /// Returns the file path to the temp file. - public Task GetLocalFilePathAsync(string fileName) - { - return Task.Run(() => GetLocalFilePath(fileName)); - } - - - /// - /// Saves a given file to the users temp directory. - /// - /// The name how the file is called. - /// Returns the file path to the temp file. - public string GetLocalFilePath(string fileName) - { - string filePath = string.Empty; - - if (compressedFiles.ContainsKey(fileName)) - { - filePath = Path.GetTempFileName(); - - if (Path.HasExtension(fileName)) - filePath = Path.ChangeExtension(filePath, Path.GetExtension(fileName)); - - var decompressed = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); - DecompressToStream(decompressed, compressedFiles[fileName]); - decompressed.Flush(); - decompressed.Close(); - } - - return filePath; - } - - private void DecompressToStream(Stream decompressed, byte[] compressedData) - { - var compressed = new MemoryStream(compressedData); - var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true); - decompressor.CopyTo(decompressed); - decompressor.Close(); - compressed.Close(); - } + private void DecompressToStream(Stream decompressed, byte[] compressedData) + { + var compressed = new MemoryStream(compressedData); + var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true); + decompressor.CopyTo(decompressed); + decompressor.Close(); + compressed.Close(); } } diff --git a/Pilz.IO/EventArgs/DataEventargs.cs b/Pilz.IO/EventArgs/DataEventargs.cs index a8f4e1b..e920d0b 100644 --- a/Pilz.IO/EventArgs/DataEventargs.cs +++ b/Pilz.IO/EventArgs/DataEventargs.cs @@ -1,14 +1,13 @@ using System; -namespace Pilz.IO -{ - public class DataEventArgs : EventArgs - { - public readonly byte[] Data; +namespace Pilz.IO; - public DataEventArgs(byte[] bytes) : base() - { - Data = bytes; - } +public class DataEventArgs : EventArgs +{ + public readonly byte[] Data; + + public DataEventArgs(byte[] bytes) : base() + { + Data = bytes; } } \ No newline at end of file diff --git a/Pilz.IO/Extensions.cs b/Pilz.IO/Extensions.cs index 0cf41e2..63eeea6 100644 --- a/Pilz.IO/Extensions.cs +++ b/Pilz.IO/Extensions.cs @@ -1,26 +1,23 @@ using Pilz.Runtime; -using Pilz.Win32.Native; using System; -using System.Collections.Generic; using System.Diagnostics; using System.Text; -namespace Pilz.IO -{ - public static class Extensions - { - static readonly int MAX_PATH = 255; +namespace Pilz.IO; - public static string GetExecutablePath(bool checkRealOS = false) +public static class Extensions +{ + static readonly int MAX_PATH = 255; + + public static string GetExecutablePath(bool checkRealOS = false) + { + if (RuntimeInformationsEx.IsOSPlatform(OSType.Windows, checkRealOS)) { - if (RuntimeInformationsEx.IsOSPlatform(OSType.Windows, checkRealOS)) - { - var sb = new StringBuilder(MAX_PATH); - Kernel32.GetModuleFileName(IntPtr.Zero, sb, MAX_PATH); - return sb.ToString(); - } - else - return Process.GetCurrentProcess().MainModule.FileName; + var sb = new StringBuilder(MAX_PATH); + Kernel32.GetModuleFileName(IntPtr.Zero, sb, MAX_PATH); + return sb.ToString(); } + else + return Process.GetCurrentProcess().MainModule.FileName; } } diff --git a/Pilz.IO/FileLocker.cs b/Pilz.IO/FileLocker.cs index c4bc8e6..7255af9 100644 --- a/Pilz.IO/FileLocker.cs +++ b/Pilz.IO/FileLocker.cs @@ -1,118 +1,117 @@ using System; using System.IO; -namespace Pilz.IO +namespace Pilz.IO; + +public partial class FileLocker : IDisposable { - public partial class FileLocker : IDisposable + private FileStream fsLock = null; + + /// + /// Defines the file path to the file that should be locked. + /// + public string FilePath { get; private set; } + /// + /// Defines the file path to the lock file that is used to identify the file lock. + /// + public string LockFile { get; private set; } + /// + /// Defines if the file is locked privatly by this instance. + /// + public bool LockedPrivate { get; private set; } = false; + + /// + /// Defines if the file is locked by an other instance/program/user. + /// + public bool LockedExternal { - private FileStream fsLock = null; - - /// - /// Defines the file path to the file that should be locked. - /// - public string FilePath { get; private set; } - /// - /// Defines the file path to the lock file that is used to identify the file lock. - /// - public string LockFile { get; private set; } - /// - /// Defines if the file is locked privatly by this instance. - /// - public bool LockedPrivate { get; private set; } = false; - - /// - /// Defines if the file is locked by an other instance/program/user. - /// - public bool LockedExternal - { - get - { - if (LockedPrivate) - return false; - else - { - string lockFile = FilePath + ".lock"; - bool isLocked = false; - - if (File.Exists(lockFile)) - { - try - { - var fs = new FileStream(lockFile, FileMode.Open, FileAccess.Read); - fs.Close(); - } - catch (IOException) - { - isLocked = true; - } - } - - return isLocked; - } - } - } - - /// - /// Generate a new instance of and locks the given file automatically. - /// - /// The file path to the file that should be locked. - public FileLocker(string filePath) : this(filePath, true) - { - } - - /// - /// Generate a new instance of - /// - /// The file path to the file that should be locked. - /// Defines if the file should be locked automatically right after creating this instance. - public FileLocker(string filePath, bool autoLock) - { - FilePath = filePath; - LockFile = filePath + ".lock"; - if (autoLock) Lock(); - } - - /// - /// Locks the file, if not already locked privatly. - /// - public void Lock() - { - if (!LockedPrivate) - { - fsLock = new FileStream(LockFile, FileMode.Create, FileAccess.ReadWrite); - LockedPrivate = true; - } - } - - /// - /// Unlocks the file, if locked privatly. - /// - public void Unlock() + get { if (LockedPrivate) + return false; + else { - fsLock.Close(); - fsLock.Dispose(); - fsLock = null; - File.Delete(LockFile); - LockedPrivate = false; + string lockFile = FilePath + ".lock"; + bool isLocked = false; + + if (File.Exists(lockFile)) + { + try + { + var fs = new FileStream(lockFile, FileMode.Open, FileAccess.Read); + fs.Close(); + } + catch (IOException) + { + isLocked = true; + } + } + + return isLocked; } } - - #region IDisposable - private bool disposedValue; - - protected virtual void Dispose(bool disposing) - { - if (!disposedValue) - Unlock(); - } - - public void Dispose() - { - Dispose(true); - disposedValue = true; - } - #endregion } + + /// + /// Generate a new instance of and locks the given file automatically. + /// + /// The file path to the file that should be locked. + public FileLocker(string filePath) : this(filePath, true) + { + } + + /// + /// Generate a new instance of + /// + /// The file path to the file that should be locked. + /// Defines if the file should be locked automatically right after creating this instance. + public FileLocker(string filePath, bool autoLock) + { + FilePath = filePath; + LockFile = filePath + ".lock"; + if (autoLock) Lock(); + } + + /// + /// Locks the file, if not already locked privatly. + /// + public void Lock() + { + if (!LockedPrivate) + { + fsLock = new FileStream(LockFile, FileMode.Create, FileAccess.ReadWrite); + LockedPrivate = true; + } + } + + /// + /// Unlocks the file, if locked privatly. + /// + public void Unlock() + { + if (LockedPrivate) + { + fsLock.Close(); + fsLock.Dispose(); + fsLock = null; + File.Delete(LockFile); + LockedPrivate = false; + } + } + + #region IDisposable + private bool disposedValue; + + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + Unlock(); + } + + public void Dispose() + { + Dispose(true); + disposedValue = true; + } + #endregion } \ No newline at end of file diff --git a/Pilz.IO/ManagedPipes/ManagedPipe.cs b/Pilz.IO/ManagedPipes/ManagedPipe.cs index 9546e5d..709b4e3 100644 --- a/Pilz.IO/ManagedPipes/ManagedPipe.cs +++ b/Pilz.IO/ManagedPipes/ManagedPipe.cs @@ -2,66 +2,65 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace Pilz.IO +namespace Pilz.IO; + +/// +/// stellt den Erben "Server" und "Client" 2 verschiedene +/// Message-Events zur Verfügung, und ein Event-Raisendes Dispose +/// +public abstract class ManagedPipe : IDisposable { + public delegate void EventHandlerWithOneArgument(T0 Sender); + /// - /// stellt den Erben "Server" und "Client" 2 verschiedene - /// Message-Events zur Verfügung, und ein Event-Raisendes Dispose + /// Zur Ausgabe chat-verwaltungstechnischer Status-Informationen /// - public abstract class ManagedPipe : IDisposable + public event EventHandler StatusMessage; + /// Zur Ausgabe von Chat-Messages + public event EventHandler RetriveData; + public event EventHandlerWithOneArgument Disposed; + + private bool _IsDisposed = false; + + protected abstract void Dispose(bool disposing); + public abstract void Send(byte[] bytes); + public abstract Task SendAsnyc(byte[] bytes); + + protected void OnStatusMessage(DataEventArgs e) { - public delegate void EventHandlerWithOneArgument(T0 Sender); + StatusMessage?.Invoke(this, e); + } - /// - /// Zur Ausgabe chat-verwaltungstechnischer Status-Informationen - /// - public event EventHandler StatusMessage; - /// Zur Ausgabe von Chat-Messages - public event EventHandler RetriveData; - public event EventHandlerWithOneArgument Disposed; + protected void OnRetriveData(DataEventArgs e) + { + RetriveData?.Invoke(this, e); + } - private bool _IsDisposed = false; + public void RemoveFrom(ICollection Coll) where T : ManagedPipe + { + Coll.Remove((T)this); + } - protected abstract void Dispose(bool disposing); - public abstract void Send(byte[] bytes); - public abstract Task SendAsnyc(byte[] bytes); - - protected void OnStatusMessage(DataEventArgs e) + public bool IsDisposed + { + get { - StatusMessage?.Invoke(this, e); - } - - protected void OnRetriveData(DataEventArgs e) - { - RetriveData?.Invoke(this, e); - } - - public void RemoveFrom(ICollection Coll) where T : ManagedPipe - { - Coll.Remove((T)this); - } - - public bool IsDisposed - { - get - { - return _IsDisposed; - } - } - - public void AddTo(ICollection Coll) where T : ManagedPipe - { - Coll.Add((T)this); - } - - public void Dispose() - { - if (_IsDisposed) - return; - _IsDisposed = true; - Dispose(true); // rufe die erzwungenen Überschreibungen von Sub Dispose(Boolean) - Disposed?.Invoke(this); - GC.SuppressFinalize(this); + return _IsDisposed; } } + + public void AddTo(ICollection Coll) where T : ManagedPipe + { + Coll.Add((T)this); + } + + public void Dispose() + { + if (_IsDisposed) + return; + _IsDisposed = true; + Dispose(true); // rufe die erzwungenen Überschreibungen von Sub Dispose(Boolean) + Disposed?.Invoke(this); + GC.SuppressFinalize(this); + } } \ No newline at end of file diff --git a/Pilz.IO/ManagedPipes/ManagedPipeClient.cs b/Pilz.IO/ManagedPipes/ManagedPipeClient.cs index cbac124..b771d56 100644 --- a/Pilz.IO/ManagedPipes/ManagedPipeClient.cs +++ b/Pilz.IO/ManagedPipes/ManagedPipeClient.cs @@ -1,90 +1,89 @@ -using System; +using global::System.IO.Pipes; +using System; using System.Collections.Generic; -using global::System.IO.Pipes; using System.Threading.Tasks; -namespace Pilz.IO +namespace Pilz.IO; + +public class ManagedPipeClient : ManagedPipe { - public class ManagedPipeClient : ManagedPipe + private PipeStream pipeStream; + private byte[] _Buf = new byte[1024]; + + public ManagedPipeClient(string pipeName) : this(pipeName, ".") { - private PipeStream pipeStream; - private byte[] _Buf = new byte[1024]; + } - public ManagedPipeClient(string pipeName) : this(pipeName, ".") + public ManagedPipeClient(string pipeName, string serverName) : this(pipeName, serverName, -1) + { + } + + public ManagedPipeClient(string pipeName, int connectionTimeout) : this(pipeName, ".", connectionTimeout) + { + } + + public ManagedPipeClient(string pipeName, string serverName, int connectionTimeout) + { + var clnt = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); + clnt.Connect(connectionTimeout); + if (!clnt.IsConnected) { + throw new TimeoutException("Connection timeout!"); } - public ManagedPipeClient(string pipeName, string serverName) : this(pipeName, serverName, -1) + SetPipe(clnt); + } + + public ManagedPipeClient(PipeStream pipe) + { + SetPipe(pipe); + } + + private void SetPipe(PipeStream pipe) + { + pipeStream = pipe; + pipeStream.BeginRead(_Buf, 0, _Buf.Length, EndRead, null); + } + + private void EndRead(IAsyncResult ar) + { + if (IsDisposed) + return; + int bytesCount = pipeStream.EndRead(ar); + if (bytesCount == 0) // leere Datenübermittlung signalisiert Verbindungsabbruch { + Dispose(); + return; } - public ManagedPipeClient(string pipeName, int connectionTimeout) : this(pipeName, ".", connectionTimeout) + var list = new List(); + for (int i = 0, loopTo = bytesCount - 1; i <= loopTo; i++) + list.Add(_Buf[i]); + while (bytesCount == _Buf.Length) { - } - - public ManagedPipeClient(string pipeName, string serverName, int connectionTimeout) - { - var clnt = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); - clnt.Connect(connectionTimeout); - if (!clnt.IsConnected) - { - throw new TimeoutException("Connection timeout!"); - } - - SetPipe(clnt); - } - - public ManagedPipeClient(PipeStream pipe) - { - SetPipe(pipe); - } - - private void SetPipe(PipeStream pipe) - { - pipeStream = pipe; - pipeStream.BeginRead(_Buf, 0, _Buf.Length, EndRead, null); - } - - private void EndRead(IAsyncResult ar) - { - if (IsDisposed) - return; - int bytesCount = pipeStream.EndRead(ar); - if (bytesCount == 0) // leere Datenübermittlung signalisiert Verbindungsabbruch - { - Dispose(); - return; - } - - var list = new List(); - for (int i = 0, loopTo = bytesCount - 1; i <= loopTo; i++) + bytesCount = pipeStream.Read(_Buf, 0, _Buf.Length); + for (int i = 0, loopTo1 = bytesCount - 1; i <= loopTo1; i++) list.Add(_Buf[i]); - while (bytesCount == _Buf.Length) - { - bytesCount = pipeStream.Read(_Buf, 0, _Buf.Length); - for (int i = 0, loopTo1 = bytesCount - 1; i <= loopTo1; i++) - list.Add(_Buf[i]); - } - - var deargs = new DataEventArgs(list.ToArray()); - OnRetriveData(deargs); - - pipeStream.BeginRead(_Buf, 0, _Buf.Length, EndRead, null); } - public override Task SendAsnyc(byte[] bytes) - { - return Task.Run(() => Send(bytes)); - } + var deargs = new DataEventArgs(list.ToArray()); + OnRetriveData(deargs); - public override void Send(byte[] data) - { - pipeStream.Write(data, 0, data.Length); - } + pipeStream.BeginRead(_Buf, 0, _Buf.Length, EndRead, null); + } - protected override void Dispose(bool disposing) - { - pipeStream.Dispose(); - } + public override Task SendAsnyc(byte[] bytes) + { + return Task.Run(() => Send(bytes)); + } + + public override void Send(byte[] data) + { + pipeStream.Write(data, 0, data.Length); + } + + protected override void Dispose(bool disposing) + { + pipeStream.Dispose(); } } \ No newline at end of file diff --git a/Pilz.IO/ManagedPipes/ManagedPipeServer.cs b/Pilz.IO/ManagedPipes/ManagedPipeServer.cs index 2f673f9..69dac16 100644 --- a/Pilz.IO/ManagedPipes/ManagedPipeServer.cs +++ b/Pilz.IO/ManagedPipes/ManagedPipeServer.cs @@ -1,108 +1,107 @@ -using System; +using global::System.IO.Pipes; +using System; using System.Collections.Generic; -using global::System.IO.Pipes; using System.Threading.Tasks; -namespace Pilz.IO +namespace Pilz.IO; + +public class ManagedPipeServer : ManagedPipe { - public class ManagedPipeServer : ManagedPipe + + // Pro Verbindung (Anfrage) wird ein Client-Objekt generiert, das den Datenaustausch dieser Verbindung abwickelt + public List Clients { get; private set; } = new List(); + + private readonly string pipeName = ""; + private readonly int maxNumbersOfServerInstances; + private int numberOfStartedServerInstances = 0; + + public ManagedPipeServer(string pipeName) : this(pipeName, 1) { + } - // Pro Verbindung (Anfrage) wird ein Client-Objekt generiert, das den Datenaustausch dieser Verbindung abwickelt - public List Clients { get; private set; } = new List(); + public ManagedPipeServer(string pipeName, int maxNumbersOfServerInstances) + { + this.pipeName = pipeName; + this.maxNumbersOfServerInstances = maxNumbersOfServerInstances; + CreateWaitingStream(); + } - private readonly string pipeName = ""; - private readonly int maxNumbersOfServerInstances; - private int numberOfStartedServerInstances = 0; - - public ManagedPipeServer(string pipeName) : this(pipeName, 1) + private void CreateWaitingStream() + { + if (numberOfStartedServerInstances < maxNumbersOfServerInstances) { - } - - public ManagedPipeServer(string pipeName, int maxNumbersOfServerInstances) - { - this.pipeName = pipeName; - this.maxNumbersOfServerInstances = maxNumbersOfServerInstances; - CreateWaitingStream(); - } - - private void CreateWaitingStream() - { - if (numberOfStartedServerInstances < maxNumbersOfServerInstances) - { - var strm = new NamedPipeServerStream(pipeName, PipeDirection.InOut, maxNumbersOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); - numberOfStartedServerInstances += 1; - strm.BeginWaitForConnection(EndAccept, strm); - } - } - - private void EndAccept(IAsyncResult ar) - { - NamedPipeServerStream strm = (NamedPipeServerStream)ar.AsyncState; - strm.EndWaitForConnection(ar); - if (IsDisposed) - { - strm.Dispose(); - return; - } - - { - var withBlock = new ManagedPipeClient(strm); - withBlock.RetriveData += Client_RetriveData; - withBlock.StatusMessage += Client_StatusMessage; - withBlock.Disposed += Client_Disposed; - withBlock.AddTo(Clients); - } - - CreateWaitingStream(); - } - - /* TODO ERROR: Skipped RegionDirectiveTrivia */ - private void Client_Disposed(ManagedPipe Sender) - { - // den Client für die beendete Verbindung entfernen - Sender.RemoveFrom(Clients); - numberOfStartedServerInstances -= 1; - CreateWaitingStream(); - } - - private void Client_RetriveData(object sender, DataEventArgs e) - { - // einkommende ChatMessages anzeigen, und an alle versenden - OnRetriveData(e); - } - - private void Client_StatusMessage(object sender, DataEventArgs e) - { - // einkommende StatusMessages durchreichen (zur Anzeige) - OnStatusMessage(e); - } - - /* TODO ERROR: Skipped EndRegionDirectiveTrivia */ - public override Task SendAsnyc(byte[] bytes) - { - return Task.Run(() => Send(bytes)); - } - - public override void Send(byte[] data) - { - foreach (ManagedPipeClient client in Clients) // an alle versenden - client.Send(data); - } - - protected override void Dispose(bool disposing) - { - if (numberOfStartedServerInstances < maxNumbersOfServerInstances) - { - using (var clnt = new NamedPipeClientStream(pipeName)) - { - // Herstellen einer Dummi-Verbindung, damit der ServerStream aus dem Wartezustand herauskommt. - clnt.Connect(); - } - } - - for (int i = Clients.Count - 1; i >= 0; i -= 1) - Clients[i].Dispose(); + var strm = new NamedPipeServerStream(pipeName, PipeDirection.InOut, maxNumbersOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + numberOfStartedServerInstances += 1; + strm.BeginWaitForConnection(EndAccept, strm); } } + + private void EndAccept(IAsyncResult ar) + { + NamedPipeServerStream strm = (NamedPipeServerStream)ar.AsyncState; + strm.EndWaitForConnection(ar); + if (IsDisposed) + { + strm.Dispose(); + return; + } + + { + var withBlock = new ManagedPipeClient(strm); + withBlock.RetriveData += Client_RetriveData; + withBlock.StatusMessage += Client_StatusMessage; + withBlock.Disposed += Client_Disposed; + withBlock.AddTo(Clients); + } + + CreateWaitingStream(); + } + + /* TODO ERROR: Skipped RegionDirectiveTrivia */ + private void Client_Disposed(ManagedPipe Sender) + { + // den Client für die beendete Verbindung entfernen + Sender.RemoveFrom(Clients); + numberOfStartedServerInstances -= 1; + CreateWaitingStream(); + } + + private void Client_RetriveData(object sender, DataEventArgs e) + { + // einkommende ChatMessages anzeigen, und an alle versenden + OnRetriveData(e); + } + + private void Client_StatusMessage(object sender, DataEventArgs e) + { + // einkommende StatusMessages durchreichen (zur Anzeige) + OnStatusMessage(e); + } + + /* TODO ERROR: Skipped EndRegionDirectiveTrivia */ + public override Task SendAsnyc(byte[] bytes) + { + return Task.Run(() => Send(bytes)); + } + + public override void Send(byte[] data) + { + foreach (ManagedPipeClient client in Clients) // an alle versenden + client.Send(data); + } + + protected override void Dispose(bool disposing) + { + if (numberOfStartedServerInstances < maxNumbersOfServerInstances) + { + using (var clnt = new NamedPipeClientStream(pipeName)) + { + // Herstellen einer Dummi-Verbindung, damit der ServerStream aus dem Wartezustand herauskommt. + clnt.Connect(); + } + } + + for (int i = Clients.Count - 1; i >= 0; i -= 1) + Clients[i].Dispose(); + } } \ No newline at end of file diff --git a/Pilz.IO/Properties/AssemblyInfo.cs b/Pilz.IO/Properties/AssemblyInfo.cs index 11816c6..b2fe7e9 100644 --- a/Pilz.IO/Properties/AssemblyInfo.cs +++ b/Pilz.IO/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using global::System; -using global::System.Reflection; using global::System.Runtime.InteropServices; [assembly: ComVisible(false)] diff --git a/Pilz.LicenseHelper/AsposeModifyInMemory.cs b/Pilz.LicenseHelper/AsposeModifyInMemory.cs index ce93850..6acd083 100644 --- a/Pilz.LicenseHelper/AsposeModifyInMemory.cs +++ b/Pilz.LicenseHelper/AsposeModifyInMemory.cs @@ -6,180 +6,179 @@ using System.Runtime.CompilerServices; using System.Text; using System.Xml; -namespace Pilz.LicenseHelper +namespace Pilz.LicenseHelper; + +public static class AsposeModifyInMemory { - public static class AsposeModifyInMemory + private static string AsposeList = "Aspose.3D.dll, Aspose.BarCode.dll, Aspose.BarCode.Compact.dll, Aspose.BarCode.WPF.dll, Aspose.Cells.GridDesktop.dll, Aspose.Cells.GridWeb.dll, Aspose.CAD.dll, Aspose.Cells.dll, Aspose.Diagram.dll, Aspose.Email.dll, Aspose.Imaging.dll, Aspose.Note.dll, Aspose.OCR.dll, Aspose.Pdf.dll, Aspose.Slides.dll, Aspose.Tasks.dll, Aspose.Words.dll"; + + public static void ActivateMemoryPatching() { - private static string AsposeList = "Aspose.3D.dll, Aspose.BarCode.dll, Aspose.BarCode.Compact.dll, Aspose.BarCode.WPF.dll, Aspose.Cells.GridDesktop.dll, Aspose.Cells.GridWeb.dll, Aspose.CAD.dll, Aspose.Cells.dll, Aspose.Diagram.dll, Aspose.Email.dll, Aspose.Imaging.dll, Aspose.Note.dll, Aspose.OCR.dll, Aspose.Pdf.dll, Aspose.Slides.dll, Aspose.Tasks.dll, Aspose.Words.dll"; - - public static void ActivateMemoryPatching() + Assembly[] arr = AppDomain.CurrentDomain.GetAssemblies(); + foreach (Assembly assembly in arr) { - Assembly[] arr = AppDomain.CurrentDomain.GetAssemblies(); - foreach (Assembly assembly in arr) - { - if (AsposeList.IndexOf(assembly.FullName.Split(',')[0] + ".dll") != -1) - ActivateForAssembly(assembly); - } - AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(ActivateOnLoad); + if (AsposeList.IndexOf(assembly.FullName.Split(',')[0] + ".dll") != -1) + ActivateForAssembly(assembly); + } + AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(ActivateOnLoad); + } + + private static void ActivateOnLoad(object sender, AssemblyLoadEventArgs e) + { + if (AsposeList.IndexOf(e.LoadedAssembly.FullName.Split(',')[0] + ".dll") != -1) + ActivateForAssembly(e.LoadedAssembly); + } + + private static void ActivateForAssembly(Assembly assembly) + { + MethodInfo miLicensed1 = typeof(AsposeModifyInMemory).GetMethod("InvokeMe1", BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo miLicensed2 = typeof(AsposeModifyInMemory).GetMethod("InvokeMe2", BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo miEvaluation = null; + + Dictionary miDict = new Dictionary() + { + {"System.DateTime" , miLicensed1}, + {"System.Xml.XmlElement", miLicensed2} + }; + + Type[] arrType = null; + bool isFound = false; + int nCount = 0; + + try + { + arrType = assembly.GetTypes(); + } + catch (ReflectionTypeLoadException err) + { + arrType = err.Types; } - private static void ActivateOnLoad(object sender, AssemblyLoadEventArgs e) + + foreach (Type type in arrType) { - if (AsposeList.IndexOf(e.LoadedAssembly.FullName.Split(',')[0] + ".dll") != -1) - ActivateForAssembly(e.LoadedAssembly); - } + if (isFound) break; - private static void ActivateForAssembly(Assembly assembly) - { - MethodInfo miLicensed1 = typeof(AsposeModifyInMemory).GetMethod("InvokeMe1", BindingFlags.NonPublic | BindingFlags.Static); - MethodInfo miLicensed2 = typeof(AsposeModifyInMemory).GetMethod("InvokeMe2", BindingFlags.NonPublic | BindingFlags.Static); - MethodInfo miEvaluation = null; + if (type == null) continue; - Dictionary miDict = new Dictionary() - { - {"System.DateTime" , miLicensed1}, - {"System.Xml.XmlElement", miLicensed2} - }; + MethodInfo[] arrMInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static); - Type[] arrType = null; - bool isFound = false; - int nCount = 0; - - try - { - arrType = assembly.GetTypes(); - } - catch (ReflectionTypeLoadException err) - { - arrType = err.Types; - } - - - foreach (Type type in arrType) + foreach (MethodInfo info in arrMInfo) { if (isFound) break; - if (type == null) continue; - - MethodInfo[] arrMInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static); - - foreach (MethodInfo info in arrMInfo) + try { - if (isFound) break; - - try + string strMethod = info.ToString(); + if ((strMethod.IndexOf("(System.Xml.XmlElement, System.String)") > 0) && (miDict.ContainsKey(info.ReturnType.ToString()))) { - string strMethod = info.ToString(); - if ((strMethod.IndexOf("(System.Xml.XmlElement, System.String)") > 0) && (miDict.ContainsKey(info.ReturnType.ToString()))) - { - miEvaluation = info; - MemoryPatching(miEvaluation, miDict[miEvaluation.ReturnType.ToString()]); - nCount++; + miEvaluation = info; + MemoryPatching(miEvaluation, miDict[miEvaluation.ReturnType.ToString()]); + nCount++; - if ((assembly.FullName.IndexOf("Aspose.3D") != -1) && (nCount == 2)) - { - isFound = true; - break; - } + if ((assembly.FullName.IndexOf("Aspose.3D") != -1) && (nCount == 2)) + { + isFound = true; + break; } } - catch - { - throw new InvalidOperationException("MemoryPatching for \"" + assembly.FullName + "\" failed !"); - } + } + catch + { + throw new InvalidOperationException("MemoryPatching for \"" + assembly.FullName + "\" failed !"); } } - - String[] aParts = assembly.FullName.Split(','); - string fName = aParts[0]; - if (fName.IndexOf("Aspose.BarCode.") != -1) - fName = "Aspose.BarCode"; - else if (fName.IndexOf("Aspose.3D") != -1) - fName = "Aspose.ThreeD"; - - try - { - Type type2 = assembly.GetType(fName + ".License"); - MethodInfo mi = type2.GetMethod("SetLicense", new Type[] { typeof(Stream) }); - string LData = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5MaWNlbnNlZTwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPmxpY2Vuc2VlQGVtYWlsLmNvbTwvRW1haWxUbz4KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4KICAgIDxMaWNlbnNlTm90ZT5MaW1pdGVkIHRvIDEwMDAgZGV2ZWxvcGVyLCB1bmxpbWl0ZWQgcGh5c2ljYWwgbG9jYXRpb25zPC9MaWNlbnNlTm90ZT4KICAgIDxPcmRlcklEPjc4NDM3ODU3Nzg1PC9PcmRlcklEPgogICAgPFVzZXJJRD4xMTk3ODkyNDM3OTwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIFByb2R1Y3QgRmFtaWx5PC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+e0YyQjk3MDQ1LTFCMjktNEIzRi1CRDUzLTYwMUVGRkExNUFBOX08L1NlcmlhbE51bWJlcj4KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+MjA5OTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4KICAgIDxMaWNlbnNlVmVyc2lvbj4zLjA8L0xpY2Vuc2VWZXJzaW9uPgogIDwvRGF0YT4KICA8U2lnbmF0dXJlPlFYTndiM05sTGxSdmRHRnNJRkJ5YjJSMVkzUWdSbUZ0YVd4NTwvU2lnbmF0dXJlPgo8L0xpY2Vuc2U+"; - Stream stream = new MemoryStream(Convert.FromBase64String(LData)); - stream.Seek(0, SeekOrigin.Begin); - mi.Invoke(Activator.CreateInstance(type2, null), new Stream[] { stream }); - } - catch - { - throw new InvalidOperationException("SetLicense for \"" + assembly.FullName + "\" failed !"); - } - } + String[] aParts = assembly.FullName.Split(','); + string fName = aParts[0]; + if (fName.IndexOf("Aspose.BarCode.") != -1) + fName = "Aspose.BarCode"; + else if (fName.IndexOf("Aspose.3D") != -1) + fName = "Aspose.ThreeD"; - private static DateTime InvokeMe1(XmlElement element, string name) + try { - return DateTime.MaxValue; + Type type2 = assembly.GetType(fName + ".License"); + MethodInfo mi = type2.GetMethod("SetLicense", new Type[] { typeof(Stream) }); + string LData = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5MaWNlbnNlZTwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPmxpY2Vuc2VlQGVtYWlsLmNvbTwvRW1haWxUbz4KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4KICAgIDxMaWNlbnNlTm90ZT5MaW1pdGVkIHRvIDEwMDAgZGV2ZWxvcGVyLCB1bmxpbWl0ZWQgcGh5c2ljYWwgbG9jYXRpb25zPC9MaWNlbnNlTm90ZT4KICAgIDxPcmRlcklEPjc4NDM3ODU3Nzg1PC9PcmRlcklEPgogICAgPFVzZXJJRD4xMTk3ODkyNDM3OTwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIFByb2R1Y3QgRmFtaWx5PC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+e0YyQjk3MDQ1LTFCMjktNEIzRi1CRDUzLTYwMUVGRkExNUFBOX08L1NlcmlhbE51bWJlcj4KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+MjA5OTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4KICAgIDxMaWNlbnNlVmVyc2lvbj4zLjA8L0xpY2Vuc2VWZXJzaW9uPgogIDwvRGF0YT4KICA8U2lnbmF0dXJlPlFYTndiM05sTGxSdmRHRnNJRkJ5YjJSMVkzUWdSbUZ0YVd4NTwvU2lnbmF0dXJlPgo8L0xpY2Vuc2U+"; + Stream stream = new MemoryStream(Convert.FromBase64String(LData)); + stream.Seek(0, SeekOrigin.Begin); + mi.Invoke(Activator.CreateInstance(type2, null), new Stream[] { stream }); + } + catch + { + throw new InvalidOperationException("SetLicense for \"" + assembly.FullName + "\" failed !"); } + } - private static XmlElement InvokeMe2(XmlElement element, string name) + + private static DateTime InvokeMe1(XmlElement element, string name) + { + return DateTime.MaxValue; + } + + + private static XmlElement InvokeMe2(XmlElement element, string name) + { + if (element.LocalName == "License") { - if (element.LocalName == "License") - { - string License64 = "PERhdGE+PExpY2Vuc2VkVG8+R3JvdXBEb2NzPC9MaWNlbnNlZFRvPjxMaWNlbnNlVHlwZT5TaXRlIE9FTTwvTGljZW5zZVR5cGU+PExpY2Vuc2VOb3RlPkxpbWl0ZWQgdG8gMTAgZGV2ZWxvcGVyczwvTGljZW5zZU5vdGU+PE9yZGVySUQ+MTMwNzI0MDQwODQ5PC9PcmRlcklEPjxPRU0+VGhpcyBpcyBhIHJlZGlzdHJpYnV0YWJsZSBsaWNlbnNlPC9PRU0+PFByb2R1Y3RzPjxQcm9kdWN0PkFzcG9zZS5Ub3RhbDwvUHJvZHVjdD48L1Byb2R1Y3RzPjxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT48U2VyaWFsTnVtYmVyPjliNTc5NTAxLTUyNjEtNDIyMC04NjcwLWZjMmQ4Y2NkZDkwYzwvU2VyaWFsTnVtYmVyPjxTdWJzY3JpcHRpb25FeHBpcnk+MjAxNDA3MjQ8L1N1YnNjcmlwdGlvbkV4cGlyeT48TGljZW5zZVZlcnNpb24+Mi4yPC9MaWNlbnNlVmVyc2lvbj48L0RhdGE+PFNpZ25hdHVyZT5udFpocmRoL3I0QS81ZFpsU2dWYnhac0hYSFBxSjZ5UVVYa0RvaW4vS2lVZWhUUWZET0lQdHdzUlR2NmRTUVplOVdXekNnV3RGdkdROWpmR2QySmF4YUQvbkx1ZEk2R0VVajhqeVhUMG4vbWRrMEF1WVZNYlBXRjJYd3dSTnFlTmRrblYyQjhrZVFwbDJ2RzZVbnhxS2J6VVFxS2Rhc1pzZ2w1Q0xqSFVEWms9PC9TaWduYXR1cmU+"; - element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(License64)); - } - - if (element.LocalName == "BlackList") - { - string BlackList64 = "PERhdGE+PC9EYXRhPjxTaWduYXR1cmU+cUJwMEx1cEVoM1ZnOWJjeS8vbUVXUk9KRWZmczRlY25iTHQxYlNhanU2NjY5RHlad09FakJ1eEdBdVBxS1hyd0x5bmZ5VWplYUNGQ0QxSkh2RVUxVUl5eXJOTnBSMXc2NXJIOUFyUCtFbE1lVCtIQkZ4NFMzckFVMnd6dkxPZnhGeU9DQ0dGQ2UraTdiSHlGQk44WHp6R1UwdGRPMGR1RTFoRTQ5M1RNY3pRPTwvU2lnbmF0dXJlPg=="; - element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(BlackList64)); - } - - XmlNodeList elementsByTagName = element.GetElementsByTagName(name); - if (elementsByTagName.Count <= 0) - { - return null; - } - - return (XmlElement)elementsByTagName[0]; + string License64 = "PERhdGE+PExpY2Vuc2VkVG8+R3JvdXBEb2NzPC9MaWNlbnNlZFRvPjxMaWNlbnNlVHlwZT5TaXRlIE9FTTwvTGljZW5zZVR5cGU+PExpY2Vuc2VOb3RlPkxpbWl0ZWQgdG8gMTAgZGV2ZWxvcGVyczwvTGljZW5zZU5vdGU+PE9yZGVySUQ+MTMwNzI0MDQwODQ5PC9PcmRlcklEPjxPRU0+VGhpcyBpcyBhIHJlZGlzdHJpYnV0YWJsZSBsaWNlbnNlPC9PRU0+PFByb2R1Y3RzPjxQcm9kdWN0PkFzcG9zZS5Ub3RhbDwvUHJvZHVjdD48L1Byb2R1Y3RzPjxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT48U2VyaWFsTnVtYmVyPjliNTc5NTAxLTUyNjEtNDIyMC04NjcwLWZjMmQ4Y2NkZDkwYzwvU2VyaWFsTnVtYmVyPjxTdWJzY3JpcHRpb25FeHBpcnk+MjAxNDA3MjQ8L1N1YnNjcmlwdGlvbkV4cGlyeT48TGljZW5zZVZlcnNpb24+Mi4yPC9MaWNlbnNlVmVyc2lvbj48L0RhdGE+PFNpZ25hdHVyZT5udFpocmRoL3I0QS81ZFpsU2dWYnhac0hYSFBxSjZ5UVVYa0RvaW4vS2lVZWhUUWZET0lQdHdzUlR2NmRTUVplOVdXekNnV3RGdkdROWpmR2QySmF4YUQvbkx1ZEk2R0VVajhqeVhUMG4vbWRrMEF1WVZNYlBXRjJYd3dSTnFlTmRrblYyQjhrZVFwbDJ2RzZVbnhxS2J6VVFxS2Rhc1pzZ2w1Q0xqSFVEWms9PC9TaWduYXR1cmU+"; + element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(License64)); } - - private static unsafe void MemoryPatching(MethodBase miEvaluation, MethodBase miLicensed) + if (element.LocalName == "BlackList") { - IntPtr IntPtrEval = GetMemoryAddress(miEvaluation); - IntPtr IntPtrLicensed = GetMemoryAddress(miLicensed); - - if (IntPtr.Size == 8) - *((long*)IntPtrEval.ToPointer()) = *((long*)IntPtrLicensed.ToPointer()); - else - *((int*)IntPtrEval.ToPointer()) = *((int*)IntPtrLicensed.ToPointer()); - + string BlackList64 = "PERhdGE+PC9EYXRhPjxTaWduYXR1cmU+cUJwMEx1cEVoM1ZnOWJjeS8vbUVXUk9KRWZmczRlY25iTHQxYlNhanU2NjY5RHlad09FakJ1eEdBdVBxS1hyd0x5bmZ5VWplYUNGQ0QxSkh2RVUxVUl5eXJOTnBSMXc2NXJIOUFyUCtFbE1lVCtIQkZ4NFMzckFVMnd6dkxPZnhGeU9DQ0dGQ2UraTdiSHlGQk44WHp6R1UwdGRPMGR1RTFoRTQ5M1RNY3pRPTwvU2lnbmF0dXJlPg=="; + element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(BlackList64)); } - - private static unsafe IntPtr GetMemoryAddress(MethodBase mb) + XmlNodeList elementsByTagName = element.GetElementsByTagName(name); + if (elementsByTagName.Count <= 0) { - RuntimeHelpers.PrepareMethod(mb.MethodHandle); + return null; + } - if ((Environment.Version.Major >= 4) || ((Environment.Version.Major == 2) && (Environment.Version.MinorRevision >= 3053))) - { - return new IntPtr(((int*)mb.MethodHandle.Value.ToPointer() + 2)); - } + return (XmlElement)elementsByTagName[0]; + } - UInt64* location = (UInt64*)(mb.MethodHandle.Value.ToPointer()); - int index = (int)(((*location) >> 32) & 0xFF); - if (IntPtr.Size == 8) - { - ulong* classStart = (ulong*)mb.DeclaringType.TypeHandle.Value.ToPointer(); - ulong* address = classStart + index + 10; - return new IntPtr(address); - } - else - { - uint* classStart = (uint*)mb.DeclaringType.TypeHandle.Value.ToPointer(); - uint* address = classStart + index + 10; - return new IntPtr(address); - } + + private static unsafe void MemoryPatching(MethodBase miEvaluation, MethodBase miLicensed) + { + IntPtr IntPtrEval = GetMemoryAddress(miEvaluation); + IntPtr IntPtrLicensed = GetMemoryAddress(miLicensed); + + if (IntPtr.Size == 8) + *((long*)IntPtrEval.ToPointer()) = *((long*)IntPtrLicensed.ToPointer()); + else + *((int*)IntPtrEval.ToPointer()) = *((int*)IntPtrLicensed.ToPointer()); + + } + + + private static unsafe IntPtr GetMemoryAddress(MethodBase mb) + { + RuntimeHelpers.PrepareMethod(mb.MethodHandle); + + if ((Environment.Version.Major >= 4) || ((Environment.Version.Major == 2) && (Environment.Version.MinorRevision >= 3053))) + { + return new IntPtr(((int*)mb.MethodHandle.Value.ToPointer() + 2)); + } + + UInt64* location = (UInt64*)(mb.MethodHandle.Value.ToPointer()); + int index = (int)(((*location) >> 32) & 0xFF); + if (IntPtr.Size == 8) + { + ulong* classStart = (ulong*)mb.DeclaringType.TypeHandle.Value.ToPointer(); + ulong* address = classStart + index + 10; + return new IntPtr(address); + } + else + { + uint* classStart = (uint*)mb.DeclaringType.TypeHandle.Value.ToPointer(); + uint* address = classStart + index + 10; + return new IntPtr(address); } } } diff --git a/Pilz.LicenseHelper/Properties/AssemblyInfo.cs b/Pilz.LicenseHelper/Properties/AssemblyInfo.cs index d1747b5..7faba21 100644 --- a/Pilz.LicenseHelper/Properties/AssemblyInfo.cs +++ b/Pilz.LicenseHelper/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/FilesRetentionClient.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/FilesRetentionClient.cs index ae5bb87..8ba58f4 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/FilesRetentionClient.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/FilesRetentionClient.cs @@ -1,45 +1,39 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention; + +public class FilesRetentionClient : ClientBase { - public class FilesRetentionClient : ClientBase + public FilesRetentionClient(NextcloudClient client) : base(client) { - public FilesRetentionClient(NextcloudClient client) : base(client) + } + + public bool CreateRetentionRule(RetentionRuleInfo rule) + { + var entry = rule.ToOcsData(); + return Client.Ocs.GetApi().CreateRetentionRule(entry); + } + + public bool DeleteRetentionRule(int ruleID) + { + return Client.Ocs.GetApi().DeleteRetentionRule(ruleID); + } + + public RetentionRule[]? GetRetentionRules() + { + var api = Client.Ocs.GetApi(); + var response = api.GetRetentionRules(); + + if (response?.Data is not null) { + var rules = new List(); + + foreach (var entry in response.Data) + rules.Add(new RetentionRule(entry)); + + return rules.ToArray(); } - public bool CreateRetentionRule(RetentionRuleInfo rule) - { - var entry = rule.ToOcsData(); - return Client.Ocs.GetApi().CreateRetentionRule(entry); - } - - public bool DeleteRetentionRule(int ruleID) - { - return Client.Ocs.GetApi().DeleteRetentionRule(ruleID); - } - - public RetentionRule[]? GetRetentionRules() - { - var api = Client.Ocs.GetApi(); - var response = api.GetRetentionRules(); - - if (response?.Data is not null) - { - var rules = new List(); - - foreach (var entry in response.Data) - rules.Add(new RetentionRule(entry)); - - return rules.ToArray(); - } - - return null; - } + return null; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRule.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRule.cs index aab6f22..0d85135 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRule.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRule.cs @@ -1,36 +1,30 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model; + +public class RetentionRule : RetentionRuleInfo { - public class RetentionRule : RetentionRuleInfo + /// + /// The ID for the retention rule. + /// + public int ID { get; init; } + + /// + /// Defines if a background job has been generated + /// + public bool HasJob { get; init; } + + public RetentionRule() { - /// - /// The ID for the retention rule. - /// - public int ID { get; init; } + } - /// - /// Defines if a background job has been generated - /// - public bool HasJob { get; init; } - - public RetentionRule() - { - } - - public RetentionRule(OcsResponseDataEntryRetention data) - { - ID = data.ID ?? -1; - TagID = data.TagID ?? -1; - TimeUnit = (RetentionTimeUnit)(data.TimeUnit ?? 0); - TimeAmount = data.TimeAmount ?? -1; - TimeAfter = (RetentionTimeAfter)(data.TimeAfter ?? 0); - HasJob = data.HasJob ?? false; - } + public RetentionRule(OcsResponseDataEntryRetention data) + { + ID = data.ID ?? -1; + TagID = data.TagID ?? -1; + TimeUnit = (RetentionTimeUnit)(data.TimeUnit ?? 0); + TimeAmount = data.TimeAmount ?? -1; + TimeAfter = (RetentionTimeAfter)(data.TimeAfter ?? 0); + HasJob = data.HasJob ?? false; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRuleInfo.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRuleInfo.cs index 630f2bb..082a1f8 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRuleInfo.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionRuleInfo.cs @@ -1,43 +1,37 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model; + +public class RetentionRuleInfo { - public class RetentionRuleInfo + /// + /// The ID for the tag that is used for this rule. + /// + public int TagID { get; init; } + + /// + /// The unit used for the time. + /// + public RetentionTimeUnit TimeUnit { get; init; } + + /// + /// Represents numer of days/weeks/months/years. + /// + public int TimeAmount { get; init; } + + /// + /// The time used for the rule. + /// + public RetentionTimeAfter TimeAfter { get; init; } + + public OcsDataRetentionRule ToOcsData() { - /// - /// The ID for the tag that is used for this rule. - /// - public int TagID { get; init; } - - /// - /// The unit used for the time. - /// - public RetentionTimeUnit TimeUnit { get; init; } - - /// - /// Represents numer of days/weeks/months/years. - /// - public int TimeAmount { get; init; } - - /// - /// The time used for the rule. - /// - public RetentionTimeAfter TimeAfter { get; init; } - - public OcsDataRetentionRule ToOcsData() + return new OcsDataRetentionRule { - return new OcsDataRetentionRule - { - TagID = TagID, - TimeUnit = (int)TimeUnit, - TimeAmount = TimeAmount, - TimeAfter = (int)TimeAfter - }; - } + TagID = TagID, + TimeUnit = (int)TimeUnit, + TimeAmount = TimeAmount, + TimeAfter = (int)TimeAfter + }; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeAfter.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeAfter.cs index a20d65f..0cf9767 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeAfter.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeAfter.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model +public enum RetentionTimeAfter { - public enum RetentionTimeAfter - { - CreationDate, - LastAccess - } + CreationDate, + LastAccess } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeUnit.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeUnit.cs index 7ebcf9b..779e7ef 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeUnit.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Model/RetentionTimeUnit.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Model +public enum RetentionTimeUnit { - public enum RetentionTimeUnit - { - Day, - Week, - Month, - Year - } + Day, + Week, + Month, + Year } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsDataRetentionRule.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsDataRetentionRule.cs index 984dd58..fe99b2b 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsDataRetentionRule.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsDataRetentionRule.cs @@ -1,26 +1,20 @@ using Newtonsoft.Json; using Pilz.Networking.CloudProviders.Nextcloud.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs; + +public class OcsDataRetentionRule : OcsData { - public class OcsDataRetentionRule : OcsData - { - [JsonProperty("tagid")] - public int? TagID { get; set; } + [JsonProperty("tagid")] + public int? TagID { get; set; } - [JsonProperty("timeunit")] - public int? TimeUnit { get; set; } + [JsonProperty("timeunit")] + public int? TimeUnit { get; set; } - [JsonProperty("timeamount")] - public int? TimeAmount { get; set; } + [JsonProperty("timeamount")] + public int? TimeAmount { get; set; } - [JsonProperty("timeafter")] - public int? TimeAfter { get; set; } - } + [JsonProperty("timeafter")] + public int? TimeAfter { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseDataEntryRetention.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseDataEntryRetention.cs index 4d2b6c6..5f8b536 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseDataEntryRetention.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseDataEntryRetention.cs @@ -1,31 +1,25 @@ using Newtonsoft.Json; using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs; + +public class OcsResponseDataEntryRetention : OcsResponseDataEntry { - public class OcsResponseDataEntryRetention : OcsResponseDataEntry - { - [JsonProperty("id")] - public int? ID { get; set; } + [JsonProperty("id")] + public int? ID { get; set; } - [JsonProperty("tagid")] - public int? TagID { get; set; } + [JsonProperty("tagid")] + public int? TagID { get; set; } - [JsonProperty("timeunit")] - public int? TimeUnit { get; set; } + [JsonProperty("timeunit")] + public int? TimeUnit { get; set; } - [JsonProperty("timeamount")] - public int? TimeAmount { get; set; } + [JsonProperty("timeamount")] + public int? TimeAmount { get; set; } - [JsonProperty("timeafter")] - public int? TimeAfter { get; set; } + [JsonProperty("timeafter")] + public int? TimeAfter { get; set; } - [JsonProperty("hasJob")] - public bool? HasJob { get; set; } - } + [JsonProperty("hasJob")] + public bool? HasJob { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseRetention.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseRetention.cs index 4963eec..780b486 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseRetention.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/Ocs/OcsResponseRetention.cs @@ -1,14 +1,7 @@ -using Newtonsoft.Json; -using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs; + +public class OcsResponseRetention : OcsResponse> { - public class OcsResponseRetention : OcsResponse> - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/OcsApiFilesRetention.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/OcsApiFilesRetention.cs index 215c839..4ca6fc3 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/OcsApiFilesRetention.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/FileRetention/OcsApiFilesRetention.cs @@ -1,38 +1,31 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention.Ocs; using Pilz.Networking.CloudProviders.Nextcloud.Ocs; -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.FileRetention; + +public class OcsApiFilesRetention : OcsApiBase { - public class OcsApiFilesRetention : OcsApiBase + public static readonly OcsApiUrlPath OCS_FILE_RETENTION_RULES = new("/ocs/v2.php/apps/files_retention/api/v1/retentions"); + public static readonly OcsApiUrlPath OCS_FILE_RETENTION_RULE = new("/ocs/v2.php/apps/files_retention/api/v1/retentions/{0}"); + + public OcsApiFilesRetention(OcsApi manager) : base(manager) { - public static readonly OcsApiUrlPath OCS_FILE_RETENTION_RULES = new("/ocs/v2.php/apps/files_retention/api/v1/retentions"); - public static readonly OcsApiUrlPath OCS_FILE_RETENTION_RULE = new("/ocs/v2.php/apps/files_retention/api/v1/retentions/{0}"); + } - public OcsApiFilesRetention(OcsApi manager) : base(manager) - { - } + public bool CreateRetentionRule(OcsDataRetentionRule rule) + { + var response = Manager.MakeRequest(HttpMethod.Post, OCS_FILE_RETENTION_RULES, content: rule); + return response.IsSuccessStatusCode; + } - public bool CreateRetentionRule(OcsDataRetentionRule rule) - { - var response = Manager.MakeRequest(HttpMethod.Post, OCS_FILE_RETENTION_RULES, content: rule); - return response.IsSuccessStatusCode; - } + public bool DeleteRetentionRule(int ruleID) + { + var response = Manager.MakeRequest(HttpMethod.Delete, OCS_FILE_RETENTION_RULE.FillParameters(ruleID)); + return response.IsSuccessStatusCode; + } - public bool DeleteRetentionRule(int ruleID) - { - var response = Manager.MakeRequest(HttpMethod.Delete, OCS_FILE_RETENTION_RULE.FillParameters(ruleID)); - return response.IsSuccessStatusCode; - } - - public OcsResponseRetention? GetRetentionRules() - { - return Manager.MakeRequestOcs(HttpMethod.Get, OCS_FILE_RETENTION_RULES); - } + public OcsResponseRetention? GetRetentionRules() + { + return Manager.MakeRequestOcs(HttpMethod.Get, OCS_FILE_RETENTION_RULES); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Column.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Column.cs index 65921f4..1bf2c64 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Column.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Column.cs @@ -1,116 +1,110 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; + +public class Column { - public class Column + [JsonProperty("type")] + private string? type; + + [JsonProperty("subtype")] + private string? subtype; + + [JsonProperty("id")] + public long ColumnId { get; set; } + + [JsonProperty("tableId")] + public long TableId { get; set; } + + [JsonProperty("title")] + public string? Title { get; set; } + + [JsonProperty("createdBy")] + public string? CreatedBy { get; set; } + + [JsonProperty("createdAt")] + public DateTime CreatedAt { get; set; } + + [JsonProperty("lastEditBy")] + public string? LastEditBy { get; set; } + + [JsonProperty("lastEditAt")] + public DateTime LastEditAt { get; set; } + + [JsonProperty("mandatory")] + public bool Mandatory { get; set; } + + [JsonProperty("description")] + public string? Description { get; set; } + + [JsonProperty("numberDefault")] + public float? NumberDefault { get; set; } + + [JsonProperty("numberMin")] + public float? NumberMin { get; set; } + + [JsonProperty("numberMax")] + public float? NumberMax { get; set; } + + [JsonProperty("numberDecimals")] + public float NumberDecimals { get; set; } + + [JsonProperty("numberPrefix")] + public string? NumberPrefix { get; set; } + + [JsonProperty("numberSuffix")] + public string? NumberSuffix { get; set; } + + [JsonProperty("textDefault")] + public string? TextDefault { get; set; } + + [JsonProperty("textAllowedPattern")] + public string? TextAllowedPattern { get; set; } + + [JsonProperty("textMaxLength")] + public int? TextMaxLength { get; set; } + + [JsonProperty("selectionOptions")] + public List SelectionOptions { get; } = new(); + + [JsonProperty("selectionDefault")] + public int? SelectionDefault { get; set; } + + [JsonProperty("datetimeDefault")] + public DateTime? DatetimeDefault { get; set; } + + [JsonIgnore] + public ColumnType Type { - [JsonProperty("type")] - private string? type; - - [JsonProperty("subtype")] - private string? subtype; - - [JsonProperty("id")] - public long ColumnId { get; set; } - - [JsonProperty("tableId")] - public long TableId { get; set; } - - [JsonProperty("title")] - public string? Title { get; set; } - - [JsonProperty("createdBy")] - public string? CreatedBy { get; set; } - - [JsonProperty("createdAt")] - public DateTime CreatedAt { get; set; } - - [JsonProperty("lastEditBy")] - public string? LastEditBy { get; set; } - - [JsonProperty("lastEditAt")] - public DateTime LastEditAt { get; set; } - - [JsonProperty("mandatory")] - public bool Mandatory { get; set; } - - [JsonProperty("description")] - public string? Description { get; set; } - - [JsonProperty("numberDefault")] - public float? NumberDefault { get; set; } - - [JsonProperty("numberMin")] - public float? NumberMin { get; set; } - - [JsonProperty("numberMax")] - public float? NumberMax { get; set; } - - [JsonProperty("numberDecimals")] - public float NumberDecimals { get; set; } - - [JsonProperty("numberPrefix")] - public string? NumberPrefix { get; set; } - - [JsonProperty("numberSuffix")] - public string? NumberSuffix { get; set; } - - [JsonProperty("textDefault")] - public string? TextDefault { get; set; } - - [JsonProperty("textAllowedPattern")] - public string? TextAllowedPattern { get; set; } - - [JsonProperty("textMaxLength")] - public int? TextMaxLength { get; set; } - - [JsonProperty("selectionOptions")] - public List SelectionOptions { get; } = new(); - - [JsonProperty("selectionDefault")] - public int? SelectionDefault { get; set; } - - [JsonProperty("datetimeDefault")] - public DateTime? DatetimeDefault { get; set; } - - [JsonIgnore] - public ColumnType Type + get => type switch { - get => type switch - { - "text" => ColumnType.Text, - "selection" => ColumnType.Selection, - "datetime" => ColumnType.DateTime, - _ => ColumnType.Unknown, - }; - set => type = value switch - { - ColumnType.Text => "text", - ColumnType.Selection => "selection", - ColumnType.DateTime => "datetime", - _ => "text" - }; - } - - [JsonIgnore] - public ColumnSubtype Subtype + "text" => ColumnType.Text, + "selection" => ColumnType.Selection, + "datetime" => ColumnType.DateTime, + _ => ColumnType.Unknown, + }; + set => type = value switch { - get => subtype switch - { - "line" => ColumnSubtype.Line, - "" => ColumnSubtype.None, - _ => ColumnSubtype.Unknown, - }; - set => subtype = value switch - { - ColumnSubtype.Line => "line", - _ => "" - }; - } + ColumnType.Text => "text", + ColumnType.Selection => "selection", + ColumnType.DateTime => "datetime", + _ => "text" + }; + } + + [JsonIgnore] + public ColumnSubtype Subtype + { + get => subtype switch + { + "line" => ColumnSubtype.Line, + "" => ColumnSubtype.None, + _ => ColumnSubtype.Unknown, + }; + set => subtype = value switch + { + ColumnSubtype.Line => "line", + _ => "" + }; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSelectionOption.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSelectionOption.cs index f3bcc89..da7ebda 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSelectionOption.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSelectionOption.cs @@ -1,18 +1,12 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; + +public class ColumnSelectionOption { - public class ColumnSelectionOption - { - [JsonProperty("id")] - public long Id { get; set; } + [JsonProperty("id")] + public long Id { get; set; } - [JsonProperty("label")] - public string? Label { get; set; } - } + [JsonProperty("label")] + public string? Label { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSubtype.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSubtype.cs index 19a04e6..63245b2 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSubtype.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnSubtype.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +public enum ColumnSubtype { - public enum ColumnSubtype - { - None, - Unknown, - Line - } + None, + Unknown, + Line } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnType.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnType.cs index 1ec8a9b..d4f1dc3 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnType.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/ColumnType.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +public enum ColumnType { - public enum ColumnType - { - Unknown, - Text, - Selection, - DateTime - } + Unknown, + Text, + Selection, + DateTime } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Columns.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Columns.cs index 634b174..f1fd723 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Columns.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Columns.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +public class Columns : List { - public class Columns : List - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Row.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Row.cs index d1e3b13..1f72439 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Row.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Row.cs @@ -1,33 +1,27 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; + +public class Row { - public class Row - { - [JsonProperty("id")] - public long RowId { get; set; } = -1; + [JsonProperty("id")] + public long RowId { get; set; } = -1; - [JsonProperty("tableId")] - public long TableId { get; set; } = -1; + [JsonProperty("tableId")] + public long TableId { get; set; } = -1; - [JsonProperty("createdBy")] - public string? CreatedBy { get; set; } + [JsonProperty("createdBy")] + public string? CreatedBy { get; set; } - [JsonProperty("createdAt")] - public DateTime CreatedAt { get; set; } + [JsonProperty("createdAt")] + public DateTime CreatedAt { get; set; } - [JsonProperty("lastEditBy")] - public string? LastEditBy { get; set; } + [JsonProperty("lastEditBy")] + public string? LastEditBy { get; set; } - [JsonProperty("lastEditAt")] - public DateTime LastEditAt { get; set; } + [JsonProperty("lastEditAt")] + public DateTime LastEditAt { get; set; } - [JsonProperty("data")] - public List Data { get; set; } = new(); - } + [JsonProperty("data")] + public List Data { get; set; } = new(); } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowData.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowData.cs index d44ba67..df05a9e 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowData.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowData.cs @@ -1,18 +1,12 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; + +public class RowData { - public class RowData - { - [JsonProperty("columnId")] - public long ColumnId { get; set; } + [JsonProperty("columnId")] + public long ColumnId { get; set; } - [JsonProperty("value")] - public object? Value { get; set; } - } + [JsonProperty("value")] + public object? Value { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowSimple.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowSimple.cs index ed18a6c..0b810b0 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowSimple.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowSimple.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +public class RowSimple : List { - public class RowSimple : List - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowUpdate.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowUpdate.cs index b1bf35b..1e64ed0 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowUpdate.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowUpdate.cs @@ -1,15 +1,9 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; + +public class RowUpdate { - public class RowUpdate - { - [JsonProperty("data")] - public Dictionary Data { get; set; } = new(); - } + [JsonProperty("data")] + public Dictionary Data { get; set; } = new(); } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Rows.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Rows.cs index 4286dd6..334e878 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Rows.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/Rows.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +public class Rows : List { - public class Rows : List - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowsSimple.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowsSimple.cs index b11d546..cdf17de 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowsSimple.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/Model/RowsSimple.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model +public class RowsSimple : List { - public class RowsSimple : List - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/OcsApiTables.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/OcsApiTables.cs index 4d9ef31..25e7f12 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/OcsApiTables.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/OcsApiTables.cs @@ -1,86 +1,79 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; using Pilz.Networking.CloudProviders.Nextcloud.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables; + +public class OcsApiTables : OcsApiBase { - public class OcsApiTables : OcsApiBase + public static readonly OcsApiUrlPath OCS_TABLES_TABLE_ROWS = new("/apps/tables/api/1/tables/{0}/rows"); + public static readonly OcsApiUrlPath OCS_TABLES_VIEW_ROWS = new("/apps/tables/api/1/views/{0}/rows"); + public static readonly OcsApiUrlPath OCS_TABLES_TABLE_ROWS_SIMPLE = new("/apps/tables/api/1/tables/{0}/rows/simple"); + public static readonly OcsApiUrlPath OCS_TABLES_TABLE_COLUMNS = new("/apps/tables/api/1/tables/{0}/columns"); + public static readonly OcsApiUrlPath OCS_TABLES_VIEW_COLUMNS = new("/apps/tables/api/1/views/{0}/columns"); + public static readonly OcsApiUrlPath OCS_TABLES_ROW = new("/apps/tables/api/1/rows/{0}"); + public static readonly OcsApiUrlPath OCS_TABLES_COLUMN = new("/apps/tables/api/1/column/{0}"); + + public OcsApiTables(OcsApi manager) : base(manager) { - public static readonly OcsApiUrlPath OCS_TABLES_TABLE_ROWS = new("/apps/tables/api/1/tables/{0}/rows"); - public static readonly OcsApiUrlPath OCS_TABLES_VIEW_ROWS = new("/apps/tables/api/1/views/{0}/rows"); - public static readonly OcsApiUrlPath OCS_TABLES_TABLE_ROWS_SIMPLE = new("/apps/tables/api/1/tables/{0}/rows/simple"); - public static readonly OcsApiUrlPath OCS_TABLES_TABLE_COLUMNS = new("/apps/tables/api/1/tables/{0}/columns"); - public static readonly OcsApiUrlPath OCS_TABLES_VIEW_COLUMNS = new("/apps/tables/api/1/views/{0}/columns"); - public static readonly OcsApiUrlPath OCS_TABLES_ROW = new("/apps/tables/api/1/rows/{0}"); - public static readonly OcsApiUrlPath OCS_TABLES_COLUMN = new("/apps/tables/api/1/column/{0}"); + } - public OcsApiTables(OcsApi manager) : base(manager) - { - } + public RowsSimple? GetRowsSimple(long tableId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_TABLE_ROWS_SIMPLE.FillParameters(tableId)); + } - public RowsSimple? GetRowsSimple(long tableId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_TABLE_ROWS_SIMPLE.FillParameters(tableId)); - } + public Rows? GetRows(long tableId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_TABLE_ROWS.FillParameters(tableId)); + } - public Rows? GetRows(long tableId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_TABLE_ROWS.FillParameters(tableId)); - } + public Rows? GetViewRows(long viewId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_VIEW_ROWS.FillParameters(viewId)); + } - public Rows? GetViewRows(long viewId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_VIEW_ROWS.FillParameters(viewId)); - } + public Row? GetRow(long rowId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_ROW.FillParameters(rowId)); + } - public Row? GetRow(long rowId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_ROW.FillParameters(rowId)); - } + public Columns? GetColumns(long tableId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_TABLE_COLUMNS.FillParameters(tableId)); + } - public Columns? GetColumns(long tableId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_TABLE_COLUMNS.FillParameters(tableId)); - } + public Columns? GetViewColumns(long viewId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_VIEW_COLUMNS.FillParameters(viewId)); + } - public Columns? GetViewColumns(long viewId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_VIEW_COLUMNS.FillParameters(viewId)); - } + public Column? GetColumn(long columnId) + { + return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_COLUMN.FillParameters(columnId)); + } - public Column? GetColumn(long columnId) - { - return Manager.MakeRequest(HttpMethod.Get, OCS_TABLES_COLUMN.FillParameters(columnId)); - } + public Row? DeleteRow(long rowId) + { + return Manager.MakeRequest(HttpMethod.Delete, OCS_TABLES_ROW.FillParameters(rowId)); + } - public Row? DeleteRow(long rowId) - { - return Manager.MakeRequest(HttpMethod.Delete, OCS_TABLES_ROW.FillParameters(rowId)); - } + public Column? DeleteColumn(long columnId) + { + return Manager.MakeRequest(HttpMethod.Delete, OCS_TABLES_COLUMN.FillParameters(columnId)); + } - public Column? DeleteColumn(long columnId) - { - return Manager.MakeRequest(HttpMethod.Delete, OCS_TABLES_COLUMN.FillParameters(columnId)); - } + public Row? UpdateRow(long rowId, RowUpdate values) + { + return Manager.MakeRequest(HttpMethod.Put, OCS_TABLES_ROW.FillParameters(rowId), content: values); + } - public Row? UpdateRow(long rowId, RowUpdate values) - { - return Manager.MakeRequest(HttpMethod.Put, OCS_TABLES_ROW.FillParameters(rowId), content: values); - } + public Row? CreateRow(long tableId, RowUpdate values) + { + return Manager.MakeRequest(HttpMethod.Post, OCS_TABLES_TABLE_ROWS.FillParameters(tableId), content: values); + } - public Row? CreateRow(long tableId, RowUpdate values) - { - return Manager.MakeRequest(HttpMethod.Post, OCS_TABLES_TABLE_ROWS.FillParameters(tableId), content: values); - } - - public Row? CreateViewRow(long viewId, RowUpdate values) - { - return Manager.MakeRequest(HttpMethod.Post, OCS_TABLES_VIEW_ROWS.FillParameters(viewId), content: values); - } + public Row? CreateViewRow(long viewId, RowUpdate values) + { + return Manager.MakeRequest(HttpMethod.Post, OCS_TABLES_VIEW_ROWS.FillParameters(viewId), content: values); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/TablesClient.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/TablesClient.cs index 8d84dee..6282bd8 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/TablesClient.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Apps/Tables/TablesClient.cs @@ -1,81 +1,75 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables; + +public class TablesClient : ClientBase { - public class TablesClient : ClientBase + public TablesClient(NextcloudClient client) : base(client) { - public TablesClient(NextcloudClient client) : base(client) - { - } + } - public RowsSimple? GetRowsSimple(long tableId) - { - return Client.Ocs.GetApi().GetRowsSimple(tableId); - } + public RowsSimple? GetRowsSimple(long tableId) + { + return Client.Ocs.GetApi().GetRowsSimple(tableId); + } - public Rows? GetRows(long tableId) - { - return Client.Ocs.GetApi().GetRows(tableId); - } + public Rows? GetRows(long tableId) + { + return Client.Ocs.GetApi().GetRows(tableId); + } - public Rows? GetViewRows(long viewId) - { - return Client.Ocs.GetApi().GetViewRows(viewId); - } + public Rows? GetViewRows(long viewId) + { + return Client.Ocs.GetApi().GetViewRows(viewId); + } - public Row? GetRow(long rowId) - { - return Client.Ocs.GetApi().GetRow(rowId); - } + public Row? GetRow(long rowId) + { + return Client.Ocs.GetApi().GetRow(rowId); + } - public Columns? GetColumns(long tableId) - { - return Client.Ocs.GetApi().GetColumns(tableId); - } + public Columns? GetColumns(long tableId) + { + return Client.Ocs.GetApi().GetColumns(tableId); + } - public Columns? GetViewColumns(long viewId) - { - return Client.Ocs.GetApi().GetViewColumns(viewId); - } + public Columns? GetViewColumns(long viewId) + { + return Client.Ocs.GetApi().GetViewColumns(viewId); + } - public Column? GetColumn(long columnId) - { - return Client.Ocs.GetApi().GetColumn(columnId); - } + public Column? GetColumn(long columnId) + { + return Client.Ocs.GetApi().GetColumn(columnId); + } - public bool DeleteRow(long rowId) - { - return DeleteRowAdv(rowId) is not null; - } + public bool DeleteRow(long rowId) + { + return DeleteRowAdv(rowId) is not null; + } - public Row? DeleteRowAdv(long rowId) - { - return Client.Ocs.GetApi().DeleteRow(rowId); - } + public Row? DeleteRowAdv(long rowId) + { + return Client.Ocs.GetApi().DeleteRow(rowId); + } - public bool DeleteColumn(long columnId) - { - return DeleteColumnAdv(columnId) is not null; - } + public bool DeleteColumn(long columnId) + { + return DeleteColumnAdv(columnId) is not null; + } - public Column? DeleteColumnAdv(long columnId) - { - return Client.Ocs.GetApi().DeleteColumn(columnId); - } + public Column? DeleteColumnAdv(long columnId) + { + return Client.Ocs.GetApi().DeleteColumn(columnId); + } - public Row? UpdateRow(long rowId, RowUpdate values) - { - return Client.Ocs.GetApi().UpdateRow(rowId, values); - } + public Row? UpdateRow(long rowId, RowUpdate values) + { + return Client.Ocs.GetApi().UpdateRow(rowId, values); + } - public Row? CreateRow(long tableId, RowUpdate values) - { - return Client.Ocs.GetApi().CreateRow(tableId, values); - } + public Row? CreateRow(long tableId, RowUpdate values) + { + return Client.Ocs.GetApi().CreateRow(tableId, values); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/ClientBase.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/ClientBase.cs index 059170c..36f4d26 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/ClientBase.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/ClientBase.cs @@ -1,20 +1,22 @@ -using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables; -using Pilz.Networking.CloudProviders.Nextcloud.Client.Apps.Tables.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client; + +/* Nicht gemergte Änderung aus Projekt "Pilz.Networking.CloudProviders.Nextcloud (net6.0)" +Vor: namespace Pilz.Networking.CloudProviders.Nextcloud.Client { public abstract class ClientBase - { - protected NextcloudClient Client { get; init; } +Nach: +namespace Pilz.Networking.CloudProviders.Nextcloud.Client; - protected ClientBase(NextcloudClient client) - { - Client = client; - } +public abstract class ClientBase +*/ +public abstract class ClientBase +{ + protected NextcloudClient Client { get; init; } + + protected ClientBase(NextcloudClient client) + { + Client = client; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/CloudClient.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/CloudClient.cs index bd61ecf..a3496f6 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/CloudClient.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/CloudClient.cs @@ -1,34 +1,28 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud; + +public class CloudClient : ClientBase { - public class CloudClient : ClientBase + public CloudClient(NextcloudClient client) : base(client) { - public CloudClient(NextcloudClient client) : base(client) - { - } - - public UserInfo? GetUserInfo() - { - if (!string.IsNullOrEmpty(Client.CurrentLogin?.LoginName)) - return GetUserInfo(Client.CurrentLogin.LoginName); - else - return null; - } - - public UserInfo? GetUserInfo(string username) - { - var result = Client.Ocs.Cloud.GetUserMeta(username); - - if (result?.Data != null) - return new UserInfo(result.Data); + } + public UserInfo? GetUserInfo() + { + if (!string.IsNullOrEmpty(Client.CurrentLogin?.LoginName)) + return GetUserInfo(Client.CurrentLogin.LoginName); + else return null; - } + } + + public UserInfo? GetUserInfo(string username) + { + var result = Client.Ocs.Cloud.GetUserMeta(username); + + if (result?.Data != null) + return new UserInfo(result.Data); + + return null; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserBackendCapabilities.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserBackendCapabilities.cs index 54cf4d0..4477461 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserBackendCapabilities.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserBackendCapabilities.cs @@ -1,22 +1,14 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model +public class UserBackendCapabilities { - public class UserBackendCapabilities - { - /// - /// Defines if the display name can be changed. - /// - public bool SetDisplayName { get; set; } + /// + /// Defines if the display name can be changed. + /// + public bool SetDisplayName { get; set; } - /// - /// Defines if the password can be changed. - /// - public bool SetPassword { get; set; } - } + /// + /// Defines if the password can be changed. + /// + public bool SetPassword { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserInfo.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserInfo.cs index 7a7d1a8..2a2c232 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserInfo.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserInfo.cs @@ -1,131 +1,125 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model; + +public class UserInfo { - public class UserInfo + /// + /// Defines if the user is enabled. + /// + public bool Enabled { get; init; } + + /// + /// The location of the user's storage directory. + /// + public string? StorageLocation { get; init; } + + /// + /// The uniquie user id that infos are for. + /// + public string? ID { get; init; } + + /// + /// The last time when the user has logged in to its account. + /// + public DateTime LastLogin { get; init; } + + /// + /// The backend of the user. Common values are "Database" or "LDAP". + /// + public string? Backend { get; init; } + + /// + /// The Email address of the user. + /// + public string? Email { get; init; } + + /// + /// The displayname of the user. + /// + public string? Displayname { get; init; } + + /// + /// The displayname of the user. + /// + public string? Displayname2 { get; init; } + + /// + /// The phone number of the user. + /// + public string? Phone { get; init; } + + /// + /// The address of the user. + /// + public string? Address { get; init; } + + /// + /// The Website of the user. + /// + public string? Website { get; init; } + + /// + /// The twitter profile name of the user. + /// + public string? Twitter { get; init; } + + /// + /// Defines the groups the user is member of. + /// + public string[] Groups { get; init; } + + /// + /// The configured language of the user. + /// + public string? Language { get; init; } + + /// + /// The configured location of the user. + /// + public string? Locale { get; init; } + + /// + /// Quota informations for the user. + /// + public UserQuota Quota { get; } = new(); + + /// + /// Backend capabilities of the user. + /// + public UserBackendCapabilities BackendCapabilities { get; } = new(); + + public UserInfo(OcsResponseDataUser responseData) { - /// - /// Defines if the user is enabled. - /// - public bool Enabled { get; init; } + Enabled = Convert.ToBoolean(responseData.Enabled); + StorageLocation = responseData.StorageLocation; + ID = responseData.ID; + LastLogin = responseData.LastLogin.UnixTimeMillisecondsToDateTime(); + Backend = responseData.Backend; + Email = responseData.Email; + Displayname = responseData.Displayname; + Displayname2 = responseData.Displayname2; + Phone = responseData.Phone; + Address = responseData.Address; + Website = responseData.Website; + Twitter = responseData.Twitter; + Groups = responseData.Groups ?? Array.Empty(); + Language = responseData.Language; + Locale = responseData.Locale; - /// - /// The location of the user's storage directory. - /// - public string? StorageLocation { get; init; } - - /// - /// The uniquie user id that infos are for. - /// - public string? ID { get; init; } - - /// - /// The last time when the user has logged in to its account. - /// - public DateTime LastLogin { get; init; } - - /// - /// The backend of the user. Common values are "Database" or "LDAP". - /// - public string? Backend { get; init; } - - /// - /// The Email address of the user. - /// - public string? Email { get; init; } - - /// - /// The displayname of the user. - /// - public string? Displayname { get; init; } - - /// - /// The displayname of the user. - /// - public string? Displayname2 { get; init; } - - /// - /// The phone number of the user. - /// - public string? Phone { get; init; } - - /// - /// The address of the user. - /// - public string? Address { get; init; } - - /// - /// The Website of the user. - /// - public string? Website { get; init; } - - /// - /// The twitter profile name of the user. - /// - public string? Twitter { get; init; } - - /// - /// Defines the groups the user is member of. - /// - public string[] Groups { get; init; } - - /// - /// The configured language of the user. - /// - public string? Language { get; init; } - - /// - /// The configured location of the user. - /// - public string? Locale { get; init; } - - /// - /// Quota informations for the user. - /// - public UserQuota Quota { get; } = new(); - - /// - /// Backend capabilities of the user. - /// - public UserBackendCapabilities BackendCapabilities { get; } = new(); - - public UserInfo(OcsResponseDataUser responseData) + if (responseData.Quota != null) { - Enabled = Convert.ToBoolean(responseData.Enabled); - StorageLocation = responseData.StorageLocation; - ID = responseData.ID; - LastLogin = responseData.LastLogin.UnixTimeMillisecondsToDateTime(); - Backend = responseData.Backend; - Email = responseData.Email; - Displayname = responseData.Displayname; - Displayname2 = responseData.Displayname2; - Phone = responseData.Phone; - Address = responseData.Address; - Website = responseData.Website; - Twitter = responseData.Twitter; - Groups = responseData.Groups ?? Array.Empty(); - Language = responseData.Language; - Locale = responseData.Locale; + Quota.Free = responseData.Quota.Free ?? 0; + Quota.Used = responseData.Quota.Used ?? 0; + Quota.Total = responseData.Quota.Total ?? 0; + Quota.Relative = responseData.Quota.Relative ?? 0.0F; + Quota.Quota = responseData.Quota.Quota ?? 0; + } - if (responseData.Quota != null) - { - Quota.Free = responseData.Quota.Free ?? 0; - Quota.Used = responseData.Quota.Used ?? 0; - Quota.Total = responseData.Quota.Total ?? 0; - Quota.Relative = responseData.Quota.Relative ?? 0.0F; - Quota.Quota = responseData.Quota.Quota ?? 0; - } - - if (responseData.BackendCapabilities != null) - { - BackendCapabilities.SetDisplayName = Convert.ToBoolean(responseData.BackendCapabilities.SetDisplayName); - BackendCapabilities.SetPassword = Convert.ToBoolean(responseData.BackendCapabilities.SetPassword); - } + if (responseData.BackendCapabilities != null) + { + BackendCapabilities.SetDisplayName = Convert.ToBoolean(responseData.BackendCapabilities.SetDisplayName); + BackendCapabilities.SetPassword = Convert.ToBoolean(responseData.BackendCapabilities.SetPassword); } } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserQuota.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserQuota.cs index 930e4d5..49fa91a 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserQuota.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Model/UserQuota.cs @@ -1,37 +1,29 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model +public class UserQuota { - public class UserQuota - { - /// - /// Amount of free bytes left. - /// - public long Free { get; set; } + /// + /// Amount of free bytes left. + /// + public long Free { get; set; } - /// - /// Amount of already used bytes. - /// - public long Used { get; set; } + /// + /// Amount of already used bytes. + /// + public long Used { get; set; } - /// - /// Total amount of all bytes (free + used). - /// - public long Total { get; set; } + /// + /// Total amount of all bytes (free + used). + /// + public long Total { get; set; } - /// - /// Relative amount of used quota in percent. - /// - public float Relative { get; set; } + /// + /// Relative amount of used quota in percent. + /// + public float Relative { get; set; } - /// - /// Total amount of bytes available. - /// - public long Quota { get; set; } - } + /// + /// Total amount of bytes available. + /// + public long Quota { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseDataUser.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseDataUser.cs index df7d602..c30cb0b 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseDataUser.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseDataUser.cs @@ -1,91 +1,85 @@ using Newtonsoft.Json; using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Ocs; + +public class OcsResponseDataUser : OcsResponseData { - public class OcsResponseDataUser : OcsResponseData + public class ResponseQuota { - public class ResponseQuota - { - [JsonProperty("free")] - public long? Free { get; set; } + [JsonProperty("free")] + public long? Free { get; set; } - [JsonProperty("used")] - public long? Used { get; set; } + [JsonProperty("used")] + public long? Used { get; set; } - [JsonProperty("total")] - public long? Total { get; set; } + [JsonProperty("total")] + public long? Total { get; set; } - [JsonProperty("relative")] - public float? Relative { get; set; } - - [JsonProperty("quota")] - public long? Quota { get; set; } - } - - public class ResponseBackendCapabilities - { - [JsonProperty("setDisplayName")] - public bool? SetDisplayName { get; set; } - - [JsonProperty("setPassword")] - public bool? SetPassword { get; set; } - } - - [JsonProperty("enabled")] - public bool? Enabled { get; set; } - - [JsonProperty("storageLocation")] - public string? StorageLocation { get; set; } - - [JsonProperty("id")] - public string? ID { get; set; } - - [JsonProperty("lastLogin")] - public long? LastLogin { get; set; } - - [JsonProperty("backend")] - public string? Backend { get; set; } + [JsonProperty("relative")] + public float? Relative { get; set; } [JsonProperty("quota")] - public ResponseQuota? Quota { get; set; } - - [JsonProperty("email")] - public string? Email { get; set; } - - [JsonProperty("displayname")] - public string? Displayname { get; set; } - - [JsonProperty("display-name")] - public string? Displayname2 { get; set; } - - [JsonProperty("phone")] - public string? Phone { get; set; } - - [JsonProperty("address")] - public string? Address { get; set; } - - [JsonProperty("website")] - public string? Website { get; set; } - - [JsonProperty("twitter")] - public string? Twitter { get; set; } - - [JsonProperty("groups")] - public string[]? Groups { get; set; } - - [JsonProperty("language")] - public string? Language { get; set; } - - [JsonProperty("locale")] - public string? Locale { get; set; } - - [JsonProperty("backendCapabilities")] - public ResponseBackendCapabilities? BackendCapabilities { get; set; } + public long? Quota { get; set; } } + + public class ResponseBackendCapabilities + { + [JsonProperty("setDisplayName")] + public bool? SetDisplayName { get; set; } + + [JsonProperty("setPassword")] + public bool? SetPassword { get; set; } + } + + [JsonProperty("enabled")] + public bool? Enabled { get; set; } + + [JsonProperty("storageLocation")] + public string? StorageLocation { get; set; } + + [JsonProperty("id")] + public string? ID { get; set; } + + [JsonProperty("lastLogin")] + public long? LastLogin { get; set; } + + [JsonProperty("backend")] + public string? Backend { get; set; } + + [JsonProperty("quota")] + public ResponseQuota? Quota { get; set; } + + [JsonProperty("email")] + public string? Email { get; set; } + + [JsonProperty("displayname")] + public string? Displayname { get; set; } + + [JsonProperty("display-name")] + public string? Displayname2 { get; set; } + + [JsonProperty("phone")] + public string? Phone { get; set; } + + [JsonProperty("address")] + public string? Address { get; set; } + + [JsonProperty("website")] + public string? Website { get; set; } + + [JsonProperty("twitter")] + public string? Twitter { get; set; } + + [JsonProperty("groups")] + public string[]? Groups { get; set; } + + [JsonProperty("language")] + public string? Language { get; set; } + + [JsonProperty("locale")] + public string? Locale { get; set; } + + [JsonProperty("backendCapabilities")] + public ResponseBackendCapabilities? BackendCapabilities { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseUser.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseUser.cs index 61a5d25..3bd5030 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseUser.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/Ocs/OcsResponseUser.cs @@ -1,14 +1,7 @@ -using Newtonsoft.Json; -using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Ocs; + +public class OcsResponseUser : OcsResponse { - public class OcsResponseUser : OcsResponse - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/OcsApiCloud.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/OcsApiCloud.cs index 010f279..de67e63 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/OcsApiCloud.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Cloud/OcsApiCloud.cs @@ -1,24 +1,18 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Ocs; using Pilz.Networking.CloudProviders.Nextcloud.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud; + +public class OcsApiCloud : OcsApiBase { - public class OcsApiCloud : OcsApiBase + public readonly static OcsApiUrlPath OCS_CLOUD_USER_METADATA = new("/ocs/v1.php/cloud/users/{0}"); + + public OcsApiCloud(OcsApi manager) : base(manager) { - public readonly static OcsApiUrlPath OCS_CLOUD_USER_METADATA = new("/ocs/v1.php/cloud/users/{0}"); + } - public OcsApiCloud(OcsApi manager) : base(manager) - { - } - - public OcsResponseUser? GetUserMeta(string username) - { - return Manager.MakeRequestOcs(HttpMethod.Get, OCS_CLOUD_USER_METADATA.FillParameters(username)); - } + public OcsResponseUser? GetUserMeta(string username) + { + return Manager.MakeRequestOcs(HttpMethod.Get, OCS_CLOUD_USER_METADATA.FillParameters(username)); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/Core/OcsApiCore.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/Core/OcsApiCore.cs index d12215c..41cc33d 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/Core/OcsApiCore.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/Core/OcsApiCore.cs @@ -1,24 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; + +/* Nicht gemergte Änderung aus Projekt "Pilz.Networking.CloudProviders.Nextcloud (net6.0)" +Vor: +using System; +Nach: +using Pilz.Networking.CloudProviders.Nextcloud.Ocs; +using System; +*/ +using +/* Nicht gemergte Änderung aus Projekt "Pilz.Networking.CloudProviders.Nextcloud (net6.0)" +Vor: using System.Threading.Tasks; using Pilz.Networking.CloudProviders.Nextcloud.Ocs; +Nach: +using System.Threading.Tasks; +*/ +Pilz.Networking.CloudProviders.Nextcloud.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Core +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.Core; + +public class OcsApiCore : OcsApiBase { - public class OcsApiCore : OcsApiBase + public static readonly OcsApiUrlPath OCS_CORE_APPPASSWORD = "/ocs/v2.php/core/apppassword"; + + public OcsApiCore(OcsApi manager) : base(manager) { - public static readonly OcsApiUrlPath OCS_CORE_APPPASSWORD = "/ocs/v2.php/core/apppassword"; + } - public OcsApiCore(OcsApi manager) : base(manager) - { - } - - public bool DeleteAppPassword() - { - using var msg = Manager.MakeRequest(HttpMethod.Delete, OCS_CORE_APPPASSWORD); - return msg != null && msg.IsSuccessStatusCode; - } + public bool DeleteAppPassword() + { + using var msg = Manager.MakeRequest(HttpMethod.Delete, OCS_CORE_APPPASSWORD); + return msg != null && msg.IsSuccessStatusCode; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2.cs index 9f8f39b..b3cdc4d 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2.cs @@ -1,40 +1,34 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; + +public class OcsResponseLoginFlowV2 { - public class OcsResponseLoginFlowV2 + public class PollData { - public class PollData - { - /// - /// The login token that has been created for the login process. - /// It can be used to poll the login state. - /// - [JsonProperty("token")] - public string? Token { get; set; } - - /// - /// - /// - [JsonProperty("endpoint")] - public string? Endpoint { get; set; } - } + /// + /// The login token that has been created for the login process. + /// It can be used to poll the login state. + /// + [JsonProperty("token")] + public string? Token { get; set; } /// /// /// - [JsonProperty("poll")] - public PollData? Poll { get; set; } - - /// - /// The temporary login url that should be used for login. - /// - [JsonProperty("login")] - public string? LoginUrl { get; set; } + [JsonProperty("endpoint")] + public string? Endpoint { get; set; } } + + /// + /// + /// + [JsonProperty("poll")] + public PollData? Poll { get; set; } + + /// + /// The temporary login url that should be used for login. + /// + [JsonProperty("login")] + public string? LoginUrl { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2Credentials.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2Credentials.cs index ae019cf..cc32e86 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2Credentials.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/Ocs/OcsResponseLoginFlowV2Credentials.cs @@ -1,30 +1,24 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; + +public class OcsResponseLoginFlowV2Credentials { - public class OcsResponseLoginFlowV2Credentials - { - /// - /// The server url the login credentials are for. - /// - [JsonProperty("server")] - public string? Server { get; set; } + /// + /// The server url the login credentials are for. + /// + [JsonProperty("server")] + public string? Server { get; set; } - /// - /// The login name (username or password) used for the login. - /// - [JsonProperty("loginName")] - public string? LoginName { get; set; } + /// + /// The login name (username or password) used for the login. + /// + [JsonProperty("loginName")] + public string? LoginName { get; set; } - /// - /// The app password that has been generated. - /// - [JsonProperty("appPassword")] - public string? AppPassword { get; set; } - } + /// + /// The app password that has been generated. + /// + [JsonProperty("appPassword")] + public string? AppPassword { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/OcsApiLoginFlowV2.cs b/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/OcsApiLoginFlowV2.cs index bcff514..2d6ed78 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/OcsApiLoginFlowV2.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Client/LoginFlowV2/OcsApiLoginFlowV2.cs @@ -1,36 +1,30 @@ using Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; using Pilz.Networking.CloudProviders.Nextcloud.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2 +namespace Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2; + +public class OcsApiLoginFlowV2 : OcsApiBase { - public class OcsApiLoginFlowV2 : OcsApiBase + private const string OCS_LOGIN_INIT = "/index.php/login/v2"; + + public OcsApiLoginFlowV2(OcsApi manager) : base(manager) { - private const string OCS_LOGIN_INIT = "/index.php/login/v2"; + } - public OcsApiLoginFlowV2(OcsApi manager) : base(manager) - { - } + public OcsResponseLoginFlowV2? Init(string url) + { + return Manager.MakeRequest(HttpMethod.Post, url + OCS_LOGIN_INIT); + } - public OcsResponseLoginFlowV2? Init(string url) - { - return Manager.MakeRequest(HttpMethod.Post, url + OCS_LOGIN_INIT); - } + public OcsResponseLoginFlowV2Credentials? Poll(OcsResponseLoginFlowV2.PollData poll) + { + ArgumentNullException.ThrowIfNull(poll?.Endpoint); + ArgumentNullException.ThrowIfNull(poll?.Token); - public OcsResponseLoginFlowV2Credentials? Poll(OcsResponseLoginFlowV2.PollData poll) - { - ArgumentNullException.ThrowIfNull(poll?.Endpoint); - ArgumentNullException.ThrowIfNull(poll?.Token); - - return Manager.MakeRequest(HttpMethod.Post, poll.Endpoint, - parameters: new Dictionary - { - { "token", poll.Token } - }); - } + return Manager.MakeRequest(HttpMethod.Post, poll.Endpoint, + parameters: new Dictionary + { + { "token", poll.Token } + }); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/Extensions.cs b/Pilz.Networking.CloudProviders.Nextcloud/Extensions.cs index dc687b4..5e85fa7 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/Extensions.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/Extensions.cs @@ -1,46 +1,41 @@ using Pilz.Networking.CloudProviders.Nextcloud.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud +namespace Pilz.Networking.CloudProviders.Nextcloud; + +public static class Extensions { - public static class Extensions + public static string ToBasicAuth(this OcsApiAuthCredentials? credentials) { - public static string ToBasicAuth(this OcsApiAuthCredentials? credentials) + if (credentials != null) { - if (credentials != null) - { - var creds = $"{credentials?.LoginName}:{credentials?.AppPassword}"; - var bytes = Encoding.UTF8.GetBytes(creds); - return "Basic " + Convert.ToBase64String(bytes); - } - - return string.Empty; + var creds = $"{credentials?.LoginName}:{credentials?.AppPassword}"; + var bytes = Encoding.UTF8.GetBytes(creds); + return "Basic " + Convert.ToBase64String(bytes); } - public static OcsApiAuthCredentials? ToOcsApiAuthCredentials(this NextcloudLogin? login) - { - if (!string.IsNullOrEmpty(login?.LoginName) && !string.IsNullOrEmpty(login?.AppPassword)) - return new OcsApiAuthCredentials(login.LoginName, login.AppPassword); - return null; - } + return string.Empty; + } - public static OcsApiUrlPath FillParameters(this OcsApiUrlPath path, params object?[] @params) - { - return (OcsApiUrlPath)string.Format(path, @params); - } + public static OcsApiAuthCredentials? ToOcsApiAuthCredentials(this NextcloudLogin? login) + { + if (!string.IsNullOrEmpty(login?.LoginName) && !string.IsNullOrEmpty(login?.AppPassword)) + return new OcsApiAuthCredentials(login.LoginName, login.AppPassword); + return null; + } - public static DateTime UnixTimeMillisecondsToDateTime(this long? value) - { - return DateTimeOffset.FromUnixTimeMilliseconds(value ?? 0).DateTime; - } + public static OcsApiUrlPath FillParameters(this OcsApiUrlPath path, params object?[] @params) + { + return (OcsApiUrlPath)string.Format(path, @params); + } - public static long ToUnixTimeMilliseconds(this DateTime value) - { - return new DateTimeOffset(value).ToUnixTimeMilliseconds(); - } + public static DateTime UnixTimeMillisecondsToDateTime(this long? value) + { + return DateTimeOffset.FromUnixTimeMilliseconds(value ?? 0).DateTime; + } + + public static long ToUnixTimeMilliseconds(this DateTime value) + { + return new DateTimeOffset(value).ToUnixTimeMilliseconds(); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/NextcloudClient.cs b/Pilz.Networking.CloudProviders.Nextcloud/NextcloudClient.cs index 6920d05..0defd4f 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/NextcloudClient.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/NextcloudClient.cs @@ -1,4 +1,14 @@ -using System; +using Pilz.Networking.CloudProviders.Nextcloud.Client; +using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud; +using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model; +using Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; + +/* Nicht gemergte Änderung aus Projekt "Pilz.Networking.CloudProviders.Nextcloud (net6.0)" +Vor: +using Pilz.Networking.CloudProviders.Nextcloud.Ocs; +Nach: +using Pilz.Networking.CloudProviders.Nextcloud.Ocs; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; @@ -6,150 +16,147 @@ using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; -using Pilz.Networking.CloudProviders.Nextcloud.Client; -using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud; -using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud.Model; -using Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; +*/ using Pilz.Networking.CloudProviders.Nextcloud.Ocs; +using System.Diagnostics; -namespace Pilz.Networking.CloudProviders.Nextcloud +namespace Pilz.Networking.CloudProviders.Nextcloud; + +public class NextcloudClient : IDisposable { - public class NextcloudClient : IDisposable + private readonly List clients = new(); + private NextcloudLogin? currentLogin; + + public OcsApi Ocs { get; init; } = new(); + + public NextcloudLogin? CurrentLogin { - private readonly List clients = new(); - private NextcloudLogin? currentLogin; - - public OcsApi Ocs { get; init; } = new(); - - public NextcloudLogin? CurrentLogin + get => currentLogin; + private set { - get => currentLogin; - private set - { - currentLogin = value; - Ocs.BaseUrl = value?.Server ?? string.Empty; - } - } - - public CloudClient Cloud => GetClient(); - - public NextcloudClient() - { - Ocs.GetOcsApiAuthCredentails += Ocs_GetOcsApiAuthCredentails; - } - - private void Ocs_GetOcsApiAuthCredentails(object sender, GetOcsApiAuthCredentailsEventArgs eventArgs) - { - if (sender == Ocs) - eventArgs.Credentials = CurrentLogin.ToOcsApiAuthCredentials(); - } - - public TClient GetClient() where TClient : ClientBase - { - var instance = TryGetClient(); - return instance is null ? throw new NullReferenceException() : instance; - } - - public TClient? TryGetClient() where TClient : ClientBase - { - TClient? instance = (TClient?)clients.FirstOrDefault(n => n is TClient); - - instance ??= (TClient?)Activator.CreateInstance(typeof(TClient), new object[] { this }); - - if (instance is not null) - clients.Add(instance); - - return instance; - } - - public UserInfo? Login(NextcloudLogin login) - { - return Login(login, true); - } - - public UserInfo? Login(NextcloudLogin login, bool checkUser) - { - // Ensure we are logged out - Logout(false); - - // Temporary set user login - CurrentLogin = login; - - if (checkUser) - { - // Try get user info & check if user is enabled - var userInfo = Cloud.GetUserInfo(); - var isValid = userInfo != null /*&& userInfo.Enabled*/; // Enabled is false for some (new) users but they still are able to login?? - - // If invalid, reset login credentials - if (!isValid) - CurrentLogin = null; - - return userInfo; - } - - return null; - } - - public NextcloudLogin? Login(string baseUrl, CancellationToken cancellationToken) - { - // Ensure we are logged out - Logout(false); - - // Init the login process - var initResponse = Ocs.LoginFlowV2.Init(baseUrl); - - if (!string.IsNullOrEmpty(initResponse?.LoginUrl) && initResponse.Poll != null) - { - // Open the browser - Process.Start(new ProcessStartInfo - { - FileName = initResponse.LoginUrl, - UseShellExecute = true - }); - - // Poll for credentails in intervals - OcsResponseLoginFlowV2Credentials? pollResponse = null; - while (!cancellationToken.IsCancellationRequested && pollResponse is null) - { - // Wait 5 seconds - Thread.Sleep(5000); - - // Poll the credentials - if (!cancellationToken.IsCancellationRequested) - pollResponse = Ocs.LoginFlowV2.Poll(initResponse.Poll); - } - - // Check login credentials - if (pollResponse is not null) - CurrentLogin = new(pollResponse); - } - - return CurrentLogin; - } - - public void Logout() - { - Logout(false); - } - - public void Logout(bool logoutOnServer) - { - if (CurrentLogin != null) - { - // Delete currently used app password - if (logoutOnServer) - Ocs.Core.DeleteAppPassword(); - - // Reset current login infos - CurrentLogin = null; - } - } - - public void Dispose() - { - Ocs.Dispose(); - GC.SuppressFinalize(this); + currentLogin = value; + Ocs.BaseUrl = value?.Server ?? string.Empty; } } + + public CloudClient Cloud => GetClient(); + + public NextcloudClient() + { + Ocs.GetOcsApiAuthCredentails += Ocs_GetOcsApiAuthCredentails; + } + + private void Ocs_GetOcsApiAuthCredentails(object sender, GetOcsApiAuthCredentailsEventArgs eventArgs) + { + if (sender == Ocs) + eventArgs.Credentials = CurrentLogin.ToOcsApiAuthCredentials(); + } + + public TClient GetClient() where TClient : ClientBase + { + var instance = TryGetClient(); + return instance is null ? throw new NullReferenceException() : instance; + } + + public TClient? TryGetClient() where TClient : ClientBase + { + TClient? instance = (TClient?)clients.FirstOrDefault(n => n is TClient); + + instance ??= (TClient?)Activator.CreateInstance(typeof(TClient), new object[] { this }); + + if (instance is not null) + clients.Add(instance); + + return instance; + } + + public UserInfo? Login(NextcloudLogin login) + { + return Login(login, true); + } + + public UserInfo? Login(NextcloudLogin login, bool checkUser) + { + // Ensure we are logged out + Logout(false); + + // Temporary set user login + CurrentLogin = login; + + if (checkUser) + { + // Try get user info & check if user is enabled + var userInfo = Cloud.GetUserInfo(); + var isValid = userInfo != null /*&& userInfo.Enabled*/; // Enabled is false for some (new) users but they still are able to login?? + + // If invalid, reset login credentials + if (!isValid) + CurrentLogin = null; + + return userInfo; + } + + return null; + } + + public NextcloudLogin? Login(string baseUrl, CancellationToken cancellationToken) + { + // Ensure we are logged out + Logout(false); + + // Init the login process + var initResponse = Ocs.LoginFlowV2.Init(baseUrl); + + if (!string.IsNullOrEmpty(initResponse?.LoginUrl) && initResponse.Poll != null) + { + // Open the browser + Process.Start(new ProcessStartInfo + { + FileName = initResponse.LoginUrl, + UseShellExecute = true + }); + + // Poll for credentails in intervals + OcsResponseLoginFlowV2Credentials? pollResponse = null; + while (!cancellationToken.IsCancellationRequested && pollResponse is null) + { + // Wait 5 seconds + Thread.Sleep(5000); + + // Poll the credentials + if (!cancellationToken.IsCancellationRequested) + pollResponse = Ocs.LoginFlowV2.Poll(initResponse.Poll); + } + + // Check login credentials + if (pollResponse is not null) + CurrentLogin = new(pollResponse); + } + + return CurrentLogin; + } + + public void Logout() + { + Logout(false); + } + + public void Logout(bool logoutOnServer) + { + if (CurrentLogin != null) + { + // Delete currently used app password + if (logoutOnServer) + Ocs.Core.DeleteAppPassword(); + + // Reset current login infos + CurrentLogin = null; + } + } + + public void Dispose() + { + Ocs.Dispose(); + GC.SuppressFinalize(this); + } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/NextcloudLogin.cs b/Pilz.Networking.CloudProviders.Nextcloud/NextcloudLogin.cs index 8e1a8b8..f84c8ad 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/NextcloudLogin.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/NextcloudLogin.cs @@ -1,39 +1,32 @@ -using Newtonsoft.Json; -using Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud +namespace Pilz.Networking.CloudProviders.Nextcloud; + +public class NextcloudLogin { - public class NextcloudLogin + /// + /// The server url the login credentials are for. + /// + public string? Server { get; set; } + + /// + /// The login name (username or password) used for the login. + /// + public string? LoginName { get; set; } + + /// + /// The app password that has been generated. + /// + public string? AppPassword { get; set; } + + public NextcloudLogin() { - /// - /// The server url the login credentials are for. - /// - public string? Server { get; set; } + } - /// - /// The login name (username or password) used for the login. - /// - public string? LoginName { get; set; } - - /// - /// The app password that has been generated. - /// - public string? AppPassword { get; set; } - - public NextcloudLogin() - { - } - - public NextcloudLogin(OcsResponseLoginFlowV2Credentials response) - { - Server = response.Server; - LoginName = response.LoginName; - AppPassword = response.AppPassword; - } + public NextcloudLogin(OcsResponseLoginFlowV2Credentials response) + { + Server = response.Server; + LoginName = response.LoginName; + AppPassword = response.AppPassword; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/GetOcsApiAuthCredentailsEventArgs.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/GetOcsApiAuthCredentailsEventArgs.cs index 6b4af7f..57549d4 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/GetOcsApiAuthCredentailsEventArgs.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/GetOcsApiAuthCredentailsEventArgs.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +public delegate void GetOcsApiAuthCredentailsEventHandler(object sender, GetOcsApiAuthCredentailsEventArgs eventArgs); + +public class GetOcsApiAuthCredentailsEventArgs : EventArgs { - public delegate void GetOcsApiAuthCredentailsEventHandler(object sender, GetOcsApiAuthCredentailsEventArgs eventArgs); - - public class GetOcsApiAuthCredentailsEventArgs : EventArgs - { - public OcsApiAuthCredentials? Credentials { get; set; } - } + public OcsApiAuthCredentials? Credentials { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApi.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApi.cs index 406aef2..0837d32 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApi.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApi.cs @@ -1,218 +1,226 @@ -using System; +/* Nicht gemergte Änderung aus Projekt "Pilz.Networking.CloudProviders.Nextcloud (net6.0)" +Vor: +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http.Headers; using Newtonsoft.Json; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; -using System.Xml.Linq; +Nach: +using Newtonsoft.Json; using Pilz.Networking.CloudProviders.Nextcloud.Client.Cloud; using Pilz.Networking.CloudProviders.Nextcloud.Client.Core; using Pilz.Networking.CloudProviders.Nextcloud.Client.LoginFlowV2; using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; +using System; +using System.Json; +*/ -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +/* Nicht gemergte Änderung aus Projekt "Pilz.Networking.CloudProviders.Nextcloud (net6.0)" +Vor: +using +Nach: +using +*/ +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; + +public class OcsApi : IDisposable { - public class OcsApi : IDisposable + public const string CONTENT_TYPE_JSON = "application/json"; + + public event GetOcsApiAuthCredentailsEventHandler? GetOcsApiAuthCredentails; + + private readonly HttpClient client = new(); + private readonly List apis = new(); + + public string BaseUrl { get; set; } = string.Empty; + + public OcsApiLoginFlowV2 LoginFlowV2 => GetApi(); + public OcsApiCore Core => GetApi(); + public OcsApiCloud Cloud => GetApi(); + + public TApi GetApi() where TApi : OcsApiBase { - public const string CONTENT_TYPE_JSON = "application/json"; + var instance = TryGetApi(); + return instance is null ? throw new NullReferenceException() : instance; + } - public event GetOcsApiAuthCredentailsEventHandler? GetOcsApiAuthCredentails; + public TApi? TryGetApi() where TApi : OcsApiBase + { + TApi? instance = (TApi?)apis.FirstOrDefault(n => n is TApi); - private readonly HttpClient client = new(); - private readonly List apis = new(); + instance ??= (TApi?)Activator.CreateInstance(typeof(TApi), new object[] { this }); - public string BaseUrl { get; set; } = string.Empty; + if (instance is not null) + apis.Add(instance); - public OcsApiLoginFlowV2 LoginFlowV2 => GetApi(); - public OcsApiCore Core => GetApi(); - public OcsApiCloud Cloud => GetApi(); + return instance; + } - public TApi GetApi() where TApi : OcsApiBase + public string BuildFullUrl(OcsApiUrlPath path) + { + return BaseUrl + path; + } + + /// + /// Makes an request with the given arguments and deserialize it to the given type. + /// + /// + /// + /// + /// + /// + /// + /// Returns the given OcsResponse type from the deserialized OcsApiResponse content. + public TResponse? MakeRequestOcs(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) where TResponse : IOcsResponse + { + return MakeRequestOcs(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters, content: content); + } + + /// + /// Makes an request with the given arguments and deserialize it to the given type. + /// + /// + /// + /// + /// + /// + /// + /// Returns the given OcsResponse type from the deserialized OcsApiResponse content. + public TResponse? MakeRequestOcs(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) where TResponse : IOcsResponse + { + var response = MakeRequest?>(httpMethod, url, useAuthentication: useAuthentication, parameters: parameters, content: content); + + if (response != null) + return response.Ocs; + + return default; + } + + /// + /// Makes an request with the given arguments and deserialize it to the given type. + /// + /// + /// + /// + /// + /// + /// + /// Returns the deserialized content of type given type. + public TResponse? MakeRequest(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) + { + return MakeRequest(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters, content: content); + } + + /// + /// Makes an request with the given arguments and deserialize it to the given type. + /// + /// + /// + /// + /// + /// + /// + /// Returns the deserialized content of type given type. + public TResponse? MakeRequest(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) + { + using var responseInit = MakeRequest(httpMethod, url, useAuthentication: useAuthentication, parameters: parameters, content: content); + + if (responseInit != null) { - var instance = TryGetApi(); - return instance is null ? throw new NullReferenceException() : instance; - } - - public TApi? TryGetApi() where TApi : OcsApiBase - { - TApi? instance = (TApi?)apis.FirstOrDefault(n => n is TApi); - - instance ??= (TApi?)Activator.CreateInstance(typeof(TApi), new object[] { this }); - - if (instance is not null) - apis.Add(instance); - - return instance; - } - - public string BuildFullUrl(OcsApiUrlPath path) - { - return BaseUrl + path; - } - - /// - /// Makes an request with the given arguments and deserialize it to the given type. - /// - /// - /// - /// - /// - /// - /// - /// Returns the given OcsResponse type from the deserialized OcsApiResponse content. - public TResponse? MakeRequestOcs(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) where TResponse : IOcsResponse - { - return MakeRequestOcs(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters, content: content); - } - - /// - /// Makes an request with the given arguments and deserialize it to the given type. - /// - /// - /// - /// - /// - /// - /// - /// Returns the given OcsResponse type from the deserialized OcsApiResponse content. - public TResponse? MakeRequestOcs(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) where TResponse : IOcsResponse - { - var response = MakeRequest?>(httpMethod, url, useAuthentication: useAuthentication, parameters: parameters, content: content); - - if (response != null) - return response.Ocs; - - return default; - } - - /// - /// Makes an request with the given arguments and deserialize it to the given type. - /// - /// - /// - /// - /// - /// - /// - /// Returns the deserialized content of type given type. - public TResponse? MakeRequest(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) - { - return MakeRequest(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters, content: content); - } - - /// - /// Makes an request with the given arguments and deserialize it to the given type. - /// - /// - /// - /// - /// - /// - /// - /// Returns the deserialized content of type given type. - public TResponse? MakeRequest(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) - { - using var responseInit = MakeRequest(httpMethod, url, useAuthentication: useAuthentication, parameters: parameters, content: content); - - if (responseInit != null) + try { - try - { - var bodyInit = responseInit.Content.ReadAsStringAsync().Result; - return JsonConvert.DeserializeObject(bodyInit); - } - catch(FormatException) { } - catch(JsonSerializationException) { } + var bodyInit = responseInit.Content.ReadAsStringAsync().Result; + return JsonConvert.DeserializeObject(bodyInit); } - - return default; + catch (FormatException) { } + catch (JsonSerializationException) { } } - /// - /// Makes an request with the given arguments. - /// - /// - /// - /// - /// - /// - /// Returns a HttpResponseMessage as result. - public HttpResponseMessage MakeRequest(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) + return default; + } + + /// + /// Makes an request with the given arguments. + /// + /// + /// + /// + /// + /// + /// Returns a HttpResponseMessage as result. + public HttpResponseMessage MakeRequest(HttpMethod httpMethod, OcsApiUrlPath url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) + { + return MakeRequest(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters, content: content); + } + + /// + /// Makes an request with the given arguments. + /// + /// + /// + /// + /// + /// + /// Returns a HttpResponseMessage as result. + public HttpResponseMessage MakeRequest(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) + { + OcsApiAuthCredentials? authentication; + string @params; + HttpContent? httpContent; + + // Get authentication + if (useAuthentication) { - return MakeRequest(httpMethod, BuildFullUrl(url), useAuthentication: useAuthentication, parameters: parameters, content: content); + var args = new GetOcsApiAuthCredentailsEventArgs(); + GetOcsApiAuthCredentails?.Invoke(this, args); + authentication = args.Credentials; } + else + authentication = null; - /// - /// Makes an request with the given arguments. - /// - /// - /// - /// - /// - /// - /// Returns a HttpResponseMessage as result. - public HttpResponseMessage MakeRequest(HttpMethod httpMethod, string url, bool useAuthentication = true, Dictionary? parameters = null, object? content = null) + // Parse params + if (parameters != null) + @params = "?" + string.Join("&", parameters.Select(p => $"{p.Key}={p.Value}")); + else + @params = string.Empty; + + // Create content + if (content is HttpContent contentHttp) + httpContent = contentHttp; + else if (content is OcsData || content is not null) { - OcsApiAuthCredentials? authentication; - string @params; - HttpContent? httpContent; - - // Get authentication - if (useAuthentication) - { - var args = new GetOcsApiAuthCredentailsEventArgs(); - GetOcsApiAuthCredentails?.Invoke(this, args); - authentication = args.Credentials; - } - else - authentication = null; - - // Parse params - if (parameters != null) - @params = "?" + string.Join("&", parameters.Select(p => $"{p.Key}={p.Value}")); - else - @params = string.Empty; - - // Create content - if (content is HttpContent contentHttp) - httpContent = contentHttp; - else if (content is OcsData || content is not null) - { - var stringContent = JsonConvert.SerializeObject(content); - httpContent = new StringContent(stringContent, null, CONTENT_TYPE_JSON); - } - else - httpContent = null; - - // Send request - var request = new HttpRequestMessage - { - Method = httpMethod ?? HttpMethod.Post, - RequestUri = new Uri(url + @params), - Headers = - { - { "Accept", CONTENT_TYPE_JSON }, - { "OCS-APIREQUEST", "true" }, - //{ "Authorization", authentication.ToBasicAuth() } - }, - Content = httpContent - }; - - // Add authorization - if (authentication != null) - request.Headers.Add("Authorization", authentication.ToBasicAuth()); - - return client.Send(request); + var stringContent = JsonConvert.SerializeObject(content); + httpContent = new StringContent(stringContent, null, CONTENT_TYPE_JSON); } + else + httpContent = null; - public void Dispose() + // Send request + var request = new HttpRequestMessage { - client.Dispose(); - GC.SuppressFinalize(this); - } + Method = httpMethod ?? HttpMethod.Post, + RequestUri = new Uri(url + @params), + Headers = + { + { "Accept", CONTENT_TYPE_JSON }, + { "OCS-APIREQUEST", "true" }, + //{ "Authorization", authentication.ToBasicAuth() } + }, + Content = httpContent + }; + + // Add authorization + if (authentication != null) + request.Headers.Add("Authorization", authentication.ToBasicAuth()); + + return client.Send(request); + } + + public void Dispose() + { + client.Dispose(); + GC.SuppressFinalize(this); } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiAuthCredentials.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiAuthCredentials.cs index da69b65..fd2591d 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiAuthCredentials.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiAuthCredentials.cs @@ -1,21 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection.Emit; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +public struct OcsApiAuthCredentials { - public struct OcsApiAuthCredentials - { - public string LoginName { get; set; } - public string AppPassword { get; set; } + public string LoginName { get; set; } + public string AppPassword { get; set; } - public OcsApiAuthCredentials(string loginName, string appPassword) - { - LoginName = loginName; - AppPassword = appPassword; - } + public OcsApiAuthCredentials(string loginName, string appPassword) + { + LoginName = loginName; + AppPassword = appPassword; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiBase.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiBase.cs index e5c8bf4..06c8cc5 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiBase.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiBase.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +public abstract class OcsApiBase { - public abstract class OcsApiBase - { - protected OcsApi Manager { get; init; } + protected OcsApi Manager { get; init; } - protected OcsApiBase(OcsApi manager) - { - Manager = manager; - } + protected OcsApiBase(OcsApi manager) + { + Manager = manager; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiResponse.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiResponse.cs index 39f7457..cd80b26 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiResponse.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiResponse.cs @@ -1,17 +1,10 @@ using Newtonsoft.Json; using Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Linq; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; + +public class OcsApiResponse where TOcsResponse : IOcsResponse { - public class OcsApiResponse where TOcsResponse : IOcsResponse - { - [JsonProperty("ocs")] - public TOcsResponse? Ocs { get; set; } - } + [JsonProperty("ocs")] + public TOcsResponse? Ocs { get; set; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiUrlPath.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiUrlPath.cs index faf93e7..6f37463 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiUrlPath.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsApiUrlPath.cs @@ -1,31 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +public readonly struct OcsApiUrlPath { - public readonly struct OcsApiUrlPath + private readonly string path; + + public OcsApiUrlPath() { - private readonly string path; + path = string.Empty; + } - public OcsApiUrlPath() - { - path = string.Empty; - } + public OcsApiUrlPath(string path) + { + this.path = path; + } - public OcsApiUrlPath(string path) - { - this.path = path; - } + public static implicit operator string(OcsApiUrlPath o) => o.path; + public static implicit operator OcsApiUrlPath(string o) => new(o); - public static implicit operator string(OcsApiUrlPath o) => o.path; - public static implicit operator OcsApiUrlPath(string o) => new(o); - - public override readonly string ToString() - { - return path; - } + public override readonly string ToString() + { + return path; } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsData.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsData.cs index c07230c..1493df6 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsData.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/OcsData.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs +public class OcsData { - public class OcsData - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponse.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponse.cs index de4ef76..f30b1ee 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponse.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponse.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +public interface IOcsResponse { - public interface IOcsResponse - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseData.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseData.cs index fab075f..bb9a2a1 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseData.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseData.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +public interface IOcsResponseData { - public interface IOcsResponseData - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseMeta.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseMeta.cs index af9dda6..d7052ee 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseMeta.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/IOcsResponseMeta.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +public interface IOcsResponseMeta { - public interface IOcsResponseMeta - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponse.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponse.cs index f0a44a3..7d237f8 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponse.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponse.cs @@ -1,26 +1,20 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; + +public class OcsResponse : IOcsResponse where TMeta : IOcsResponseMeta where TData : IOcsResponseData { - public class OcsResponse : IOcsResponse where TMeta : IOcsResponseMeta where TData : IOcsResponseData - { - [JsonProperty("meta")] - public TMeta? Meta { get; set; } + [JsonProperty("meta")] + public TMeta? Meta { get; set; } - [JsonProperty("data")] - public TData? Data { get; set; } - } - - public class OcsResponse : OcsResponse where TData : IOcsResponseData - { - } - - public class OcsResponse : OcsResponse - { - } + [JsonProperty("data")] + public TData? Data { get; set; } +} + +public class OcsResponse : OcsResponse where TData : IOcsResponseData +{ +} + +public class OcsResponse : OcsResponse +{ } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseData.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseData.cs index 8aaf5e1..73ad990 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseData.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseData.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +public class OcsResponseData : IOcsResponseData { - public class OcsResponseData : IOcsResponseData - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataArray.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataArray.cs index 7cfbb52..e9cdb7a 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataArray.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataArray.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +public class OcsResponseDataArray : List, IOcsResponseData where TEntry : OcsResponseDataEntry { - public class OcsResponseDataArray : List, IOcsResponseData where TEntry : OcsResponseDataEntry - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataEntry.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataEntry.cs index 551babf..f54cb6a 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataEntry.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseDataEntry.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +public class OcsResponseDataEntry { - public class OcsResponseDataEntry - { - } } diff --git a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseMeta.cs b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseMeta.cs index 32f01da..4563745 100644 --- a/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseMeta.cs +++ b/Pilz.Networking.CloudProviders.Nextcloud/OCS/Responses/OcsResponseMeta.cs @@ -1,21 +1,15 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses +namespace Pilz.Networking.CloudProviders.Nextcloud.Ocs.Responses; + +public class OcsResponseMeta : IOcsResponseMeta { - public class OcsResponseMeta : IOcsResponseMeta - { - [JsonProperty("status")] - public string? Status { get; set; } + [JsonProperty("status")] + public string? Status { get; set; } - [JsonProperty("statuscode")] - public int? StatusCode { get; set; } + [JsonProperty("statuscode")] + public int? StatusCode { get; set; } - [JsonProperty("message")] - public string? Message { get; set; } - } + [JsonProperty("message")] + public string? Message { get; set; } } diff --git a/Pilz.Networking/ConnectionManagerBase.vb b/Pilz.Networking/ConnectionManagerBase.vb index ae1f7b1..87c5088 100644 --- a/Pilz.Networking/ConnectionManagerBase.vb +++ b/Pilz.Networking/ConnectionManagerBase.vb @@ -1,5 +1,6 @@ Imports System.IO Imports System.Net + Imports Newtonsoft.Json.Linq Public MustInherit Class ConnectionManagerBase diff --git a/Pilz.Networking/TCPManager.vb b/Pilz.Networking/TCPManager.vb index 801dcf9..96f2bed 100644 --- a/Pilz.Networking/TCPManager.vb +++ b/Pilz.Networking/TCPManager.vb @@ -1,8 +1,14 @@ -Imports System.IO -Imports System.Net -Imports System.Net.NetworkInformation +Imports System.Net + +' Nicht gemergte Änderung aus Projekt "Pilz.Networking (net8.0-windows)" +' Vor: +' Imports System.Net.Sockets +' Imports Newtonsoft.Json.Linq +' Nach: +' Imports System.Net.Sockets +' +' Imports Newtonsoft.Json.Linq Imports System.Net.Sockets -Imports Newtonsoft.Json.Linq Public Class TCPManager Inherits ConnectionManagerBase diff --git a/Pilz.Networking/UDPManager.vb b/Pilz.Networking/UDPManager.vb index 99dba2e..ecc5da1 100644 --- a/Pilz.Networking/UDPManager.vb +++ b/Pilz.Networking/UDPManager.vb @@ -1,9 +1,15 @@ -Imports System.IO -Imports System.Net -Imports System.Net.NetworkInformation +Imports System.Net Imports System.Net.Sockets + +' Nicht gemergte Änderung aus Projekt "Pilz.Networking (net8.0-windows)" +' Vor: +' Imports System.Threading +' Imports Newtonsoft.Json.Linq +' Nach: +' Imports System.Threading +' +' Imports Newtonsoft.Json.Linq Imports System.Threading -Imports Newtonsoft.Json.Linq Public Class UDPManager Inherits ConnectionManagerBase diff --git a/Pilz.Plugins.Advanced.UI.Telerik/Extensions.cs b/Pilz.Plugins.Advanced.UI.Telerik/Extensions.cs index ecc0448..50d2dde 100644 --- a/Pilz.Plugins.Advanced.UI.Telerik/Extensions.cs +++ b/Pilz.Plugins.Advanced.UI.Telerik/Extensions.cs @@ -1,125 +1,121 @@ -using System.Drawing; -using System.Reflection; -using Telerik.WinControls; -using Telerik.WinControls.Elements; +using Telerik.WinControls; using Telerik.WinControls.UI; -namespace Pilz.Plugins.Advanced.UI.Telerik +namespace Pilz.Plugins.Advanced.UI.Telerik; + +public static class Extensions { - public static class Extensions + public static Icon? ToIcon(this Image image) { - public static Icon? ToIcon(this Image image) - { - if (image is Bitmap bitmap) - return Icon.FromHandle(bitmap.GetHicon()); - return null; - } + if (image is Bitmap bitmap) + return Icon.FromHandle(bitmap.GetHicon()); + return null; + } - public static RadMenuItem GetAsItem(this PluginModuleBase module) - { - return GetAsItem(module, true); - } + public static RadMenuItem GetAsItem(this PluginModuleBase module) + { + return GetAsItem(module, true); + } - public static RadMenuItem GetAsItem(this PluginModuleBase module, bool addDefaultHandler) - { - return GetAsItem(module, addDefaultHandler ? RadMenuItem_RMMethod_Click : null); - } + public static RadMenuItem GetAsItem(this PluginModuleBase module, bool addDefaultHandler) + { + return GetAsItem(module, addDefaultHandler ? RadMenuItem_RMMethod_Click : null); + } - public static RadMenuItem GetAsItem(this PluginFunction function) - { - return GetAsItem(function, true); - } + public static RadMenuItem GetAsItem(this PluginFunction function) + { + return GetAsItem(function, true); + } - public static RadMenuItem GetAsItem(this PluginFunction function, bool addDefaultHandler) - { - return GetAsItem(function, addDefaultHandler ? RadMenuItem_RMFunction_Click : null); - } + public static RadMenuItem GetAsItem(this PluginFunction function, bool addDefaultHandler) + { + return GetAsItem(function, addDefaultHandler ? RadMenuItem_RMFunction_Click : null); + } - public static RadMenuItem GetAsItem(this PluginFeature module, EventHandler? clickHandler) + public static RadMenuItem GetAsItem(this PluginFeature module, EventHandler? clickHandler) + { + var item = new RadMenuItem { - var item = new RadMenuItem + Text = module.Name, + Image = module.Icon as Image, + SvgImage = module.Icon as RadSvgImage, + Tag = module, + Visibility = module.Enabled ? ElementVisibility.Visible : ElementVisibility.Collapsed + }; + + if (clickHandler is not null) + item.Click += clickHandler; + + return item; + } + + /// + /// Inserts all items to an item collection. + /// + /// + /// Examples:
+ /// -
+ /// -
+ /// -
+ /// -
+ /// -
+ /// Will add a default click handler that executes the feature.
+ /// You usually don't set customClickHandler if you set this parameter to . + /// Adds a custom click handler. If addDefaultHandler is true, it will only work on s.
+ /// You usually don't set addDefaultHandler to true if you set this parameter to something not null. + public static void InsertItemsTo(this IEnumerable features, RadItemOwnerCollection itemsCollection, bool addDefaultHandler = false, EventHandler? customClickHandler = null, FeatureInsertMode insertMode = FeatureInsertMode.Default, int? customDefault = null, int? customTop = null, int? customBottom = null, FeatureInsertPosition insertSplitter = FeatureInsertPosition.None) + { + var insertDefault = customDefault ?? (insertMode.HasFlag(FeatureInsertMode.DefaultStart) ? 0 : itemsCollection.Count); + var insertTop = customTop ?? (insertMode.HasFlag(FeatureInsertMode.InsertTop) || insertMode.HasFlag(FeatureInsertMode.DefaultStart) ? 0 : insertDefault); + var insertBottom = customBottom ?? (insertMode.HasFlag(FeatureInsertMode.InsertBottom) || insertMode.HasFlag(FeatureInsertMode.DefaultEnd) ? itemsCollection.Count : insertDefault); + + foreach (var feature in features) + { + RadMenuItem item; + + if (feature is PluginFunction function) + item = function.GetAsItem(addDefaultHandler); + else if (feature is PluginModuleBase module) + item = module.GetAsItem(addDefaultHandler); + else + item = feature.GetAsItem(null); + + if (!addDefaultHandler && customClickHandler != null) + item.Click += customClickHandler; + + switch (feature.Prioritization) { - Text = module.Name, - Image = module.Icon as Image, - SvgImage = module.Icon as RadSvgImage, - Tag = module, - Visibility = module.Enabled ? ElementVisibility.Visible : ElementVisibility.Collapsed - }; - - if (clickHandler is not null) - item.Click += clickHandler; - - return item; - } - - /// - /// Inserts all items to an item collection. - /// - /// - /// Examples:
- /// -
- /// -
- /// -
- /// -
- /// -
- /// Will add a default click handler that executes the feature.
- /// You usually don't set customClickHandler if you set this parameter to . - /// Adds a custom click handler. If addDefaultHandler is true, it will only work on s.
- /// You usually don't set addDefaultHandler to true if you set this parameter to something not null. - public static void InsertItemsTo(this IEnumerable features, RadItemOwnerCollection itemsCollection, bool addDefaultHandler = false, EventHandler? customClickHandler = null, FeatureInsertMode insertMode = FeatureInsertMode.Default, int? customDefault = null, int? customTop = null, int? customBottom = null, FeatureInsertPosition insertSplitter = FeatureInsertPosition.None) - { - var insertDefault = customDefault ?? (insertMode.HasFlag(FeatureInsertMode.DefaultStart) ? 0 : itemsCollection.Count); - var insertTop = customTop ?? (insertMode.HasFlag(FeatureInsertMode.InsertTop) || insertMode.HasFlag(FeatureInsertMode.DefaultStart) ? 0 : insertDefault); - var insertBottom = customBottom ?? (insertMode.HasFlag(FeatureInsertMode.InsertBottom) || insertMode.HasFlag(FeatureInsertMode.DefaultEnd) ? itemsCollection.Count : insertDefault); - - foreach (var feature in features) - { - RadMenuItem item; - - if (feature is PluginFunction function) - item = function.GetAsItem(addDefaultHandler); - else if (feature is PluginModuleBase module) - item = module.GetAsItem(addDefaultHandler); - else - item = feature.GetAsItem(null); - - if (!addDefaultHandler && customClickHandler != null) - item.Click += customClickHandler; - - switch (feature.Prioritization) - { - case FeaturePrioritization.High: - if (insertDefault >= insertTop) insertDefault++; - if (insertBottom >= insertTop) insertBottom++; - // ... - itemsCollection.Insert(insertTop++, item); - break; - case FeaturePrioritization.Default: - if (insertBottom >= insertDefault) insertBottom++; - if (insertTop >= insertDefault) insertTop++; - // ... - itemsCollection.Insert(insertDefault++, item); - break; - case FeaturePrioritization.Low: - if (insertTop >= insertBottom) insertTop++; - if (insertDefault >= insertBottom) insertDefault++; - // ... - itemsCollection.Insert(insertBottom++, item); - break; - } + case FeaturePrioritization.High: + if (insertDefault >= insertTop) insertDefault++; + if (insertBottom >= insertTop) insertBottom++; + // ... + itemsCollection.Insert(insertTop++, item); + break; + case FeaturePrioritization.Default: + if (insertBottom >= insertDefault) insertBottom++; + if (insertTop >= insertDefault) insertTop++; + // ... + itemsCollection.Insert(insertDefault++, item); + break; + case FeaturePrioritization.Low: + if (insertTop >= insertBottom) insertTop++; + if (insertDefault >= insertBottom) insertDefault++; + // ... + itemsCollection.Insert(insertBottom++, item); + break; } } + } - private static void RadMenuItem_RMMethod_Click(object? sender, EventArgs e) - { - if (sender is RadMenuItem item && item.Tag is PluginModule function) - function.ShowUI(); - } + private static void RadMenuItem_RMMethod_Click(object? sender, EventArgs e) + { + if (sender is RadMenuItem item && item.Tag is PluginModule function) + function.ShowUI(); + } - private static void RadMenuItem_RMFunction_Click(object? sender, EventArgs e) - { - if (sender is RadMenuItem item && item.Tag is PluginFunction function) - function.Execute(); - } + private static void RadMenuItem_RMFunction_Click(object? sender, EventArgs e) + { + if (sender is RadMenuItem item && item.Tag is PluginFunction function) + function.Execute(); } } \ No newline at end of file diff --git a/Pilz.Plugins.Advanced.UI.Telerik/PluginModule.cs b/Pilz.Plugins.Advanced.UI.Telerik/PluginModule.cs index f3c26c1..5744df1 100644 --- a/Pilz.Plugins.Advanced.UI.Telerik/PluginModule.cs +++ b/Pilz.Plugins.Advanced.UI.Telerik/PluginModule.cs @@ -1,39 +1,35 @@ -using Pilz.Plugins.Advanced.UI; -using Pilz.UI.Telerik; +using Pilz.UI.Telerik; using Pilz.UI.Telerik.Dialogs; -using System.Drawing; -using System.Windows.Forms; using Telerik.WinControls; -namespace Pilz.Plugins.Advanced.UI.Telerik +namespace Pilz.Plugins.Advanced.UI.Telerik; + +public abstract class PluginModule : PluginModule { - public abstract class PluginModule : PluginModule + /// + /// Wrapper for the property to directly use it as . + /// + public RadSvgImage? SvgImage { - /// - /// Wrapper for the property to directly use it as . - /// - public RadSvgImage? SvgImage - { - get => base.Icon as RadSvgImage; - set => base.Icon = value; - } + get => base.Icon as RadSvgImage; + set => base.Icon = value; + } - protected PluginModule(string moduleType, string moduleIdentifier) : base(moduleType, moduleIdentifier) - { + protected PluginModule(string moduleType, string moduleIdentifier) : base(moduleType, moduleIdentifier) + { - } + } - protected PluginModule(string moduleType, string moduleIdentifier, string moduleName) : base(moduleType, moduleIdentifier, moduleName) - { - } + protected PluginModule(string moduleType, string moduleIdentifier, string moduleName) : base(moduleType, moduleIdentifier, moduleName) + { + } - public override void ShowUI() + public override void ShowUI() + { + if (CreateNewUI() is PluginModuleUI ui) { - if (CreateNewUI() is PluginModuleUI ui) - { - ui.BackColor = Color.Transparent; - DialogBase.Show(ui, Name!, SvgImage!.ToImage().ToIcon()!); - } + ui.BackColor = Color.Transparent; + DialogBase.Show(ui, Name!, SvgImage!.ToImage().ToIcon()!); } } } \ No newline at end of file diff --git a/Pilz.Plugins.Advanced.UI.Telerik/PluginModuleUI.cs b/Pilz.Plugins.Advanced.UI.Telerik/PluginModuleUI.cs index 7af7482..53f83ca 100644 --- a/Pilz.Plugins.Advanced.UI.Telerik/PluginModuleUI.cs +++ b/Pilz.Plugins.Advanced.UI.Telerik/PluginModuleUI.cs @@ -1,22 +1,15 @@ using Pilz.UI.Telerik.Dialogs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -namespace Pilz.Plugins.Advanced.UI.Telerik +namespace Pilz.Plugins.Advanced.UI.Telerik; + +public class PluginModuleUI : FlyoutBase, ILoadContent { - public class PluginModuleUI : FlyoutBase, ILoadContent + public PluginModuleUI() { - public PluginModuleUI() - { - ActionPanelVisible = false; - } + ActionPanelVisible = false; + } - public virtual void LoadContent() - { - } + public virtual void LoadContent() + { } } diff --git a/Pilz.Plugins.Advanced.UI/FeatureInsertMode.cs b/Pilz.Plugins.Advanced.UI/FeatureInsertMode.cs index 7aae2a6..f7fb3fd 100644 --- a/Pilz.Plugins.Advanced.UI/FeatureInsertMode.cs +++ b/Pilz.Plugins.Advanced.UI/FeatureInsertMode.cs @@ -1,39 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced.UI; -namespace Pilz.Plugins.Advanced.UI +[Flags] +public enum FeatureInsertMode { - [Flags] - public enum FeatureInsertMode - { - /// - /// Features will be inserted at the end of the collection. - /// - Default = 0, - /// - /// Features will be inserted at the end of the collection. - /// This is the default behavior and equals . Will only be used if not set . - /// - DefaultEnd = Default, - /// - /// Features will be inserted at the start of the collection. - /// Will only be used if not set . - /// - DefaultStart = 1, - /// - /// Features with prioritization will be inserted at the top (or left). - /// - InsertTop = 1 << 2, - /// - /// Features with prioritization will be inserted at the bottom (or right). - /// - InsertBottom = 1 << 3, - /// - /// Features with prioritization other then will be inserted at the top or bottom. - /// - InsertTopAndBottom = InsertTop | InsertBottom, - } + /// + /// Features will be inserted at the end of the collection. + /// + Default = 0, + /// + /// Features will be inserted at the end of the collection. + /// This is the default behavior and equals . Will only be used if not set . + /// + DefaultEnd = Default, + /// + /// Features will be inserted at the start of the collection. + /// Will only be used if not set . + /// + DefaultStart = 1, + /// + /// Features with prioritization will be inserted at the top (or left). + /// + InsertTop = 1 << 2, + /// + /// Features with prioritization will be inserted at the bottom (or right). + /// + InsertBottom = 1 << 3, + /// + /// Features with prioritization other then will be inserted at the top or bottom. + /// + InsertTopAndBottom = InsertTop | InsertBottom, } diff --git a/Pilz.Plugins.Advanced.UI/FeatureInsertPosition.cs b/Pilz.Plugins.Advanced.UI/FeatureInsertPosition.cs index e45a0df..19a4394 100644 --- a/Pilz.Plugins.Advanced.UI/FeatureInsertPosition.cs +++ b/Pilz.Plugins.Advanced.UI/FeatureInsertPosition.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced.UI; -namespace Pilz.Plugins.Advanced.UI +[Flags] +public enum FeatureInsertPosition { - [Flags] - public enum FeatureInsertPosition - { - None = 0, - Default = 1, - Top = 2, - Bottom = 3, - } + None = 0, + Default = 1, + Top = 2, + Bottom = 3, } diff --git a/Pilz.Plugins.Advanced.UI/PluginModule.cs b/Pilz.Plugins.Advanced.UI/PluginModule.cs index 7990af4..178e96f 100644 --- a/Pilz.Plugins.Advanced.UI/PluginModule.cs +++ b/Pilz.Plugins.Advanced.UI/PluginModule.cs @@ -1,48 +1,44 @@ -using System.Drawing; -using System.Windows.Forms; +namespace Pilz.Plugins.Advanced.UI; -namespace Pilz.Plugins.Advanced.UI +public abstract class PluginModule : PluginModuleBase where TPluginModuleUI : Control { - public abstract class PluginModule : PluginModuleBase where TPluginModuleUI : Control + public delegate void PluginModuleUIEventHandler(PluginModuleBase module, TPluginModuleUI ui); + + /// + /// Fires when a instance has been created. + /// + public static event PluginModuleUIEventHandler? OnUICreated; + + public bool Visible { get; set; } = true; + public bool AllowEmbedding { get; set; } = true; + + /// + /// Wrapper for the property to directly use it as . + /// + public Image? Image { - public delegate void PluginModuleUIEventHandler(PluginModuleBase module, TPluginModuleUI ui); - - /// - /// Fires when a instance has been created. - /// - public static event PluginModuleUIEventHandler? OnUICreated; - - public bool Visible { get; set; } = true; - public bool AllowEmbedding { get; set; } = true; - - /// - /// Wrapper for the property to directly use it as . - /// - public Image? Image - { - get => base.Icon as Image; - set => base.Icon = value; - } - - protected PluginModule(string moduleType, string moduleIdentifier) : base(moduleType, moduleIdentifier) - { - } - - protected PluginModule(string moduleType, string moduleIdentifier, string moduleName) : base(moduleType, moduleIdentifier, moduleName) - { - } - - public virtual void ShowUI() - { - } - - public virtual TPluginModuleUI CreateUI() - { - var ui = CreateNewUI(); - OnUICreated?.Invoke(this, ui); - return ui; - } - - protected abstract TPluginModuleUI CreateNewUI(); + get => base.Icon as Image; + set => base.Icon = value; } + + protected PluginModule(string moduleType, string moduleIdentifier) : base(moduleType, moduleIdentifier) + { + } + + protected PluginModule(string moduleType, string moduleIdentifier, string moduleName) : base(moduleType, moduleIdentifier, moduleName) + { + } + + public virtual void ShowUI() + { + } + + public virtual TPluginModuleUI CreateUI() + { + var ui = CreateNewUI(); + OnUICreated?.Invoke(this, ui); + return ui; + } + + protected abstract TPluginModuleUI CreateNewUI(); } \ No newline at end of file diff --git a/Pilz.Plugins.Advanced/FeaturePrioritization.cs b/Pilz.Plugins.Advanced/FeaturePrioritization.cs index a38bbc0..28ef367 100644 --- a/Pilz.Plugins.Advanced/FeaturePrioritization.cs +++ b/Pilz.Plugins.Advanced/FeaturePrioritization.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public enum FeaturePrioritization { - public enum FeaturePrioritization - { - Low = -1, - Default = 0, - High = 1, - } + Low = -1, + Default = 0, + High = 1, } diff --git a/Pilz.Plugins.Advanced/IPluginFeatureProvider.cs b/Pilz.Plugins.Advanced/IPluginFeatureProvider.cs index f7446d9..8e35415 100644 --- a/Pilz.Plugins.Advanced/IPluginFeatureProvider.cs +++ b/Pilz.Plugins.Advanced/IPluginFeatureProvider.cs @@ -1,21 +1,12 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection.Metadata; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public interface IPluginFeatureProvider { - public interface IPluginFeatureProvider - { - static abstract PluginFeature Instance { get; } - } - - public interface IPluginFeatureProvider : IPluginFeatureProvider where T : PluginFeature, IPluginFeatureProvider - { - static new abstract T Instance { get; } - static PluginFeature IPluginFeatureProvider.Instance => T.Instance; - } + static abstract PluginFeature Instance { get; } +} + +public interface IPluginFeatureProvider : IPluginFeatureProvider where T : PluginFeature, IPluginFeatureProvider +{ + static new abstract T Instance { get; } + static PluginFeature IPluginFeatureProvider.Instance => T.Instance; } diff --git a/Pilz.Plugins.Advanced/IPluginFeaturesProvider.cs b/Pilz.Plugins.Advanced/IPluginFeaturesProvider.cs index f5eca6e..1e136f7 100644 --- a/Pilz.Plugins.Advanced/IPluginFeaturesProvider.cs +++ b/Pilz.Plugins.Advanced/IPluginFeaturesProvider.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public interface IPluginFeaturesProvider { - public interface IPluginFeaturesProvider - { - static abstract PluginFeature[] GetFeatures(); - } + static abstract PluginFeature[] GetFeatures(); } diff --git a/Pilz.Plugins.Advanced/PluginFeature.cs b/Pilz.Plugins.Advanced/PluginFeature.cs index dff18a3..1b64a4f 100644 --- a/Pilz.Plugins.Advanced/PluginFeature.cs +++ b/Pilz.Plugins.Advanced/PluginFeature.cs @@ -1,60 +1,53 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public abstract class PluginFeature { - public abstract class PluginFeature + /// + /// The type of the feature defines where the feature get integrated. + /// + public string Type { get; init; } + /// + /// The identifier of the feature should be uniquie for the current . + /// It defines a feature within a type. + /// + public string Identifier { get; init; } + /// + /// The full identifier of the feature should be uniquie and is the combination of and . + /// It defines a feature across all types. + /// + public string FullIdentifier => GetFullIdentifier(Type, Identifier); + /// + /// The (display) name of the feature. + /// + public virtual string? Name { get; init; } + /// + /// The symbol for the feature. + /// + public virtual object? Icon { get; set; } + /// + /// Sets the prioritization of the feature. + /// This will be respected on abfragen features and on inserting as items using the extension methods"/>. + /// Some applications might implement a way to regonize feature prioritization via its own way. + /// + public virtual FeaturePrioritization Prioritization { get; set; } + /// + /// Defines if the feature is enabled/visible. + /// + public virtual bool Enabled { get; set; } = true; + + protected PluginFeature(string featureType, string identifier) { - /// - /// The type of the feature defines where the feature get integrated. - /// - public string Type { get; init; } - /// - /// The identifier of the feature should be uniquie for the current . - /// It defines a feature within a type. - /// - public string Identifier { get; init; } - /// - /// The full identifier of the feature should be uniquie and is the combination of and . - /// It defines a feature across all types. - /// - public string FullIdentifier => GetFullIdentifier(Type, Identifier); - /// - /// The (display) name of the feature. - /// - public virtual string? Name { get; init; } - /// - /// The symbol for the feature. - /// - public virtual object? Icon { get; set; } - /// - /// Sets the prioritization of the feature. - /// This will be respected on abfragen features and on inserting as items using the extension methods"/>. - /// Some applications might implement a way to regonize feature prioritization via its own way. - /// - public virtual FeaturePrioritization Prioritization { get; set; } - /// - /// Defines if the feature is enabled/visible. - /// - public virtual bool Enabled { get; set; } = true; + Identifier = identifier; + Type = featureType; + } - protected PluginFeature(string featureType, string identifier) - { - Identifier = identifier; - Type = featureType; - } + protected PluginFeature(string featureType, string featureIdentifier, string? featureName) : this(featureType, featureIdentifier) + { + Name = featureName; + } - protected PluginFeature(string featureType, string featureIdentifier, string? featureName) : this(featureType, featureIdentifier) - { - Name = featureName; - } - - public static string GetFullIdentifier(string featureType, string identifier) - { - return $"{featureType}:{identifier}"; - } + public static string GetFullIdentifier(string featureType, string identifier) + { + return $"{featureType}:{identifier}"; } } diff --git a/Pilz.Plugins.Advanced/PluginFeatureController.cs b/Pilz.Plugins.Advanced/PluginFeatureController.cs index 1003348..58c8528 100644 --- a/Pilz.Plugins.Advanced/PluginFeatureController.cs +++ b/Pilz.Plugins.Advanced/PluginFeatureController.cs @@ -1,273 +1,267 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; -namespace Pilz.Plugins.Advanced +namespace Pilz.Plugins.Advanced; + +public class PluginFeatureController { - public class PluginFeatureController + // D e l e g a t e s + + public delegate void PluginFeatureEventHandler(PluginFeatureController controller, PluginFeature feature); + + // S t a t i c E v e n t s + + /// + /// Fires when a new has been registred. + /// + public static event PluginFeatureEventHandler? OnPluginFeatureReistred; + + /// + /// Fires when a has been unregistred. + /// + public static event PluginFeatureEventHandler? OnPluginFeatureUnregistred; + + // S t a t i c M e m b e r s + + protected static readonly string nameGetFeatures = $"{nameof(IPluginFeaturesProvider.GetFeatures)}"; + protected static readonly string nameGetFeaturesExplicit = $"{typeof(IPluginFeaturesProvider).FullName}.{nameof(IPluginFeaturesProvider.GetFeatures)}"; + protected static readonly string nameInstance = $"get_{nameof(IPluginFeatureProvider.Instance)}"; + protected static readonly string nameInstnaceExplicit = $"{typeof(IPluginFeaturesProvider).FullName}.get_{nameof(IPluginFeatureProvider.Instance)}"; + + /// + /// The default public instance that can be used by plugins and the interface providing software. + /// + public static PluginFeatureController Instance { get; private set; } = new(); + + // I n s t a n c e M e m e b e r s + + private readonly HashSet features = []; + + /// + /// A wrapper of all registred instances. + /// + public FeatureController Features { get; init; } + + /// + /// A wrapper for all registred instances. + /// + public ModuleController Modules { get; init; } + + /// + /// A wrapper for all registred instances. + /// + public FunctionController Functions { get; init; } + + public PluginFeatureController() { - // D e l e g a t e s + Features = new(this); + Functions = new(this); + Modules = new(this); + } - public delegate void PluginFeatureEventHandler(PluginFeatureController controller, PluginFeature feature); + /// + /// Registers all features found in the currently executing Assembly via , and . + /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
+ ///
+ public void RegisterAllOwn() + { + RegisterAll(Assembly.GetCallingAssembly()); + } - // S t a t i c E v e n t s + /// + /// Registers all features found in the given via , and . + /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
+ ///
+ /// + public void RegisterAll(Assembly[] assemblies) + { + foreach (var assembly in assemblies) + RegisterAll(assembly); + } - /// - /// Fires when a new has been registred. - /// - public static event PluginFeatureEventHandler? OnPluginFeatureReistred; + /// + /// Registers all features found in the given via , and . + /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
+ ///
+ /// + public void RegisterAll(Assembly assembly) + { + RegisterAll(assembly.GetTypes()); + } - /// - /// Fires when a has been unregistred. - /// - public static event PluginFeatureEventHandler? OnPluginFeatureUnregistred; + /// + /// Registers all features found from the given via , and . + /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
+ ///
+ /// + public void RegisterAll(Type[] types) + { + foreach (var type in types) + RegisterAll(type); + } - // S t a t i c M e m b e r s - - protected static readonly string nameGetFeatures = $"{nameof(IPluginFeaturesProvider.GetFeatures)}"; - protected static readonly string nameGetFeaturesExplicit = $"{typeof(IPluginFeaturesProvider).FullName}.{nameof(IPluginFeaturesProvider.GetFeatures)}"; - protected static readonly string nameInstance = $"get_{nameof(IPluginFeatureProvider.Instance)}"; - protected static readonly string nameInstnaceExplicit = $"{typeof(IPluginFeaturesProvider).FullName}.get_{nameof(IPluginFeatureProvider.Instance)}"; - - /// - /// The default public instance that can be used by plugins and the interface providing software. - /// - public static PluginFeatureController Instance { get; private set; } = new(); - - // I n s t a n c e M e m e b e r s - - private readonly HashSet features = []; - - /// - /// A wrapper of all registred instances. - /// - public FeatureController Features { get; init; } - - /// - /// A wrapper for all registred instances. - /// - public ModuleController Modules { get; init; } - - /// - /// A wrapper for all registred instances. - /// - public FunctionController Functions { get; init; } - - public PluginFeatureController() + /// + /// Registers all features found from the given via , and . + /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
+ ///
+ /// + public void RegisterAll(Type type) + { + if (type.IsAssignableTo(typeof(IPluginFeaturesProvider))) { - Features = new(this); - Functions = new(this); - Modules = new(this); - } + var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + var method = methods.FirstOrDefault(n => n.Name == nameGetFeaturesExplicit || n.Name == nameGetFeatures); - /// - /// Registers all features found in the currently executing Assembly via , and . - /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
- ///
- public void RegisterAllOwn() - { - RegisterAll(Assembly.GetCallingAssembly()); - } - - /// - /// Registers all features found in the given via , and . - /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
- ///
- /// - public void RegisterAll(Assembly[] assemblies) - { - foreach (var assembly in assemblies) - RegisterAll(assembly); - } - - /// - /// Registers all features found in the given via , and . - /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
- ///
- /// - public void RegisterAll(Assembly assembly) - { - RegisterAll(assembly.GetTypes()); - } - - /// - /// Registers all features found from the given via , and . - /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
- ///
- /// - public void RegisterAll(Type[] types) - { - foreach (var type in types) - RegisterAll(type); - } - - /// - /// Registers all features found from the given via , and . - /// Note:
Explicit implementations of can not be detected. For this case just implement instead.
- ///
- /// - public void RegisterAll(Type type) - { - if (type.IsAssignableTo(typeof(IPluginFeaturesProvider))) + if (method != null && method.Invoke(null, null) is PluginFeature[] features) { - var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - var method = methods.FirstOrDefault(n => n.Name == nameGetFeaturesExplicit || n.Name == nameGetFeatures); - - if (method != null && method.Invoke(null, null) is PluginFeature[] features) - { - foreach (var feature in features) - Register(feature); - } - } - else if (type.IsAssignableTo(typeof(IPluginFeatureProvider))) - { - var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - var method = methods.FirstOrDefault(n => n.Name == nameInstnaceExplicit || n.Name == nameInstance); - - if (method != null && method.Invoke(null, null) is PluginFeature feature) + foreach (var feature in features) Register(feature); } } - - /// - /// Registers a feature via the given or . - /// - public void Register() where TProvider : IPluginFeatureProvider + else if (type.IsAssignableTo(typeof(IPluginFeatureProvider))) { - Register(TProvider.Instance); - } + var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + var method = methods.FirstOrDefault(n => n.Name == nameInstnaceExplicit || n.Name == nameInstance); - /// - /// Registers all features via the given . - /// - public void RegisterAll() where TProvider : IPluginFeaturesProvider - { - foreach (var feature in TProvider.GetFeatures()) + if (method != null && method.Invoke(null, null) is PluginFeature feature) Register(feature); } + } - /// - /// Registers the given feature. - /// - /// - public void Register(PluginFeature module) + /// + /// Registers a feature via the given or . + /// + public void Register() where TProvider : IPluginFeatureProvider + { + Register(TProvider.Instance); + } + + /// + /// Registers all features via the given . + /// + public void RegisterAll() where TProvider : IPluginFeaturesProvider + { + foreach (var feature in TProvider.GetFeatures()) + Register(feature); + } + + /// + /// Registers the given feature. + /// + /// + public void Register(PluginFeature module) + { + if (!features.Contains(module)) { - if (!features.Contains(module)) - { - features.Add(module); - OnPluginFeatureReistred?.Invoke(this, module); - } + features.Add(module); + OnPluginFeatureReistred?.Invoke(this, module); + } + } + + /// + /// Unregisters the given feature. + /// + /// + public void Unregister(PluginFeature module) + { + features.Remove(module); + OnPluginFeatureUnregistred?.Invoke(this, module); + } + + public class FeatureController(PluginFeatureController controller) + { + protected readonly PluginFeatureController controller = controller; + + public virtual IEnumerable GetAll() + { + return controller.features.ToArray(); } - /// - /// Unregisters the given feature. - /// - /// - public void Unregister(PluginFeature module) + public virtual IEnumerable Get(string featureType) { - features.Remove(module); - OnPluginFeatureUnregistred?.Invoke(this, module); + return controller.features.Where(n => n.Type == featureType); } - public class FeatureController(PluginFeatureController controller) + public virtual PluginFeature? GetFirst(string featureType) { - protected readonly PluginFeatureController controller = controller; - - public virtual IEnumerable GetAll() - { - return controller.features.ToArray(); - } - - public virtual IEnumerable Get(string featureType) - { - return controller.features.Where(n => n.Type == featureType); - } - - public virtual PluginFeature? GetFirst(string featureType) - { - return controller.features.FirstOrDefault(n => n.Type == featureType); - } - - public virtual PluginFeature? GetByIdentifier(string fullIdentifier) - { - return controller.features.FirstOrDefault(n => n.FullIdentifier == fullIdentifier); - } - - public virtual PluginFeature? GetByIdentifier(string featureType, string identifier) - { - return controller.features.FirstOrDefault(n => n.Type == featureType && n.Identifier == identifier); - } + return controller.features.FirstOrDefault(n => n.Type == featureType); } - public class FeatureController(PluginFeatureController controller) : FeatureController(controller) where T : PluginFeature + public virtual PluginFeature? GetByIdentifier(string fullIdentifier) { - public override IEnumerable GetAll() - { - return controller.features.OfType(); - } - - public override IEnumerable Get(string moduleType) - { - return GetAll().Where(n => n.Type == moduleType); - } - - public override T? GetFirst(string moduleType) - { - return base.GetFirst(moduleType) as T; - } - - public override T? GetByIdentifier(string fullIdentifier) - { - return base.GetByIdentifier(fullIdentifier) as T; - } - - public override T? GetByIdentifier(string featureType, string identifier) - { - return base.GetByIdentifier(featureType, identifier) as T; - } + return controller.features.FirstOrDefault(n => n.FullIdentifier == fullIdentifier); } - public class ModuleController(PluginFeatureController controller) : FeatureController(controller) + public virtual PluginFeature? GetByIdentifier(string featureType, string identifier) { + return controller.features.FirstOrDefault(n => n.Type == featureType && n.Identifier == identifier); + } + } + + public class FeatureController(PluginFeatureController controller) : FeatureController(controller) where T : PluginFeature + { + public override IEnumerable GetAll() + { + return controller.features.OfType(); } - public class FunctionController(PluginFeatureController controller) : FeatureController(controller) + public override IEnumerable Get(string moduleType) { - public void ExecuteAll(string functionType) - { - foreach (var function in Get(functionType)) - function.Execute(); - } + return GetAll().Where(n => n.Type == moduleType); + } - public void ExecuteAll(string functionType, params object?[]? @params) - { - foreach (var function in Get(functionType)) - function.Execute(@params); - } + public override T? GetFirst(string moduleType) + { + return base.GetFirst(moduleType) as T; + } - public void ExecuteAll(string functionType, PluginFunctionParameter @params) - { - foreach (var function in Get(functionType)) - function.Execute(@params); - } + public override T? GetByIdentifier(string fullIdentifier) + { + return base.GetByIdentifier(fullIdentifier) as T; + } - public IEnumerable ExcuteAndGetResults(string functionType) - { - return Get(functionType).Select(n => n.Execute()); - } + public override T? GetByIdentifier(string featureType, string identifier) + { + return base.GetByIdentifier(featureType, identifier) as T; + } + } - public IEnumerable ExcuteAndGetResults(string functionType, params object?[]? @params) - { - return Get(functionType).Select(n => n.Execute(@params)); - } + public class ModuleController(PluginFeatureController controller) : FeatureController(controller) + { + } - public IEnumerable ExcuteAndGetResults(string functionType, PluginFunctionParameter @params) - { - return Get(functionType).Select(n => n.Execute(@params)); - } + public class FunctionController(PluginFeatureController controller) : FeatureController(controller) + { + public void ExecuteAll(string functionType) + { + foreach (var function in Get(functionType)) + function.Execute(); + } + + public void ExecuteAll(string functionType, params object?[]? @params) + { + foreach (var function in Get(functionType)) + function.Execute(@params); + } + + public void ExecuteAll(string functionType, PluginFunctionParameter @params) + { + foreach (var function in Get(functionType)) + function.Execute(@params); + } + + public IEnumerable ExcuteAndGetResults(string functionType) + { + return Get(functionType).Select(n => n.Execute()); + } + + public IEnumerable ExcuteAndGetResults(string functionType, params object?[]? @params) + { + return Get(functionType).Select(n => n.Execute(@params)); + } + + public IEnumerable ExcuteAndGetResults(string functionType, PluginFunctionParameter @params) + { + return Get(functionType).Select(n => n.Execute(@params)); } } } diff --git a/Pilz.Plugins.Advanced/PluginFunction.cs b/Pilz.Plugins.Advanced/PluginFunction.cs index 4831687..e7f6e2b 100644 --- a/Pilz.Plugins.Advanced/PluginFunction.cs +++ b/Pilz.Plugins.Advanced/PluginFunction.cs @@ -1,48 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public abstract class PluginFunction : PluginFeature { - public abstract class PluginFunction : PluginFeature + protected PluginFunction(string functionType, string functionIdentifier) : base(functionType, functionIdentifier) { - protected PluginFunction(string functionType, string functionIdentifier) : base(functionType, functionIdentifier) - { - } - - protected PluginFunction(string functionType, string functionIdentifier, string? functionName) : base(functionType, functionIdentifier, functionName) - { - } - - public virtual object? Execute() - { - return Execute((PluginFunctionParameter?)null); - } - - public virtual T? Execute(params object?[]? @params) - { - return Execute(new PluginFunctionSimpleParamter(@params)); - } - - public virtual object? Execute(params object?[]? @params) - { - return Execute(new PluginFunctionSimpleParamter(@params)); - } - - public virtual T? Execute(PluginFunctionSimpleParamter? @params) - { - if (Execute(@params) is T result) - return result; - return default; - } - - public virtual object? Execute(PluginFunctionParameter? @params) - { - return ExecuteFunction(@params); - } - - protected abstract object? ExecuteFunction(PluginFunctionParameter? @params); } + + protected PluginFunction(string functionType, string functionIdentifier, string? functionName) : base(functionType, functionIdentifier, functionName) + { + } + + public virtual object? Execute() + { + return Execute((PluginFunctionParameter?)null); + } + + public virtual T? Execute(params object?[]? @params) + { + return Execute(new PluginFunctionSimpleParamter(@params)); + } + + public virtual object? Execute(params object?[]? @params) + { + return Execute(new PluginFunctionSimpleParamter(@params)); + } + + public virtual T? Execute(PluginFunctionSimpleParamter? @params) + { + if (Execute(@params) is T result) + return result; + return default; + } + + public virtual object? Execute(PluginFunctionParameter? @params) + { + return ExecuteFunction(@params); + } + + protected abstract object? ExecuteFunction(PluginFunctionParameter? @params); } diff --git a/Pilz.Plugins.Advanced/PluginFunctionParameter.cs b/Pilz.Plugins.Advanced/PluginFunctionParameter.cs index 1c840fe..e9d16ed 100644 --- a/Pilz.Plugins.Advanced/PluginFunctionParameter.cs +++ b/Pilz.Plugins.Advanced/PluginFunctionParameter.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public class PluginFunctionParameter { - public class PluginFunctionParameter - { - } } diff --git a/Pilz.Plugins.Advanced/PluginFunctionSimpleParamter.cs b/Pilz.Plugins.Advanced/PluginFunctionSimpleParamter.cs index c8fcb8a..b55415e 100644 --- a/Pilz.Plugins.Advanced/PluginFunctionSimpleParamter.cs +++ b/Pilz.Plugins.Advanced/PluginFunctionSimpleParamter.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins.Advanced; -namespace Pilz.Plugins.Advanced +public sealed class PluginFunctionSimpleParamter : PluginFunctionParameter { - public sealed class PluginFunctionSimpleParamter : PluginFunctionParameter - { - public object?[]? Params { get; init; } + public object?[]? Params { get; init; } - public PluginFunctionSimpleParamter(params object?[]? @params) - { - Params = @params; - } + public PluginFunctionSimpleParamter(params object?[]? @params) + { + Params = @params; } } diff --git a/Pilz.Plugins.Advanced/PluginModuleBase.cs b/Pilz.Plugins.Advanced/PluginModuleBase.cs index 7e3e33c..d2e7d47 100644 --- a/Pilz.Plugins.Advanced/PluginModuleBase.cs +++ b/Pilz.Plugins.Advanced/PluginModuleBase.cs @@ -1,16 +1,15 @@ using System.ComponentModel; -namespace Pilz.Plugins.Advanced -{ - [EditorBrowsable(EditorBrowsableState.Never)] - public abstract class PluginModuleBase : PluginFeature - { - protected PluginModuleBase(string moduleType, string moduleIdentifier) : base(moduleType, moduleIdentifier) - { - } +namespace Pilz.Plugins.Advanced; - protected PluginModuleBase(string moduleType, string moduleIdentifier, string moduleName) : base(moduleType, moduleIdentifier, moduleName) - { - } +[EditorBrowsable(EditorBrowsableState.Never)] +public abstract class PluginModuleBase : PluginFeature +{ + protected PluginModuleBase(string moduleType, string moduleIdentifier) : base(moduleType, moduleIdentifier) + { + } + + protected PluginModuleBase(string moduleType, string moduleIdentifier, string moduleName) : base(moduleType, moduleIdentifier, moduleName) + { } } \ No newline at end of file diff --git a/Pilz.Plugins/IPlugin.cs b/Pilz.Plugins/IPlugin.cs index bb97eb5..64de7ef 100644 --- a/Pilz.Plugins/IPlugin.cs +++ b/Pilz.Plugins/IPlugin.cs @@ -1,7 +1,6 @@ -namespace Pilz.Plugins +namespace Pilz.Plugins; + +public interface IPlugin { - public interface IPlugin - { - public string Name { get; } - } + public string Name { get; } } \ No newline at end of file diff --git a/Pilz.Plugins/IPluginLateInitialization.cs b/Pilz.Plugins/IPluginLateInitialization.cs index c8cb979..ae87370 100644 --- a/Pilz.Plugins/IPluginLateInitialization.cs +++ b/Pilz.Plugins/IPluginLateInitialization.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins; -namespace Pilz.Plugins +public interface IPluginLateInitialization { - public interface IPluginLateInitialization - { - abstract void LateInit(); - } + abstract void LateInit(); } diff --git a/Pilz.Plugins/PluginLoadContext.cs b/Pilz.Plugins/PluginLoadContext.cs index 0de14a0..a04cb04 100644 --- a/Pilz.Plugins/PluginLoadContext.cs +++ b/Pilz.Plugins/PluginLoadContext.cs @@ -1,40 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; +using System.Reflection; using System.Runtime.Loader; -using System.Text; -using System.Threading.Tasks; -namespace Pilz.Plugins +namespace Pilz.Plugins; + +internal class PluginLoadContext : AssemblyLoadContext { - internal class PluginLoadContext : AssemblyLoadContext + private readonly AssemblyDependencyResolver _resolver; + + public PluginLoadContext(string pluginPath) { - private readonly AssemblyDependencyResolver _resolver; + _resolver = new AssemblyDependencyResolver(pluginPath); + } - public PluginLoadContext(string pluginPath) - { - _resolver = new AssemblyDependencyResolver(pluginPath); - } + protected override Assembly? Load(AssemblyName assemblyName) + { + var assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); - protected override Assembly? Load(AssemblyName assemblyName) - { - var assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); + if (assemblyPath != null) + return LoadFromAssemblyPath(assemblyPath); - if (assemblyPath != null) - return LoadFromAssemblyPath(assemblyPath); + return null; + } - return null; - } + protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) + { + var libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); - protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) - { - var libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); + if (libraryPath != null) + return LoadUnmanagedDllFromPath(libraryPath); - if (libraryPath != null) - return LoadUnmanagedDllFromPath(libraryPath); - - return IntPtr.Zero; - } + return IntPtr.Zero; } } diff --git a/Pilz.Plugins/PluginLoadInfo.cs b/Pilz.Plugins/PluginLoadInfo.cs index 7556f08..19677a8 100644 --- a/Pilz.Plugins/PluginLoadInfo.cs +++ b/Pilz.Plugins/PluginLoadInfo.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; -namespace Pilz.Plugins +namespace Pilz.Plugins; + +public class PluginLoadInfo where TPluginInterface : class where TPluginRuntimeInfo : PluginRuntimeInfo { - public class PluginLoadInfo where TPluginInterface : class where TPluginRuntimeInfo : PluginRuntimeInfo - { - internal List PluginsInternal { get; } = []; - public Assembly Assembly { get; internal set; } - public PluginLoadStatus Status { get; internal set; } - public IEnumerable Plugins => PluginsInternal.AsReadOnly(); - } + internal List PluginsInternal { get; } = []; + public Assembly Assembly { get; internal set; } + public PluginLoadStatus Status { get; internal set; } + public IEnumerable Plugins => PluginsInternal.AsReadOnly(); } diff --git a/Pilz.Plugins/PluginLoadStatus.cs b/Pilz.Plugins/PluginLoadStatus.cs index 1af7dc8..fa54e43 100644 --- a/Pilz.Plugins/PluginLoadStatus.cs +++ b/Pilz.Plugins/PluginLoadStatus.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins; -namespace Pilz.Plugins +public enum PluginLoadStatus { - public enum PluginLoadStatus - { - None, - Success, - AlreadyLoaded, - ErrorAtLoading, - FileNotFound, - NoValidPlugin - } + None, + Success, + AlreadyLoaded, + ErrorAtLoading, + FileNotFound, + NoValidPlugin } diff --git a/Pilz.Plugins/PluginManager.cs b/Pilz.Plugins/PluginManager.cs index 13bc26b..30a94f8 100644 --- a/Pilz.Plugins/PluginManager.cs +++ b/Pilz.Plugins/PluginManager.cs @@ -1,14 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins; -namespace Pilz.Plugins +public class PluginManager : PluginManager { - public class PluginManager : PluginManager - { - public static PluginManager Instance { get; private set; } = new(); - } + public static PluginManager Instance { get; private set; } = new(); } diff --git a/Pilz.Plugins/PluginManagerT.cs b/Pilz.Plugins/PluginManagerT.cs index 6c1a5e0..f9cc638 100644 --- a/Pilz.Plugins/PluginManagerT.cs +++ b/Pilz.Plugins/PluginManagerT.cs @@ -1,215 +1,206 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net.Http.Headers; -using System.Reflection; -using System.Reflection.Metadata.Ecma335; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; -namespace Pilz.Plugins +namespace Pilz.Plugins; + +public class PluginManager where TPluginInterface : class where TPluginRuntimeInfo : PluginRuntimeInfo { - public class PluginManager where TPluginInterface : class where TPluginRuntimeInfo : PluginRuntimeInfo + protected readonly List loadedPlugins = []; + + /// + /// The default initialization parameters used when no parameters passed. Commonly used for dynamically loading assemblies. + /// + public virtual object?[] DefaultParameters { get; set; } = []; + + /// + /// Returns a list of all currently loaded plugins. + /// + public virtual IEnumerable LoadedPlugins => loadedPlugins.AsReadOnly(); + + protected void OnCurrentAppDomainAssemblyLoad(object? sender, AssemblyLoadEventArgs args) { - protected readonly List loadedPlugins = []; + LoadPlugins(args.LoadedAssembly); + } - /// - /// The default initialization parameters used when no parameters passed. Commonly used for dynamically loading assemblies. - /// - public virtual object?[] DefaultParameters { get; set; } = []; + /// + /// Loads assembly from the given file paths and then loads the plugins from the assemblies. + /// + /// + /// + /// + public virtual IEnumerable> LoadPlugins(string[] paths, params object?[]? parameters) + { + var results = new List>(); - /// - /// Returns a list of all currently loaded plugins. - /// - public virtual IEnumerable LoadedPlugins => loadedPlugins.AsReadOnly(); + foreach (var path in paths) + results.Add(LoadPlugin(path, parameters)); - protected void OnCurrentAppDomainAssemblyLoad(object? sender, AssemblyLoadEventArgs args) + return results; + } + + /// + /// Loads plugins from the given assemblies. + /// + /// + /// + /// + public virtual IEnumerable> LoadPlugins(Assembly[] assemblies, params object?[]? parameters) + { + var results = new List>(); + + foreach (var assembly in assemblies) + results.Add(LoadPlugins(assembly, parameters)); + + return results; + } + + /// + /// Loads plugins from already loaded assemblies for the current . + /// + /// + public virtual IEnumerable> LoadOwnPlugins(params object?[]? parameters) + { + return LoadOwnPlugins(false, parameters); + } + + /// + /// Loads plugins from already loaded assemblies for the current . + /// + /// Do also load plugins from all yet not loaded assemblies by listening the event . + /// + public virtual IEnumerable> LoadOwnPlugins(bool listenAssemblyLoadContext, params object?[]? parameters) + { + var results = new List>(); + + if (listenAssemblyLoadContext) + AppDomain.CurrentDomain.AssemblyLoad += OnCurrentAppDomainAssemblyLoad; + + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + results.Add(LoadPlugins(assembly, parameters)); + + return results; + } + + /// + /// Loads an assembly from the given file path and then loads plugins from the assembly. + /// + /// + /// + /// + public virtual PluginLoadInfo LoadPlugin(string path, params object?[]? parameters) + { + var result = new PluginLoadInfo(); + var loadContext = new PluginLoadContext(path); + + if (File.Exists(path)) { - LoadPlugins(args.LoadedAssembly); - } - - /// - /// Loads assembly from the given file paths and then loads the plugins from the assemblies. - /// - /// - /// - /// - public virtual IEnumerable> LoadPlugins(string[] paths, params object?[]? parameters) - { - var results = new List>(); - - foreach (var path in paths) - results.Add(LoadPlugin(path, parameters)); - - return results; - } - - /// - /// Loads plugins from the given assemblies. - /// - /// - /// - /// - public virtual IEnumerable> LoadPlugins(Assembly[] assemblies, params object?[]? parameters) - { - var results = new List>(); - - foreach (var assembly in assemblies) - results.Add(LoadPlugins(assembly, parameters)); - - return results; - } - - /// - /// Loads plugins from already loaded assemblies for the current . - /// - /// - public virtual IEnumerable> LoadOwnPlugins(params object?[]? parameters) - { - return LoadOwnPlugins(false, parameters); - } - - /// - /// Loads plugins from already loaded assemblies for the current . - /// - /// Do also load plugins from all yet not loaded assemblies by listening the event . - /// - public virtual IEnumerable> LoadOwnPlugins(bool listenAssemblyLoadContext, params object?[]? parameters) - { - var results = new List>(); - - if (listenAssemblyLoadContext) - AppDomain.CurrentDomain.AssemblyLoad += OnCurrentAppDomainAssemblyLoad; - - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) - results.Add(LoadPlugins(assembly, parameters)); - - return results; - } - - /// - /// Loads an assembly from the given file path and then loads plugins from the assembly. - /// - /// - /// - /// - public virtual PluginLoadInfo LoadPlugin(string path, params object?[]? parameters) - { - var result = new PluginLoadInfo(); - var loadContext = new PluginLoadContext(path); - - if (File.Exists(path)) + try { - try - { - result.Assembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(path))); - } - catch - { - result.Status = PluginLoadStatus.ErrorAtLoading; - } + result.Assembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(path))); } - else - result.Status = PluginLoadStatus.FileNotFound; - - if (result.Assembly != null) - LoadPlugin(result, parameters); - - return result; - } - - /// - /// Load plugins from a given assembly. - /// - /// - /// - /// - public virtual PluginLoadInfo LoadPlugins(Assembly assembly, params object?[]? parameters) - { - var result = new PluginLoadInfo + catch { - Assembly = assembly - }; + result.Status = PluginLoadStatus.ErrorAtLoading; + } + } + else + result.Status = PluginLoadStatus.FileNotFound; + if (result.Assembly != null) LoadPlugin(result, parameters); - - return result; + + return result; + } + + /// + /// Load plugins from a given assembly. + /// + /// + /// + /// + public virtual PluginLoadInfo LoadPlugins(Assembly assembly, params object?[]? parameters) + { + var result = new PluginLoadInfo + { + Assembly = assembly + }; + + LoadPlugin(result, parameters); + + return result; + } + + /// + /// Loads the plugin from a given type. + ///
Commonly used to ensure loading core plugins. + ///
+ /// + /// + /// + public virtual PluginLoadInfo LoadPlugin(params object?[]? parameters) where TPlugin : TPluginInterface + { + var result = new PluginLoadInfo + { + Assembly = typeof(TPlugin).Assembly + }; + + LoadPlugin(result, typeof(TPlugin), parameters); + + return result; + } + + protected virtual void LoadPlugin(PluginLoadInfo result, params object?[]? parameters) + { + if (result.Assembly == null) + result.Status = PluginLoadStatus.NoValidPlugin; + else if (loadedPlugins.Any(n => n.Assembly == result.Assembly)) + result.Status = PluginLoadStatus.AlreadyLoaded; + else + { + foreach (var type in result.Assembly.GetTypes()) + LoadPlugin(result, type, parameters); } - /// - /// Loads the plugin from a given type. - ///
Commonly used to ensure loading core plugins. - ///
- /// - /// - /// - public virtual PluginLoadInfo LoadPlugin(params object?[]? parameters) where TPlugin : TPluginInterface + if (result.PluginsInternal.Count == 0) + result.Status = PluginLoadStatus.NoValidPlugin; + } + + protected virtual void LoadPlugin(PluginLoadInfo result, Type type, params object?[]? parameters) + { + if (parameters == null || parameters.Length == 0) + parameters = DefaultParameters; + + if (loadedPlugins.Any(n => n.Plugin != null && n.Plugin.GetType() == type)) + result.Status = PluginLoadStatus.AlreadyLoaded; + else if (type.IsAssignableTo(typeof(TPluginInterface))) { - var result = new PluginLoadInfo + var info = Activator.CreateInstance(); + info.Assembly = result.Assembly; + result.PluginsInternal.Add(info); + + try { - Assembly = typeof(TPlugin).Assembly - }; - - LoadPlugin(result, typeof(TPlugin), parameters); - - return result; - } - - protected virtual void LoadPlugin(PluginLoadInfo result, params object?[]? parameters) - { - if (result.Assembly == null) - result.Status = PluginLoadStatus.NoValidPlugin; - else if (loadedPlugins.Any(n => n.Assembly == result.Assembly)) - result.Status = PluginLoadStatus.AlreadyLoaded; - else - { - foreach (var type in result.Assembly.GetTypes()) - LoadPlugin(result, type, parameters); - } - - if (result.PluginsInternal.Count == 0) - result.Status = PluginLoadStatus.NoValidPlugin; - } - - protected virtual void LoadPlugin(PluginLoadInfo result, Type type, params object?[]? parameters) - { - if (parameters == null || parameters.Length == 0) - parameters = DefaultParameters; - - if (loadedPlugins.Any(n => n.Plugin != null && n.Plugin.GetType() == type)) - result.Status = PluginLoadStatus.AlreadyLoaded; - else if (type.IsAssignableTo(typeof(TPluginInterface))) - { - var info = Activator.CreateInstance(); - info.Assembly = result.Assembly; - result.PluginsInternal.Add(info); - - try + if (Activator.CreateInstance(type, GetConstructorFlags(), null, parameters, null) is TPluginInterface plugin) { - if (Activator.CreateInstance(type, GetConstructorFlags(), null, parameters, null) is TPluginInterface plugin) - { - if (plugin is IPluginLateInitialization pluginLateInit) - pluginLateInit.LateInit(); + if (plugin is IPluginLateInitialization pluginLateInit) + pluginLateInit.LateInit(); - info.Plugin = plugin; - info.Status = PluginStatus.Success; - loadedPlugins.Add(info); - } - } - catch (Exception ex) - { - info.Exception = ex; - info.Status = PluginStatus.ErrorAtInitializing; + info.Plugin = plugin; + info.Status = PluginStatus.Success; + loadedPlugins.Add(info); } } - else - result.Status = PluginLoadStatus.NoValidPlugin; + catch (Exception ex) + { + info.Exception = ex; + info.Status = PluginStatus.ErrorAtInitializing; + } } + else + result.Status = PluginLoadStatus.NoValidPlugin; + } - protected virtual BindingFlags GetConstructorFlags() - { - return BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; - } + protected virtual BindingFlags GetConstructorFlags() + { + return BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; } } diff --git a/Pilz.Plugins/PluginRuntimeInfo.cs b/Pilz.Plugins/PluginRuntimeInfo.cs index c0d5264..7b57581 100644 --- a/Pilz.Plugins/PluginRuntimeInfo.cs +++ b/Pilz.Plugins/PluginRuntimeInfo.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins; -namespace Pilz.Plugins +public class PluginRuntimeInfo : PluginRuntimeInfo { - public class PluginRuntimeInfo : PluginRuntimeInfo - { - } } diff --git a/Pilz.Plugins/PluginRuntimeInfoT.cs b/Pilz.Plugins/PluginRuntimeInfoT.cs index 98bc7c7..bf89e49 100644 --- a/Pilz.Plugins/PluginRuntimeInfoT.cs +++ b/Pilz.Plugins/PluginRuntimeInfoT.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; -namespace Pilz.Plugins +namespace Pilz.Plugins; + +public class PluginRuntimeInfo where T : class { - public class PluginRuntimeInfo where T : class - { - public T? Plugin { get; internal set; } - public PluginStatus Status { get; internal set; } - public Assembly? Assembly { get; internal set; } - public Exception? Exception { get; internal set; } - } + public T? Plugin { get; internal set; } + public PluginStatus Status { get; internal set; } + public Assembly? Assembly { get; internal set; } + public Exception? Exception { get; internal set; } } diff --git a/Pilz.Plugins/PluginStatus.cs b/Pilz.Plugins/PluginStatus.cs index c490107..efe2564 100644 --- a/Pilz.Plugins/PluginStatus.cs +++ b/Pilz.Plugins/PluginStatus.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.Plugins; -namespace Pilz.Plugins +public enum PluginStatus { - public enum PluginStatus - { - None, - Success, - ErrorAtInitializing, - NoValidPlugin - } + None, + Success, + ErrorAtInitializing, + NoValidPlugin } diff --git a/Pilz.Simple3DFileParser/FileParser/Aspose3DLoader.vb b/Pilz.Simple3DFileParser/FileParser/Aspose3DLoader.vb index 67806f0..2878251 100644 --- a/Pilz.Simple3DFileParser/FileParser/Aspose3DLoader.vb +++ b/Pilz.Simple3DFileParser/FileParser/Aspose3DLoader.vb @@ -1,9 +1,9 @@ Imports System.Globalization Imports System.IO Imports System.Threading + Imports Aspose.ThreeD Imports Aspose.ThreeD.Entities -Imports Aspose.ThreeD.Formats Imports Aspose.ThreeD.Shading Imports Aspose.ThreeD.Utilities diff --git a/Pilz.Simple3DFileParser/FileParser/AssimpLoader.vb b/Pilz.Simple3DFileParser/FileParser/AssimpLoader.vb index 2571ba2..c60d484 100644 --- a/Pilz.Simple3DFileParser/FileParser/AssimpLoader.vb +++ b/Pilz.Simple3DFileParser/FileParser/AssimpLoader.vb @@ -1,4 +1,5 @@ Imports System.IO + Imports Assimp Imports Assimp.Unmanaged diff --git a/Pilz.Simple3DFileParser/FileParser/Obj.vb b/Pilz.Simple3DFileParser/FileParser/Obj.vb index 7b9de0e..8fb361b 100644 --- a/Pilz.Simple3DFileParser/FileParser/Obj.vb +++ b/Pilz.Simple3DFileParser/FileParser/Obj.vb @@ -1,6 +1,7 @@ Imports System.Globalization Imports System.IO Imports System.Threading + Imports Pilz.S3DFileParser.Exceptions Namespace ObjModule diff --git a/Pilz.Simple3DFileParser/Model/Object3D.vb b/Pilz.Simple3DFileParser/Model/Object3D.vb index 7e36721..f40f7d3 100644 --- a/Pilz.Simple3DFileParser/Model/Object3D.vb +++ b/Pilz.Simple3DFileParser/Model/Object3D.vb @@ -1,5 +1,4 @@ -Imports System.IO -Imports System.Numerics +Imports System.Numerics Public Class Object3D diff --git a/Pilz.Simple3DFileParser/Other/Extensions.vb b/Pilz.Simple3DFileParser/Other/Extensions.vb index 59da39b..14eeaa7 100644 --- a/Pilz.Simple3DFileParser/Other/Extensions.vb +++ b/Pilz.Simple3DFileParser/Other/Extensions.vb @@ -1,5 +1,4 @@ -Imports System.IO -Imports System.Runtime.CompilerServices +Imports System.Runtime.CompilerServices Friend Module Extensions diff --git a/Pilz.Simple3DFileParser/Other/LoaderModule.vb b/Pilz.Simple3DFileParser/Other/LoaderModule.vb index 620657f..8f71d86 100644 --- a/Pilz.Simple3DFileParser/Other/LoaderModule.vb +++ b/Pilz.Simple3DFileParser/Other/LoaderModule.vb @@ -1,4 +1,12 @@ -Imports System.Reflection + +' Nicht gemergte Änderung aus Projekt "Pilz.Simple3DFileParser (netstandard2.0)" +' Vor: +' Imports System.Reflection +' Imports Assimp.Unmanaged +' Nach: +' Imports System.Reflection +' +' Imports Assimp.Unmanaged Imports Assimp.Unmanaged Public Class File3DLoaderModule diff --git a/Pilz.UI.Telerik.SymbolFactory/Extensions.cs b/Pilz.UI.Telerik.SymbolFactory/Extensions.cs index 161f12a..5ff5524 100644 --- a/Pilz.UI.Telerik.SymbolFactory/Extensions.cs +++ b/Pilz.UI.Telerik.SymbolFactory/Extensions.cs @@ -1,25 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Drawing; using Telerik.WinControls; using Telerik.WinControls.Svg; -namespace Pilz.UI.Telerik +namespace Pilz.UI.Telerik; + +public static class Extensions { - public static class Extensions + public static Image ToImage(this RadSvgImage svg) { - public static Image ToImage(this RadSvgImage svg) - { - return svg?.Document.Draw(svg.Width, svg.Height); - } - - public static void ApplyColor(this RadSvgImage svg, Color color) - { - svg.Document.Fill = new SvgColourServer(color); - svg.ClearCache(); - } + return svg?.Document.Draw(svg.Width, svg.Height); + } + + public static void ApplyColor(this RadSvgImage svg, Color color) + { + svg.Document.Fill = new SvgColourServer(color); + svg.ClearCache(); } } diff --git a/Pilz.UI.Telerik.SymbolFactory/SvgImageSize.cs b/Pilz.UI.Telerik.SymbolFactory/SvgImageSize.cs index 905d4ed..90313b8 100644 --- a/Pilz.UI.Telerik.SymbolFactory/SvgImageSize.cs +++ b/Pilz.UI.Telerik.SymbolFactory/SvgImageSize.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.UI.Telerik; -namespace Pilz.UI.Telerik +public enum SvgImageSize { - public enum SvgImageSize - { - Default, - Small, - Medium, - Large - } + Default, + Small, + Medium, + Large } diff --git a/Pilz.UI.Telerik.SymbolFactory/SymbolFactory.cs b/Pilz.UI.Telerik.SymbolFactory/SymbolFactory.cs index a0280f2..e75b5db 100644 --- a/Pilz.UI.Telerik.SymbolFactory/SymbolFactory.cs +++ b/Pilz.UI.Telerik.SymbolFactory/SymbolFactory.cs @@ -1,84 +1,82 @@ using System.Drawing; using System.Reflection; using Telerik.WinControls; -using Telerik.WinControls.Svg; -namespace Pilz.UI.Telerik +namespace Pilz.UI.Telerik; + +public abstract class SymbolFactory where TSvgSymbols : Enum { - public abstract class SymbolFactory where TSvgSymbols : Enum + public abstract string GetSvgImageRessourcePath(TSvgSymbols svgImage); + public abstract Assembly GetSvgImageResourceAssembly(); + + protected virtual Size ResolveCommonSize(SvgImageSize size) { - public abstract string GetSvgImageRessourcePath(TSvgSymbols svgImage); - public abstract Assembly GetSvgImageResourceAssembly(); - - protected virtual Size ResolveCommonSize(SvgImageSize size) + return size switch { - return size switch - { - SvgImageSize.Small => new Size(16, 16), - SvgImageSize.Medium => new Size(20, 20), - SvgImageSize.Large => new Size(32, 32), - _ => Size.Empty, - }; - } + SvgImageSize.Small => new Size(16, 16), + SvgImageSize.Medium => new Size(20, 20), + SvgImageSize.Large => new Size(32, 32), + _ => Size.Empty, + }; + } - public virtual Stream? GetSvgImageRessourceStream(TSvgSymbols svgImage) - { - var asm = GetSvgImageResourceAssembly(); - var path = GetSvgImageRessourcePath(svgImage); - return asm.GetManifestResourceStream(path); - } + public virtual Stream? GetSvgImageRessourceStream(TSvgSymbols svgImage) + { + var asm = GetSvgImageResourceAssembly(); + var path = GetSvgImageRessourcePath(svgImage); + return asm.GetManifestResourceStream(path); + } - public virtual RadSvgImage GetSvgImage(TSvgSymbols svgImage, SvgImageSize size) - { - return GetSvgImage(svgImage, ResolveCommonSize(size)); - } + public virtual RadSvgImage GetSvgImage(TSvgSymbols svgImage, SvgImageSize size) + { + return GetSvgImage(svgImage, ResolveCommonSize(size)); + } - public virtual RadSvgImage GetSvgImage(TSvgSymbols svgImage, Size size) - { - using var stream = GetSvgImageRessourceStream(svgImage); - var img = RadSvgImage.FromStream(stream); + public virtual RadSvgImage GetSvgImage(TSvgSymbols svgImage, Size size) + { + using var stream = GetSvgImageRessourceStream(svgImage); + var img = RadSvgImage.FromStream(stream); - if (!size.IsEmpty) - img.Size = size; + if (!size.IsEmpty) + img.Size = size; - return img; - } + return img; + } - public virtual RadSvgImage GetSvgImageColored(TSvgSymbols svgImage, SvgImageSize size, Color color) - { - return GetSvgImageColored(svgImage, ResolveCommonSize(size), color); - } + public virtual RadSvgImage GetSvgImageColored(TSvgSymbols svgImage, SvgImageSize size, Color color) + { + return GetSvgImageColored(svgImage, ResolveCommonSize(size), color); + } - public virtual RadSvgImage GetSvgImageColored(TSvgSymbols svgImage, Size size, Color color) - { - var img = GetSvgImage(svgImage, size); - img.ApplyColor(color); - return img; - } + public virtual RadSvgImage GetSvgImageColored(TSvgSymbols svgImage, Size size, Color color) + { + var img = GetSvgImage(svgImage, size); + img.ApplyColor(color); + return img; + } - public virtual Image GetImage(TSvgSymbols svgImage, SvgImageSize size) - { - return GetImage(svgImage, ResolveCommonSize(size)); - } + public virtual Image GetImage(TSvgSymbols svgImage, SvgImageSize size) + { + return GetImage(svgImage, ResolveCommonSize(size)); + } - public virtual Image GetImage(TSvgSymbols svgImage, Size size) - { - return GetImageFromSvg(GetSvgImage(svgImage, size)); - } + public virtual Image GetImage(TSvgSymbols svgImage, Size size) + { + return GetImageFromSvg(GetSvgImage(svgImage, size)); + } - public virtual Image GetImageColored(TSvgSymbols svgImage, SvgImageSize size, Color color) - { - return GetImageColored(svgImage, ResolveCommonSize(size), color); - } + public virtual Image GetImageColored(TSvgSymbols svgImage, SvgImageSize size, Color color) + { + return GetImageColored(svgImage, ResolveCommonSize(size), color); + } - public virtual Image GetImageColored(TSvgSymbols svgImage, Size size, Color color) - { - return GetImageFromSvg(GetSvgImageColored(svgImage, size, color)); - } + public virtual Image GetImageColored(TSvgSymbols svgImage, Size size, Color color) + { + return GetImageFromSvg(GetSvgImageColored(svgImage, size, color)); + } - public virtual Image GetImageFromSvg(RadSvgImage svg) - { - return svg.ToImage(); - } + public virtual Image GetImageFromSvg(RadSvgImage svg) + { + return svg.ToImage(); } } \ No newline at end of file diff --git a/Pilz.UI.Telerik/Dialogs/DialogBase.Statics.cs b/Pilz.UI.Telerik/Dialogs/DialogBase.Statics.cs index 0413f27..f2d78ce 100644 --- a/Pilz.UI.Telerik/Dialogs/DialogBase.Statics.cs +++ b/Pilz.UI.Telerik/Dialogs/DialogBase.Statics.cs @@ -1,86 +1,76 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window; +namespace Pilz.UI.Telerik.Dialogs; -namespace Pilz.UI.Telerik.Dialogs +partial class DialogBase { - partial class DialogBase - { - public delegate void DialogLoadingEventHandler(DialogLoadingEventArgs e); - public delegate void DialogClosedEventHandler(DialogClosedEventArgs e); + public delegate void DialogLoadingEventHandler(DialogLoadingEventArgs e); + public delegate void DialogClosedEventHandler(DialogClosedEventArgs e); - public static event DialogLoadingEventHandler? DialogLoading; - public static event DialogClosedEventHandler? DialogClosed; + public static event DialogLoadingEventHandler? DialogLoading; + public static event DialogClosedEventHandler? DialogClosed; - public static T Show(string title, Icon icon, object? tag = null) where T : FlyoutBase + public static T Show(string title, Icon icon, object? tag = null) where T : FlyoutBase + { + return Show(null, title, icon, tag); + } + + public static T ShowDialog(string title, Icon icon, object? tag = null) where T : FlyoutBase + { + return ShowDialog(null, title, icon, tag); + } + + public static T Show(IWin32Window? parent, string title, Icon icon, object? tag = null) where T : FlyoutBase + { + return Show(CreatePanelInstance(tag), parent, title, icon); + } + + public static T ShowDialog(IWin32Window? parent, string title, Icon icon, object? tag = null) where T : FlyoutBase + { + return ShowDialog(CreatePanelInstance(tag), parent, title, icon); + } + + public static T Show(T dialogPanel, string title, Icon icon) where T : FlyoutBase + { + return Show(dialogPanel, null, title, icon); + } + + public static T ShowDialog(T dialogPanel, string title, Icon icon) where T : FlyoutBase + { + return ShowDialog(dialogPanel, null, title, icon); + } + + public static T Show(T dialogPanel, IWin32Window? parent, string title, Icon icon) where T : FlyoutBase + { + CreateForm(dialogPanel, parent, title, icon).Show(); + return dialogPanel; + } + + public static T ShowDialog(T dialogPanel, IWin32Window? parent, string title, Icon icon) where T : FlyoutBase + { + CreateForm(dialogPanel, parent, title, icon).ShowDialog(); + return dialogPanel; + } + + private static T CreatePanelInstance(object? tag) where T : FlyoutBase + { + T dialogPanel = Activator.CreateInstance(); + dialogPanel.Tag = tag; + return dialogPanel; + } + + private static DialogBase CreateForm(T dialogPanel, IWin32Window? parent, string title, Icon icon) where T : FlyoutBase + { + dialogPanel.Dock = DockStyle.Fill; + + var dialog = new DialogBase(dialogPanel) { - return Show(null, title, icon, tag); - } + Text = title, + Icon = icon, + StartPosition = parent == null ? FormStartPosition.CenterScreen : FormStartPosition.CenterParent, + ClientSize = dialogPanel.Size + }; - public static T ShowDialog(string title, Icon icon, object? tag = null) where T : FlyoutBase - { - return ShowDialog(null, title, icon, tag); - } + dialog.Controls.Add(dialogPanel); - public static T Show(IWin32Window? parent, string title, Icon icon, object? tag = null) where T : FlyoutBase - { - return Show(CreatePanelInstance(tag), parent, title, icon); - } - - public static T ShowDialog(IWin32Window? parent, string title, Icon icon, object? tag = null) where T : FlyoutBase - { - return ShowDialog(CreatePanelInstance(tag), parent, title, icon); - } - - public static T Show(T dialogPanel, string title, Icon icon) where T : FlyoutBase - { - return Show(dialogPanel, null, title, icon); - } - - public static T ShowDialog(T dialogPanel, string title, Icon icon) where T : FlyoutBase - { - return ShowDialog(dialogPanel, null, title, icon); - } - - public static T Show(T dialogPanel, IWin32Window? parent, string title, Icon icon) where T : FlyoutBase - { - CreateForm(dialogPanel, parent, title, icon).Show(); - return dialogPanel; - } - - public static T ShowDialog(T dialogPanel, IWin32Window? parent, string title, Icon icon) where T : FlyoutBase - { - CreateForm(dialogPanel, parent, title, icon).ShowDialog(); - return dialogPanel; - } - - private static T CreatePanelInstance(object? tag) where T : FlyoutBase - { - T dialogPanel = Activator.CreateInstance(); - dialogPanel.Tag = tag; - return dialogPanel; - } - - private static DialogBase CreateForm(T dialogPanel, IWin32Window? parent, string title, Icon icon) where T : FlyoutBase - { - dialogPanel.Dock = DockStyle.Fill; - - var dialog = new DialogBase(dialogPanel) - { - Text = title, - Icon = icon, - StartPosition = parent == null ? FormStartPosition.CenterScreen : FormStartPosition.CenterParent, - ClientSize = dialogPanel.Size - }; - - dialog.Controls.Add(dialogPanel); - - return dialog; - } - } + return dialog; + } } diff --git a/Pilz.UI.Telerik/Dialogs/DialogBase.cs b/Pilz.UI.Telerik/Dialogs/DialogBase.cs index efe326f..a4a723f 100644 --- a/Pilz.UI.Telerik/Dialogs/DialogBase.cs +++ b/Pilz.UI.Telerik/Dialogs/DialogBase.cs @@ -1,39 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using Telerik.WinControls.UI; +using Telerik.WinControls.UI; -namespace Pilz.UI.Telerik.Dialogs +namespace Pilz.UI.Telerik.Dialogs; + +public partial class DialogBase : RadForm { - public partial class DialogBase : RadForm + public FlyoutBase? DialogPanel { get; private set; } + + private DialogBase() { - public FlyoutBase? DialogPanel { get; private set; } + Load += DialogBaseForm_Load; + FormClosed += DialogBaseForm_FormClosed; + } - private DialogBase() - { - Load += DialogBaseForm_Load; - FormClosed += DialogBaseForm_FormClosed; - } + public DialogBase(FlyoutBase? dialogPanel) : this() + { + DialogPanel = dialogPanel; + } - public DialogBase(FlyoutBase? dialogPanel) : this() - { - DialogPanel = dialogPanel; - } + private void DialogBaseForm_Load(object? sender, EventArgs e) + { + if (DialogPanel is ILoadContent iLoadContent) + iLoadContent.LoadContent(); - private void DialogBaseForm_Load(object? sender, EventArgs e) - { - if (DialogPanel is ILoadContent iLoadContent) - iLoadContent.LoadContent(); + DialogLoading?.Invoke(new DialogLoadingEventArgs(this)); + } - DialogLoading?.Invoke(new DialogLoadingEventArgs(this)); - } - - private void DialogBaseForm_FormClosed(object? sender, FormClosedEventArgs e) - { - DialogClosed?.Invoke(new DialogClosedEventArgs(this)); - } + private void DialogBaseForm_FormClosed(object? sender, FormClosedEventArgs e) + { + DialogClosed?.Invoke(new DialogClosedEventArgs(this)); } } diff --git a/Pilz.UI.Telerik/Dialogs/DialogClosedEventArgs.cs b/Pilz.UI.Telerik/Dialogs/DialogClosedEventArgs.cs index 3f1f33a..39ec11d 100644 --- a/Pilz.UI.Telerik/Dialogs/DialogClosedEventArgs.cs +++ b/Pilz.UI.Telerik/Dialogs/DialogClosedEventArgs.cs @@ -1,20 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +namespace Pilz.UI.Telerik.Dialogs; -namespace Pilz.UI.Telerik.Dialogs +public class DialogClosedEventArgs : EventArgs { - public class DialogClosedEventArgs : EventArgs - { - public DialogBase Parent { get; private set; } - public FlyoutBase? Content => Parent?.DialogPanel; + public DialogBase Parent { get; private set; } + public FlyoutBase? Content => Parent?.DialogPanel; - public DialogClosedEventArgs(DialogBase dialog) - { - Parent = dialog; - } + public DialogClosedEventArgs(DialogBase dialog) + { + Parent = dialog; } } diff --git a/Pilz.UI.Telerik/Dialogs/DialogLoadingEventArgs.cs b/Pilz.UI.Telerik/Dialogs/DialogLoadingEventArgs.cs index 1ae2030..fefcec0 100644 --- a/Pilz.UI.Telerik/Dialogs/DialogLoadingEventArgs.cs +++ b/Pilz.UI.Telerik/Dialogs/DialogLoadingEventArgs.cs @@ -1,21 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using System.Windows.Forms.Design; +namespace Pilz.UI.Telerik.Dialogs; -namespace Pilz.UI.Telerik.Dialogs +public class DialogLoadingEventArgs : EventArgs { - public class DialogLoadingEventArgs : EventArgs - { - public DialogBase Parent { get; private set; } - public FlyoutBase? Content => Parent?.DialogPanel; + public DialogBase Parent { get; private set; } + public FlyoutBase? Content => Parent?.DialogPanel; - public DialogLoadingEventArgs(DialogBase dialog) - { - Parent = dialog; - } + public DialogLoadingEventArgs(DialogBase dialog) + { + Parent = dialog; } } diff --git a/Pilz.UI.Telerik/Dialogs/FlyoutBase.Statics.cs b/Pilz.UI.Telerik/Dialogs/FlyoutBase.Statics.cs index ec4d545..5a1d80a 100644 --- a/Pilz.UI.Telerik/Dialogs/FlyoutBase.Statics.cs +++ b/Pilz.UI.Telerik/Dialogs/FlyoutBase.Statics.cs @@ -1,101 +1,94 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Telerik.WinControls.UI; using Telerik.WinControls.UI.SplashScreen; -using Telerik.WinControls.UI; -using System.Windows.Forms; -namespace Pilz.UI.Telerik.Dialogs +namespace Pilz.UI.Telerik.Dialogs; + +partial class FlyoutBase { - partial class FlyoutBase + public delegate void FlyoutCreatedEventHandler(FlyoutCreatedEventArgs e); + public delegate void FlyoutClosedEventHandler(FlyoutClosedEventArgs e); + + public static event FlyoutCreatedEventHandler FlyoutCreated { - public delegate void FlyoutCreatedEventHandler(FlyoutCreatedEventArgs e); - public delegate void FlyoutClosedEventHandler(FlyoutClosedEventArgs e); + add => flyoutCreatedHandlers.Add(value); + remove => flyoutCreatedHandlers.Remove(value); + } - public static event FlyoutCreatedEventHandler FlyoutCreated + public static event FlyoutClosedEventHandler FlyoutClosed + { + add => flyoutCloseHandlers.Add(value); + remove => flyoutCloseHandlers.Remove(value); + } + + private static readonly List flyoutCreatedHandlers = new(); + private static readonly List flyoutCloseHandlers = new(); + + private static object? tagToAssign = null; + public static Control? ParentContext { get; private set; } = null; + + static FlyoutBase() + { + RadFlyoutManager.ContentCreated += RadFlyoutManager_ContentCreated; + RadFlyoutManager.FlyoutClosed += RadFlyoutManager_FlyoutClosed; + } + + private static void RadFlyoutManager_ContentCreated(ContentCreatedEventArgs e) + { + if (e.Content is FlyoutBase dialogBase) { - add => flyoutCreatedHandlers.Add(value); - remove => flyoutCreatedHandlers.Remove(value); - } + if (tagToAssign != null) + dialogBase.Tag = tagToAssign; - public static event FlyoutClosedEventHandler FlyoutClosed - { - add => flyoutCloseHandlers.Add(value); - remove => flyoutCloseHandlers.Remove(value); - } + var eventArgs = new FlyoutCreatedEventArgs((FlyoutBase)e.Content); - private static readonly List flyoutCreatedHandlers = new(); - private static readonly List flyoutCloseHandlers = new(); - - private static object? tagToAssign = null; - public static Control? ParentContext { get; private set; } = null; + if (dialogBase is ILoadContent iLoadContent) + iLoadContent.LoadContent(); - static FlyoutBase() - { - RadFlyoutManager.ContentCreated += RadFlyoutManager_ContentCreated; - RadFlyoutManager.FlyoutClosed += RadFlyoutManager_FlyoutClosed; - } - - private static void RadFlyoutManager_ContentCreated(ContentCreatedEventArgs e) - { - if (e.Content is FlyoutBase dialogBase) + foreach (var args in flyoutCreatedHandlers) { - if (tagToAssign != null) - dialogBase.Tag = tagToAssign; - - var eventArgs = new FlyoutCreatedEventArgs((FlyoutBase)e.Content); - - if (dialogBase is ILoadContent iLoadContent) - iLoadContent.LoadContent(); - - foreach (var args in flyoutCreatedHandlers) - { - if (ParentContext != null) - ParentContext?.Invoke(args, eventArgs); - else - args.Invoke(eventArgs); - } + if (ParentContext != null) + ParentContext?.Invoke(args, eventArgs); + else + args.Invoke(eventArgs); } } - - private static void RadFlyoutManager_FlyoutClosed(global::Telerik.WinControls.UI.SplashScreen.FlyoutClosedEventArgs e) - { - if (e.Content is FlyoutBase dialogBase) - { - var eventArgs = new FlyoutClosedEventArgs((FlyoutBase)e.Content); - - foreach (var args in flyoutCloseHandlers) - { - if (ParentContext != null) - ParentContext?.Invoke(args, eventArgs); - else - args.Invoke(eventArgs); - } - } - - ParentContext = null; - } - - public static void Show(Control controlToAssociate, object? tag = null) - { - Show(controlToAssociate, typeof(T), tag); - } - - public static void Show(Control controlToAssociate, Type flyoutContentType, object? tag = null) - { - tagToAssign = tag; - ParentContext = controlToAssociate; - RadFlyoutManager.Show(controlToAssociate, flyoutContentType); - } - - protected static void CloseFlyout() - { - if (ParentContext == null) - throw new NullReferenceException(nameof(ParentContext)); - - ParentContext.BeginInvoke(RadFlyoutManager.Close); - } + } + + private static void RadFlyoutManager_FlyoutClosed(global::Telerik.WinControls.UI.SplashScreen.FlyoutClosedEventArgs e) + { + if (e.Content is FlyoutBase dialogBase) + { + var eventArgs = new FlyoutClosedEventArgs((FlyoutBase)e.Content); + + foreach (var args in flyoutCloseHandlers) + { + if (ParentContext != null) + ParentContext?.Invoke(args, eventArgs); + else + args.Invoke(eventArgs); + } + } + + ParentContext = null; + } + + public static void Show(Control controlToAssociate, object? tag = null) + { + Show(controlToAssociate, typeof(T), tag); + } + + public static void Show(Control controlToAssociate, Type flyoutContentType, object? tag = null) + { + tagToAssign = tag; + ParentContext = controlToAssociate; + RadFlyoutManager.Show(controlToAssociate, flyoutContentType); + } + + protected static void CloseFlyout() + { + if (ParentContext == null) + throw new NullReferenceException(nameof(ParentContext)); + + ParentContext.BeginInvoke(RadFlyoutManager.Close); } } diff --git a/Pilz.UI.Telerik/Dialogs/FlyoutBase.cs b/Pilz.UI.Telerik/Dialogs/FlyoutBase.cs index acc771f..6ca0e61 100644 --- a/Pilz.UI.Telerik/Dialogs/FlyoutBase.cs +++ b/Pilz.UI.Telerik/Dialogs/FlyoutBase.cs @@ -1,99 +1,85 @@ -using Pilz.UI.Telerik; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using Telerik.WinControls; -using Telerik.WinControls.UI; -using Telerik.WinControls.UI.SplashScreen; -using static Telerik.WinControls.UI.PopupEditorNotificationData; +using Telerik.WinControls; -namespace Pilz.UI.Telerik.Dialogs +namespace Pilz.UI.Telerik.Dialogs; + +public partial class FlyoutBase : UserControl { - public partial class FlyoutBase : UserControl + public static RadSvgImage? CancelSvg { get; set; } = null; + public static RadSvgImage? ConfirmSvg { get; set; } = null; + + public DialogResult Result { get; protected set; } + public bool RegisterDialogAccept { get; set; } = true; + public bool RegisterDialogCancel { get; set; } = false; + + protected bool ActionPanelVisible { - public static RadSvgImage? CancelSvg { get; set; } = null; - public static RadSvgImage? ConfirmSvg { get; set; } = null; + get => tableLayoutPanel_ActionButtons.Visible; + set => tableLayoutPanel_ActionButtons.Visible = value; + } - public DialogResult Result { get; protected set; } - public bool RegisterDialogAccept { get; set; } = true; - public bool RegisterDialogCancel { get; set; } = false; + protected bool CancelButtonVisible + { + get => radButton_Cancel.Visible; + set => radButton_Cancel.Visible = value; + } - protected bool ActionPanelVisible + protected bool CancelButtonEnable + { + get => radButton_Cancel.Enabled; + set => radButton_Cancel.Enabled = value; + } + + protected bool ConfirmButtonEnable + { + get => radButton_Confirm.Enabled; + set => radButton_Confirm.Enabled = value; + } + + protected FlyoutBase() + { + InitializeComponent(); + ParentChanged += FlyoutDialogBase_ParentChanged; + + // SVG Symbols + radButton_Cancel.SvgImage = CancelSvg; + radButton_Confirm.SvgImage = ConfirmSvg; + } + + private void FlyoutDialogBase_ParentChanged(object? sender, EventArgs e) + { + var frm = FindForm(); + if (frm != null) { - get => tableLayoutPanel_ActionButtons.Visible; - set => tableLayoutPanel_ActionButtons.Visible = value; - } - - protected bool CancelButtonVisible - { - get => radButton_Cancel.Visible; - set => radButton_Cancel.Visible = value; - } - - protected bool CancelButtonEnable - { - get => radButton_Cancel.Enabled; - set => radButton_Cancel.Enabled = value; - } - - protected bool ConfirmButtonEnable - { - get => radButton_Confirm.Enabled; - set => radButton_Confirm.Enabled = value; - } - - protected FlyoutBase() - { - InitializeComponent(); - ParentChanged += FlyoutDialogBase_ParentChanged; - - // SVG Symbols - radButton_Cancel.SvgImage = CancelSvg; - radButton_Confirm.SvgImage = ConfirmSvg; - } - - private void FlyoutDialogBase_ParentChanged(object? sender, EventArgs e) - { - var frm = FindForm(); - if (frm != null) - { - if (RegisterDialogAccept) - frm.AcceptButton = radButton_Confirm; - if (RegisterDialogCancel) - frm.CancelButton = radButton_Cancel; - } - } - - protected void Close(DialogResult result) - { - Result = result; - - if (FindForm() is DialogBase dialogForm) - dialogForm.Close(); - else - CloseFlyout(); - } - - private void RadButton_Confirm_Click(object sender, EventArgs e) - { - if (ValidateOK()) - Close(DialogResult.OK); - } - - private void RadButton_Cancel_Click(object sender, EventArgs e) - { - Close(DialogResult.Cancel); - } - - protected virtual bool ValidateOK() - { - return true; + if (RegisterDialogAccept) + frm.AcceptButton = radButton_Confirm; + if (RegisterDialogCancel) + frm.CancelButton = radButton_Cancel; } } + + protected void Close(DialogResult result) + { + Result = result; + + if (FindForm() is DialogBase dialogForm) + dialogForm.Close(); + else + CloseFlyout(); + } + + private void RadButton_Confirm_Click(object sender, EventArgs e) + { + if (ValidateOK()) + Close(DialogResult.OK); + } + + private void RadButton_Cancel_Click(object sender, EventArgs e) + { + Close(DialogResult.Cancel); + } + + protected virtual bool ValidateOK() + { + return true; + } } diff --git a/Pilz.UI.Telerik/Dialogs/FlyoutClosedEventArgs.cs b/Pilz.UI.Telerik/Dialogs/FlyoutClosedEventArgs.cs index 21d51a3..dcf3ecd 100644 --- a/Pilz.UI.Telerik/Dialogs/FlyoutClosedEventArgs.cs +++ b/Pilz.UI.Telerik/Dialogs/FlyoutClosedEventArgs.cs @@ -1,18 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +namespace Pilz.UI.Telerik.Dialogs; -namespace Pilz.UI.Telerik.Dialogs +public class FlyoutClosedEventArgs : global::Telerik.WinControls.UI.SplashScreen.FlyoutClosedEventArgs { - public class FlyoutClosedEventArgs : global::Telerik.WinControls.UI.SplashScreen.FlyoutClosedEventArgs - { - public new FlyoutBase? Content => base.Content as FlyoutBase; + public new FlyoutBase? Content => base.Content as FlyoutBase; - public FlyoutClosedEventArgs(FlyoutBase content) : base(content) - { - } + public FlyoutClosedEventArgs(FlyoutBase content) : base(content) + { } } diff --git a/Pilz.UI.Telerik/Dialogs/FlyoutCreatedEventArgs.cs b/Pilz.UI.Telerik/Dialogs/FlyoutCreatedEventArgs.cs index f7263cb..fdcdcdd 100644 --- a/Pilz.UI.Telerik/Dialogs/FlyoutCreatedEventArgs.cs +++ b/Pilz.UI.Telerik/Dialogs/FlyoutCreatedEventArgs.cs @@ -1,19 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using Telerik.WinControls.UI.SplashScreen; +using Telerik.WinControls.UI.SplashScreen; -namespace Pilz.UI.Telerik.Dialogs +namespace Pilz.UI.Telerik.Dialogs; + +public class FlyoutCreatedEventArgs : ContentCreatedEventArgs { - public class FlyoutCreatedEventArgs : ContentCreatedEventArgs - { - public new FlyoutBase? Content => base.Content as FlyoutBase; + public new FlyoutBase? Content => base.Content as FlyoutBase; - public FlyoutCreatedEventArgs(FlyoutBase content) : base(content) - { - } + public FlyoutCreatedEventArgs(FlyoutBase content) : base(content) + { } } diff --git a/Pilz.UI.Telerik/Dialogs/ILoadContent.cs b/Pilz.UI.Telerik/Dialogs/ILoadContent.cs index 6ab549c..46992bd 100644 --- a/Pilz.UI.Telerik/Dialogs/ILoadContent.cs +++ b/Pilz.UI.Telerik/Dialogs/ILoadContent.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Pilz.UI.Telerik.Dialogs; -namespace Pilz.UI.Telerik.Dialogs +public interface ILoadContent { - public interface ILoadContent - { - void LoadContent(); - } + void LoadContent(); } diff --git a/Pilz.UI/Highlighter.vb b/Pilz.UI/Highlighter.vb index db56865..e7da68c 100644 --- a/Pilz.UI/Highlighter.vb +++ b/Pilz.UI/Highlighter.vb @@ -1,9 +1,15 @@ -Imports System -Imports System.Collections.Generic -Imports System.ComponentModel -Imports System.Windows.Forms +Imports System.ComponentModel Imports System.Drawing +' Nicht gemergte Änderung aus Projekt "Pilz.UI (net8.0-windows)" +' Vor: +' Imports System.Windows.Forms +' Imports System.Drawing +' Nach: +' Imports System.Drawing +' Imports System.Windows.Forms +Imports System.Windows.Forms + Public Class Highlighter Inherits Component diff --git a/Pilz.UI/PaintingControl/DefaultDrawMethodes.vb b/Pilz.UI/PaintingControl/DefaultDrawMethodes.vb index f115a31..136796b 100644 --- a/Pilz.UI/PaintingControl/DefaultDrawMethodes.vb +++ b/Pilz.UI/PaintingControl/DefaultDrawMethodes.vb @@ -1,6 +1,7 @@ Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Windows.Forms + Imports Pilz.Drawing ''' diff --git a/Pilz.UI/PaintingControl/EventArgs/PaintingObjectEventArgs.vb b/Pilz.UI/PaintingControl/EventArgs/PaintingObjectEventArgs.vb index ef5c14b..27b7d1f 100644 --- a/Pilz.UI/PaintingControl/EventArgs/PaintingObjectEventArgs.vb +++ b/Pilz.UI/PaintingControl/EventArgs/PaintingObjectEventArgs.vb @@ -1,9 +1,12 @@ -Imports System.Drawing -Imports System.IO -Imports System.Windows.Forms -Imports Newtonsoft.Json -Imports Newtonsoft.Json.Linq - + +' Nicht gemergte Änderung aus Projekt "Pilz.UI (net8.0-windows)" +' Vor: +' Imports System.Windows.Forms +' Imports Newtonsoft.Json +' Nach: +' Imports System.Windows.Forms +' +' Imports Newtonsoft.Json Public Class PaintingObjectEventArgs Inherits EventArgs diff --git a/Pilz.UI/PaintingControl/EventArgs/PaintingObjectPaintEventArgs.vb b/Pilz.UI/PaintingControl/EventArgs/PaintingObjectPaintEventArgs.vb index aaca912..6283571 100644 --- a/Pilz.UI/PaintingControl/EventArgs/PaintingObjectPaintEventArgs.vb +++ b/Pilz.UI/PaintingControl/EventArgs/PaintingObjectPaintEventArgs.vb @@ -1,8 +1,13 @@ Imports System.Drawing -Imports System.IO -Imports System.Windows.Forms -Imports Newtonsoft.Json -Imports Newtonsoft.Json.Linq +' Nicht gemergte Änderung aus Projekt "Pilz.UI (net8.0-windows)" +' Vor: +' Imports System.Windows.Forms +' Imports Newtonsoft.Json +' Nach: +' Imports System.Windows.Forms +' +' Imports Newtonsoft.Json + Public Class PaintingObjectPaintEventArgs Inherits EventArgs diff --git a/Pilz.UI/PaintingControl/IPaintingObjectContainer.vb b/Pilz.UI/PaintingControl/IPaintingObjectContainer.vb index 6909c7d..3418742 100644 --- a/Pilz.UI/PaintingControl/IPaintingObjectContainer.vb +++ b/Pilz.UI/PaintingControl/IPaintingObjectContainer.vb @@ -1,5 +1,3 @@ -Imports System.Drawing - -Public Interface IPaintingObjectContainer +Public Interface IPaintingObjectContainer End Interface diff --git a/Pilz.UI/PaintingControl/LineCapProps.vb b/Pilz.UI/PaintingControl/LineCapProps.vb index 6d48807..1dbc011 100644 --- a/Pilz.UI/PaintingControl/LineCapProps.vb +++ b/Pilz.UI/PaintingControl/LineCapProps.vb @@ -1,6 +1,4 @@ -Imports System.Drawing - -Public MustInherit Class LineCapProps +Public MustInherit Class LineCapProps Friend MustOverride Function Configure() As LineCapConfigurationArgs diff --git a/Pilz.UI/PaintingControl/PaintingControl.vb b/Pilz.UI/PaintingControl/PaintingControl.vb index 05a3fdd..874f673 100644 --- a/Pilz.UI/PaintingControl/PaintingControl.vb +++ b/Pilz.UI/PaintingControl/PaintingControl.vb @@ -1,8 +1,8 @@ Imports System.ComponentModel Imports System.Drawing Imports System.Drawing.Drawing2D -Imports System.Runtime.CompilerServices Imports System.Windows.Forms + Imports Pilz.Drawing Public Class PaintingControl diff --git a/Pilz.UI/PaintingControl/PaintingObject.vb b/Pilz.UI/PaintingControl/PaintingObject.vb index 78f00ca..edc5b82 100644 --- a/Pilz.UI/PaintingControl/PaintingObject.vb +++ b/Pilz.UI/PaintingControl/PaintingObject.vb @@ -2,10 +2,8 @@ Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Reflection -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Runtime.Serialization Imports System.Windows.Forms + Imports Newtonsoft.Json Public Class PaintingObject diff --git a/Pilz.UI/PaintingControl/PaintingObjectResizing.vb b/Pilz.UI/PaintingControl/PaintingObjectResizing.vb index bd9a5e9..9e8f17e 100644 --- a/Pilz.UI/PaintingControl/PaintingObjectResizing.vb +++ b/Pilz.UI/PaintingControl/PaintingObjectResizing.vb @@ -1,9 +1,6 @@ Imports System.Drawing -Imports System.Runtime.CompilerServices Imports System.Windows.Forms -Imports Newtonsoft.Json - Imports Pilz.Drawing Friend Class PaintingObjectResizing diff --git a/Pilz.Win32/Internals/IconFactory.vb b/Pilz.Win32/Internals/IconFactory.vb index 26ff50f..d0eeaa9 100644 --- a/Pilz.Win32/Internals/IconFactory.vb +++ b/Pilz.Win32/Internals/IconFactory.vb @@ -1,12 +1,19 @@ -Imports System -Imports System.Runtime.InteropServices -Imports Microsoft.Win32 +' Nicht gemergte Änderung aus Projekt "Pilz.Win32 (net6.0-windows)" +' Vor: +' Imports System.Runtime.InteropServices +' Imports Microsoft.Win32 +' Nach: +' Imports System.Collections.Generic +' Imports System.Drawing +.Drawing Imports System.Reflection -Imports System.Collections.Generic -Imports System.Drawing +Imports System.Runtime.InteropServices + +Imports Microsoft.Win32 + +Imports Pilz.Win32.Mapped Imports Pilz.Win32.Native Imports Pilz.Win32.Native.Shell32 -Imports Pilz.Win32.Mapped Namespace Internals Public Class IconFactory diff --git a/Pilz.Win32/Mapped/NativeFileInfo.vb b/Pilz.Win32/Mapped/NativeFileInfo.vb index 83b2c5c..34ae50c 100644 --- a/Pilz.Win32/Mapped/NativeFileInfo.vb +++ b/Pilz.Win32/Mapped/NativeFileInfo.vb @@ -1,4 +1,5 @@ Imports System.Drawing + Imports Pilz.Win32.Native Namespace Mapped diff --git a/Pilz/Runtime/RuntimeInformationsEx.vb b/Pilz/Runtime/RuntimeInformationsEx.vb index 5e9ad7a..6ad5541 100644 --- a/Pilz/Runtime/RuntimeInformationsEx.vb +++ b/Pilz/Runtime/RuntimeInformationsEx.vb @@ -26,56 +26,56 @@ Namespace Runtime End Get End Property - Public ReadOnly Property RealOSType As OSType - Get - Static t As OSType? = Nothing + Public ReadOnly Property RealOSType As OSType + Get + Static t As OSType? = Nothing - If t Is Nothing Then + If t Is Nothing Then - Dim windir = Environment.GetEnvironmentVariable("windir") - Const ostypeDirWine = "Z:\proc\sys\kernel\ostype" - Const ostypeDirNative = "/proc/sys/kernel/ostype" - Const systemVersionWine = "Z:\System\Library\CoreServices\SystemVersion.plist" - Const systemVersionNative = "/System/Library/CoreServices/SystemVersion.plist" + Dim windir = Environment.GetEnvironmentVariable("windir") + Const ostypeDirWine = "Z:\proc\sys\kernel\ostype" + Const ostypeDirNative = "/proc/sys/kernel/ostype" + Const systemVersionWine = "Z:\System\Library\CoreServices\SystemVersion.plist" + Const systemVersionNative = "/System/Library/CoreServices/SystemVersion.plist" - If File.Exists(ostypeDirWine) Then ' Linux using wine - Dim osTypeString As String = File.ReadAllText(ostypeDirWine) - If osTypeString.StartsWith("Linux", StringComparison.OrdinalIgnoreCase) Then - ' Note: Android gets here too - t = OSType.Linux - Else - t = OSType.Unknown - End If - ElseIf File.Exists(ostypeDirNative) Then ' Linux native - Dim osTypeString As String = File.ReadAllText(ostypeDirNative) - If osTypeString.StartsWith("Linux", StringComparison.OrdinalIgnoreCase) Then - ' Note: Android gets here too - t = OSType.Linux - Else - t = OSType.Unknown - End If - ElseIf File.Exists(systemVersionWine) Then ' OSX using wine - ' Note: iOS gets here too - t = OSType.OSX - ElseIf File.Exists(systemVersionNative) Then ' OSX native - ' Note: iOS gets here too - t = OSType.OSX - ElseIf Not String.IsNullOrEmpty(windir) AndAlso Directory.Exists(windir) AndAlso Path.DirectorySeparatorChar = "\"c Then ' Windows - t = OSType.Windows - Else - t = OSType.Unknown - End If + If File.Exists(ostypeDirWine) Then ' Linux using wine + Dim osTypeString As String = File.ReadAllText(ostypeDirWine) + If osTypeString.StartsWith("Linux", StringComparison.OrdinalIgnoreCase) Then + ' Note: Android gets here too + t = OSType.Linux + Else + t = OSType.Unknown + End If + ElseIf File.Exists(ostypeDirNative) Then ' Linux native + Dim osTypeString As String = File.ReadAllText(ostypeDirNative) + If osTypeString.StartsWith("Linux", StringComparison.OrdinalIgnoreCase) Then + ' Note: Android gets here too + t = OSType.Linux + Else + t = OSType.Unknown + End If + ElseIf File.Exists(systemVersionWine) Then ' OSX using wine + ' Note: iOS gets here too + t = OSType.OSX + ElseIf File.Exists(systemVersionNative) Then ' OSX native + ' Note: iOS gets here too + t = OSType.OSX + ElseIf Not String.IsNullOrEmpty(windir) AndAlso Directory.Exists(windir) AndAlso Path.DirectorySeparatorChar = "\"c Then ' Windows + t = OSType.Windows + Else + t = OSType.Unknown + End If - End If + End If - Return t - End Get - End Property + Return t + End Get + End Property - Public Function IsOSPlatform(os As OSType, checkRealOS As Boolean) As Boolean - Return If(checkRealOS, RealOSType, OSType) = os - End Function + Public Function IsOSPlatform(os As OSType, checkRealOS As Boolean) As Boolean + Return If(checkRealOS, RealOSType, OSType) = os + End Function - End Module + End Module End Namespace