Browse Source

Ajout de la méthode FirstUpperOtherLower dans StringUtils et StringUtilsExt : permet de mettre en majuscule la première lettre d'un mot, et de mettre en minuscule le reste du mot.
Ajout d'une méthode EnumUtils.TryParseEnum, substitue à celle du .NetFramework 4 non présente dans le .NetFramework 3.5
Ajout de méthodes pour écrire dans la Console en couleur. Création de ConsoleUtils.cs

Aryx 2 years ago
parent
commit
ab1c37b6ba
6 changed files with 324 additions and 0 deletions
  1. 2 0
      AryxDevLibrary.csproj
  2. BIN
      AryxDevLibrary.v12.suo
  3. 155 0
      EnumUtils.cs
  4. 26 0
      extensions/StringUtilsExt.cs
  5. 115 0
      utils/ConsoleUtils.cs
  6. 26 0
      utils/StringUtils.cs

+ 2 - 0
AryxDevLibrary.csproj

@@ -49,12 +49,14 @@
       <DesignTime>True</DesignTime>
       <DependentUpon>AssemblyTTempl.tt</DependentUpon>
     </Compile>
+    <Compile Include="EnumUtils.cs" />
     <Compile Include="extensions\DateUtilsExt.cs" />
     <Compile Include="extensions\StringUtilsExt.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="utils\cliParser\CliParser.cs" />
     <Compile Include="utils\cliParser\CliParserInitException.cs" />
     <Compile Include="utils\cliParser\CliParsingException.cs" />
+    <Compile Include="utils\ConsoleUtils.cs" />
     <Compile Include="utils\DateUtils.cs" />
     <Compile Include="utils\EnumConverter.cs" />
     <Compile Include="utils\EnumEncoding.cs" />

BIN
AryxDevLibrary.v12.suo


+ 155 - 0
EnumUtils.cs

@@ -0,0 +1,155 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace AryxDevLibrary
+{
+    public static class EnumUtils
+    {
+        private static readonly char[] FlagDelimiter = new[] { ',' };
+
+        public static bool TryParseEnum<TEnum>(string value, out TEnum result) where TEnum : struct
+        {
+            if (string.IsNullOrEmpty(value))
+            {
+                result = default(TEnum);
+                return false;
+            }
+
+            var enumType = typeof(TEnum);
+
+            if (!enumType.IsEnum)
+                throw new ArgumentException(string.Format("Type '{0}' is not an enum", enumType.FullName));
+
+
+            result = default(TEnum);
+
+            // Try to parse the value directly 
+            if (Enum.IsDefined(enumType, value))
+            {
+                result = (TEnum)Enum.Parse(enumType, value);
+                return true;
+            }
+
+            // Get some info on enum
+            var enumValues = Enum.GetValues(enumType);
+            if (enumValues.Length == 0)
+                return false;  // probably can't happen as you cant define empty enum?
+            var enumTypeCode = Type.GetTypeCode(enumValues.GetValue(0).GetType());
+
+            // Try to parse it as a flag 
+            if (value.IndexOf(',') != -1)
+            {
+                if (!Attribute.IsDefined(enumType, typeof(FlagsAttribute)))
+                    return false;  // value has flags but enum is not flags
+
+                // todo: cache this for efficiency
+                var enumInfo = new Dictionary<string, object>();
+                var enumNames = Enum.GetNames(enumType);
+                for (var i = 0; i < enumNames.Length; i++)
+                    enumInfo.Add(enumNames[i], enumValues.GetValue(i));
+
+                ulong retVal = 0;
+                foreach (var name in value.Split(FlagDelimiter))
+                {
+                    var trimmedName = name.Trim();
+                    if (!enumInfo.ContainsKey(trimmedName))
+                        return false;   // Enum has no such flag
+
+                    var enumValueObject = enumInfo[trimmedName];
+                    ulong enumValueLong;
+                    switch (enumTypeCode)
+                    {
+                        case TypeCode.Byte:
+                            enumValueLong = (byte)enumValueObject;
+                            break;
+                        case TypeCode.SByte:
+                            enumValueLong = (byte)((sbyte)enumValueObject);
+                            break;
+                        case TypeCode.Int16:
+                            enumValueLong = (ushort)((short)enumValueObject);
+                            break;
+                        case TypeCode.Int32:
+                            enumValueLong = (uint)((int)enumValueObject);
+                            break;
+                        case TypeCode.Int64:
+                            enumValueLong = (ulong)((long)enumValueObject);
+                            break;
+                        case TypeCode.UInt16:
+                            enumValueLong = (ushort)enumValueObject;
+                            break;
+                        case TypeCode.UInt32:
+                            enumValueLong = (uint)enumValueObject;
+                            break;
+                        case TypeCode.UInt64:
+                            enumValueLong = (ulong)enumValueObject;
+                            break;
+                        default:
+                            return false;   // should never happen
+                    }
+                    retVal |= enumValueLong;
+                }
+                result = (TEnum)Enum.ToObject(enumType, retVal);
+                return true;
+            }
+
+            // the value may be a number, so parse it directly
+            switch (enumTypeCode)
+            {
+                case TypeCode.SByte:
+                    sbyte sb;
+                    if (!SByte.TryParse(value, out sb))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, sb);
+                    break;
+                case TypeCode.Byte:
+                    byte b;
+                    if (!Byte.TryParse(value, out b))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, b);
+                    break;
+                case TypeCode.Int16:
+                    short i16;
+                    if (!Int16.TryParse(value, out i16))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, i16);
+                    break;
+                case TypeCode.UInt16:
+                    ushort u16;
+                    if (!UInt16.TryParse(value, out u16))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, u16);
+                    break;
+                case TypeCode.Int32:
+                    int i32;
+                    if (!Int32.TryParse(value, out i32))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, i32);
+                    break;
+                case TypeCode.UInt32:
+                    uint u32;
+                    if (!UInt32.TryParse(value, out u32))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, u32);
+                    break;
+                case TypeCode.Int64:
+                    long i64;
+                    if (!Int64.TryParse(value, out i64))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, i64);
+                    break;
+                case TypeCode.UInt64:
+                    ulong u64;
+                    if (!UInt64.TryParse(value, out u64))
+                        return false;
+                    result = (TEnum)Enum.ToObject(enumType, u64);
+                    break;
+                default:
+                    return false; // should never happen
+            }
+
+            return true;
+        }
+    }
+}

+ 26 - 0
extensions/StringUtilsExt.cs

@@ -10,6 +10,32 @@ namespace AryxDevLibrary.extensions
     {
 
         /// <summary>
+        /// Capitalize the first letter and lower the others.
+        /// </summary>
+        /// <param name="str">this string</param>
+        /// <returns>The string with the first letter upped and lowered the others</returns>
+        public static string FirstUpperOtherLower(this string str)
+        {
+            if (StringUtils.IsNullOrWhiteSpace(str))
+            {
+                return str;
+            }
+
+            String fl = "";
+            if (str.Length >= 1)
+            {
+                fl = str.Substring(0, 1).ToUpper();
+            }
+
+            if (str.Length >= 2)
+            {
+                fl += str.Substring(1).ToLower();
+            }
+
+            return fl;
+        }
+
+        /// <summary>
         /// Test if the string is empty.
         /// </summary>
         /// <param name="value">this string</param>

+ 115 - 0
utils/ConsoleUtils.cs

@@ -0,0 +1,115 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using AryxDevLibrary.extensions;
+
+namespace AryxDevLibrary.utils
+{
+    public static class ConsoleUtils
+    {
+        /// <summary>
+        /// 
+        /// Begin of foreground color tag: <*color*>. End of foreground color tag: <*/*>. 
+        /// Begin of background color tag: <*!color*>. End of background color tag: <*/!*>.
+        /// 
+        /// https://stackoverflow.com/questions/2697944/using-colors-in-console-how-to-store-in-a-simplified-notation
+        /// </summary>
+        /// <param name="str">The string to show</param>
+        public static void WriteColor(string str)
+        {
+            var fgStack = new Stack<ConsoleColor>();
+            var bgStack = new Stack<ConsoleColor>();
+            var parts = str.Split(new[] { "<*" }, StringSplitOptions.None);
+            foreach (var part in parts)
+            {
+                var tokens = part.Split(new[] { "*>" }, StringSplitOptions.None);
+                if (tokens.Length == 1)
+                {
+                    Console.Write(tokens[0]);
+                }
+                else
+                {
+                    if (!String.IsNullOrEmpty(tokens[0]))
+                    {
+                        ConsoleColor color;
+                        if (tokens[0][0] == '!')
+                        {
+                            if (EnumUtils.TryParseEnum(tokens[0].Substring(1).FirstUpperOtherLower(), out color))
+                            {
+                                bgStack.Push(Console.BackgroundColor);
+                                Console.BackgroundColor = color;
+                            }
+                        }
+                        else if (tokens[0][0] == '/')
+                        {
+                            if (tokens[0].Length > 1 && tokens[0][1] == '!')
+                            {
+                                if (bgStack.Count > 0)
+                                    Console.BackgroundColor = bgStack.Pop();
+                            }
+                            else
+                            {
+                                if (fgStack.Count > 0)
+                                    Console.ForegroundColor = fgStack.Pop();
+                            }
+                        }
+                        else
+                        {
+                            if (EnumUtils.TryParseEnum(tokens[0].FirstUpperOtherLower(), out color))
+                            {
+                                fgStack.Push(Console.ForegroundColor);
+                                Console.ForegroundColor = color;
+                            }
+                        }
+                    }
+                    for (int j = 1; j < tokens.Length; j++)
+                        Console.Write(tokens[j]);
+                }
+            }
+        }
+
+        /// <summary>
+        /// 
+        /// Begin of foreground color tag: <*color*>. End of foreground color tag: <*/*>. 
+        /// Begin of background color tag: <*!color*>. End of background color tag: <*/!*>.
+        /// 
+        /// https://stackoverflow.com/questions/2697944/using-colors-in-console-how-to-store-in-a-simplified-notation
+        /// </summary>
+        /// <param name="str">The string to show</param>
+        public static void WriteLineColor(string str)
+        {
+            WriteColor(str);
+            Console.WriteLine();
+        }
+
+        /// <summary>
+        /// 
+        /// Begin of foreground color tag: <*color*>. End of foreground color tag: <*/*>. 
+        /// Begin of background color tag: <*!color*>. End of background color tag: <*/!*>.
+        /// 
+        /// https://stackoverflow.com/questions/2697944/using-colors-in-console-how-to-store-in-a-simplified-notation
+        /// </summary>
+        /// <param name="str">The string to show</param>
+        /// <param name="arg"></param>
+        public static void WriteColor(string str, params object[] arg)
+        {
+            WriteColor(String.Format(str, arg));
+        }
+
+        /// <summary>
+        /// 
+        /// Begin of foreground color tag: <*color*>. End of foreground color tag: <*/*>. 
+        /// Begin of background color tag: <*!color*>. End of background color tag: <*/!*>.
+        /// 
+        /// https://stackoverflow.com/questions/2697944/using-colors-in-console-how-to-store-in-a-simplified-notation
+        /// </summary>
+        /// <param name="str">The string to show</param>
+        /// <param name="arg"></param>
+        public static void WriteLineColor(string str, params object[] arg)
+        {
+            WriteColor(String.Format(str, arg));
+            Console.WriteLine();
+        }
+    }
+}

+ 26 - 0
utils/StringUtils.cs

@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Globalization;
+using System.IO;
 using System.Linq;
 using System.Text;
 
@@ -14,6 +15,31 @@ namespace AryxDevLibrary.utils
         public const string AUTH_FILENAME_CHARS =
     "ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+&é()è_ç[]{}=^¨,;§!µ%ù£$€&~²";
 
+        /// <summary>
+        /// Capitalize the first letter and lower the others.
+        /// </summary>
+        /// <param name="str">this string</param>
+        /// <returns>The string with the first letter upped and lowered the others</returns>
+        public static string FirstUpperOtherLower(String str)
+        {
+            if (IsNullOrWhiteSpace(str))
+            {
+                return str;
+            }
+
+            String fl = "";
+            if (str.Length >= 1)
+            {
+                fl = str.Substring(0, 1).ToUpper();
+            }
+
+            if (str.Length >= 2)
+            {
+                fl += str.Substring(1).ToLower();
+            }
+
+            return fl;
+        }
 
         /// <summary>
         /// Truncate the string.