Fill a dictionary with properties of a class

ConfigurationHelper-Class

using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace Common.Libraries
{
    /// <summary>
    /// Handels Local File Configuration
    /// </summary>
    public sealed class ConfigurationHelper
    {
        private string _configurationPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Reflection\";
        private string _configurationFile = "reflection.config";
        private static readonly Logger _log = LogManager.GetCurrentClassLogger();
        private static readonly object _locker = new object();

        public Dictionary<string, object> ConfigurationItems { get; private set; }
        private static ConfigurationHelper _configuration = new ConfigurationHelper();
        public static ConfigurationHelper Configuration
        {
            get
            {
                return _configuration;
            }
            private set
            {
                lock(_locker)
                {
                    _configuration = value;
                    Monitor.Pulse(_locker);
                }
            }
        }

        private ConfigurationHelper() { }

        static ConfigurationHelper() { }

        /// <summary>
        /// Loads the Confiugration if it exists, Creates a Standard-Configuration with default Values
        /// if it does not exist
        /// </summary>
        public void LoadOrCreateConfiguration()
        {
            _log.Debug("--> LoadOrCreateConfiguration");

            if (!ConfigurationSet)
            {
                ConfigurationItems = new Dictionary<string, object>();
                PropertiesToDictionary();
                _log.Trace("### Dictonary with the configuration items has been created");

                if (ConfigurationExists())
                {
                    ReadConfiguration();
                    _log.Debug("<-- LoadOrCreateConfiguration");
                }
                else
                {
                    CreateConfiguration();
                    _log.Debug("<-- LoadOrCreateConfiguration");
                }
            }
        }

        /// <summary>
        /// Save a current Configuration
        /// </summary>
        public void SaveConfiuration()
        {
            _log.Debug("--> SaveConfiguration");

            CreateConfiguration();

            _log.Debug("<-- Save Configuration");
        }

        /// <summary>
        /// Create the Standard configuration with the property values
        /// </summary>
        private void CreateConfiguration()
        {
            _log.Debug("--> CreateStandardConfiguration");

            if (!ConfigurationSet)
                SetDefautlValues();
            if (!ConfigurationExists())
                Directory.CreateDirectory(_configurationPath);

            using (FileStream fs = new FileStream(_configurationPath + _configurationFile, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    foreach (KeyValuePair<string, object> configItem in ConfigurationItems)
                    {
                        sw.WriteLine(configItem.Key + "=" + configItem.Value);
                    }
                }
            }

            _log.Debug("<-- CreateStandardConfiguration: Created standard configuration and file: {0}", _configurationPath + _configurationFile);
        }

        /// <summary>
        /// Set Default Values for the Configuration
        /// </summary>
        private void SetDefautlValues()
        {
            _log.Debug("--> SetDefaultValues");

            LocalIPAddress = "10.254.0.101";
            LocalPort = "0";
            RemoteIPAddress = "10.254.0.133";
            RemotePort = "43238";

            TCP = false;
            UDP = false;
            Multicast = true;
            GzipCompression = false;

            ReceiveBufferSize = "8192";
            MaxSegmentSize = "200";
            SocketBufferSize = "8388608";
            MulticastSendTimeoutInMS = "500";

            DateMatchGroup = @"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})";
            TextAfterDateMatch = @"(.*)";
            TextBeforeProviderMatchGroup = @"CallList from";
            ProviderMatchGroup = @"(.*)";
            TextBeforeXMLCallListMatchGroup = @"\/MTP received. New Revision \(\d{1,9}\):";
            CallListMatchGroup = @"(.*)";

            FullRegex = DateMatchGroup + TextAfterDateMatch + TextBeforeProviderMatchGroup + ProviderMatchGroup + TextBeforeXMLCallListMatchGroup + CallListMatchGroup;

            ExtractionFolder = @"C:\Temp\";
            ExtractionFileName = @"extraction.log";

            ConfigurationSet = true;

            PropertiesToDictionary();

            _log.Debug("<-- SetDefaultValues");
        }

        /// <summary>
        /// Read Configuration from Configuration File
        /// </summary>
        private void ReadConfiguration()
        {
            _log.Debug("--> ReadConfiguration");

            using (FileStream fileStream = new FileStream(_configurationPath + _configurationFile, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader streamreader = new StreamReader(fileStream))
                {
                    string configurationLine;
                    while (!streamreader.EndOfStream)
                    {
                        configurationLine = streamreader.ReadLine();
                        configurationLine = configurationLine.Trim();

                        string[] configItem = configurationLine.Split('=');
                        UpdateDictionaryValue(configItem);
                    }
                }
            }
            ConfigurationSet = true;
            ConfigurationItems[nameof(ConfigurationSet)] = true;

            DictionaryToProperties();

            _log.Debug("<-- ReadConfiguration");
        }

        /// <summary>
        /// Transfers the read configuration Item to the Property, so it can be accessed from outside
        /// </summary>
        /// <param name="configItem">String Array with Propertyname and Propertyvalue</param>
        private void UpdateDictionaryValue(string[] configItem)
        {
            _log.Debug("--> TransformConfigurationItemToPropertyViaReflection: Configuration Item: {0}, Configuration Value: {1}", configItem[0], configItem[1]);

            if (ConfigurationItems.ContainsKey(configItem[0]))
                ConfigurationItems[configItem[0]] = configItem[1];
            else
                _log.Error("### Configuration Item with Key: {0} and Value: {1} couldn't be found", configItem[0], configItem[1]);

            _log.Trace("<-- TransformConfigurationItemToPropertyViaReflection");
        }

        /// <summary>
        /// Uses Reflection to get a dictionary of the properties
        /// </summary>
        private void PropertiesToDictionary()
        {
            _log.Debug("--> GenerateDictionaryFromProperties");

            ConfigurationItems = (Dictionary<string, object>)ObjectExtensions.ObjectToDictionary(this);
            _log.Debug("### Properties found {0}", ConfigurationItems.Count);

            _log.Debug("<-- GenerateDictionaryFromProperties");
        }

        /// <summary>
        /// Transforms the Dictionary to the Singleton Properties
        /// </summary>
        private void DictionaryToProperties()
        {
            _log.Debug("--> DictionaryToProperties");

            Configuration = ObjectExtensions.ObjectFromDictionary<ConfigurationHelper>(ConfigurationItems);

            _log.Debug("<-- DictionaryToProperties");
        }

        /// <summary>
        /// Check if the Confiuration File exists
        /// </summary>
        /// <returns></returns>
        private bool ConfigurationExists()
        {
            _log.Debug("<--> ConfigurationExists");

            return File.Exists(_configurationPath + _configurationFile);
        }

        #region Properties

        public bool ConfigurationSet { get; set; }
        public string RemoteIPAddress { get; set; }
        public string RemotePort { get; set; }
        public string LocalIPAddress { get; set; }
        public string LocalPort { get; set; }
        public bool TCP { get; set; }
        public bool UDP { get; set; }
        public bool Multicast { get; set; }
        public bool GzipCompression { get; set; }
        public string ReceiveBufferSize { get; set; }
        public string MaxSegmentSize { get; set; }
        public string SocketBufferSize { get; set; }
        public string DateMatchGroup { get; set; }
        public string TextAfterDateMatch { get; set; }
        public string TextBeforeProviderMatchGroup { get; set; }
        public string ProviderMatchGroup { get; set; }
        public string TextBeforeXMLCallListMatchGroup { get; set; }
        public string FullRegex { get; private set; }
        public string CallListMatchGroup { get; set; }
        public string ConfigurationPath
        {
            get
            {
                return _configurationPath;
            }
            private set => _configurationPath = value;
        }
        public string ConfigurationFile
        {
            get
            {
                return _configurationFile;
            }
            private set => _configurationFile = value;
        }
        public string ExtractionFileName { get; set; }
        public string ExtractionFolder { get; set; }
        public string MulticastSendTimeoutInMS { get; set; }

        #endregion properties
    }
}

ObjectExtensions Class

using NLog;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Common.Libraries
{
    public static class ObjectExtensions
    {
        private static readonly Logger _log = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Transfer a given dicionary to a given class
        /// </summary>
        /// <typeparam name="T">Class with Properties to be mapped</typeparam>
        /// <param name="dict">Dictionary for Property-mapping</param>
        /// <returns></returns>
        public static T ObjectFromDictionary<T>(IDictionary<string, object> dict) where T:class
        {
            _log.Debug("--> ObjectFromDictionary");

            Type myObjectType = typeof(T);
            T result = (T)Activator.CreateInstance(myObjectType);
            foreach (var item in dict)
            {
                //TODO optimize this if!
                if (item.Value.Equals("true") || item.Value.Equals("True"))
                        myObjectType.GetProperty(item.Key).SetValue(result, true, null);
                else if(item.Value.Equals("false") || item.Value.Equals("False"))
                        myObjectType.GetProperty(item.Key).SetValue(result, false, null);
                else
                    myObjectType.GetProperty(item.Key).SetValue(result, item.Value, null);
            }

            _log.Debug("<-- ObjectFromDictionary");

            return result;
        }

        /// <summary>
        /// Transfers a given class and the properties to a Dictionary
        /// </summary>
        /// <typeparam name="T">Classtype to be transfered</typeparam>
        /// <param name="item">Class-Object to be transfered</param>
        /// <returns></returns>
        public static IDictionary<string, object> ObjectToDictionary<T>(T item) where T:class
        {
            Type myObjectType = item.GetType();
            IDictionary<string, object> dict = new Dictionary<string, object>();
            PropertyInfo[] properties = myObjectType.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                var value = property.GetValue(item, null);
                dict.Add(property.Name, value);
            }
            return dict;
        }
    }
}

If you have any Suggestions or find a better soluation, just write a comment ­čÖé

This entry was posted in C#, PC, programming, Sonstiges, Wissen, Work and tagged , , , , . Bookmark the permalink.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.