Browse Source

StringUtils :
+method SafeSubstring() to cut string without worrying about maximum length
+method SafeEquals() to test strings equality with null.
-remove deprecated methods

ProcessUtils :
+method GoTo() to open explorer and select a file.

DateUtils :
+method LastDayOfMonth to get a DateTime object at the last day of the month of the date passed in input.
+method FirstDayOfMonth to get a DateTime object at the first day of the month of the date passed in input.
+method MaxDateTime to get the most recent date between two.
+method MinDateTime to get the earliest date between two.

New Utils : BooleansContainers
To be used to accumulate booleans and to know the number of true, false, as well as to perform AND and OR operations.

Aryx 3 months ago
parent
commit
44a7eb9de9

+ 3 - 0
AryxDevLibrary.csproj

@@ -31,6 +31,7 @@
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Release\AryxDevLibrary.XML</DocumentationFile>
   </PropertyGroup>
   <PropertyGroup>
     <ApplicationIcon>
@@ -74,6 +75,7 @@
     <Compile Include="extensions\DateUtilsExt.cs" />
     <Compile Include="extensions\StringUtilsExt.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="utils\BooleansContainers.cs" />
     <Compile Include="utils\cliParser\CliParser.cs" />
     <Compile Include="utils\cliParser\CliParserInitException.cs" />
     <Compile Include="utils\cliParser\CliParserLangRef.cs" />
@@ -83,6 +85,7 @@
     <Compile Include="utils\EnumConverter.cs" />
     <Compile Include="utils\EnumEncoding.cs" />
     <Compile Include="utils\EventList.cs" />
+    <Compile Include="utils\ExceptionHandlingUtils.cs" />
     <Compile Include="utils\FileUtils.cs" />
     <Compile Include="utils\logger\Logger.cs" />
     <Compile Include="utils\MiscUtils.cs" />

+ 5 - 1
AryxDevLibrary.sln.DotSettings.user

@@ -1,6 +1,10 @@
 <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+	<s:Boolean x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=1AB069F30A384B78934E0CDF5EB44E58/@KeyIndexDefined">True</s:Boolean>
+	<s:Int64 x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=1AB069F30A384B78934E0CDF5EB44E58/GroupingIndex/@EntryValue">4</s:Int64>
+	<s:String x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=1AB069F30A384B78934E0CDF5EB44E58/Name/@EntryValue">SafeSubstringTest</s:String>
+	<s:String x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=1AB069F30A384B78934E0CDF5EB44E58/XmlSerializedElements/@EntryValue">&lt;Session&gt;&lt;e Id="AryxUtilsTest.DateUtilsTest.SafeSubstringTest" Project="5887C441-06CE-422D-A32C-21A772FEBC7A" Provider="MSTest" /&gt;&lt;e Id="AryxUtilsTest.DateUtilsTest" Project="5887C441-06CE-422D-A32C-21A772FEBC7A" Provider="MSTest" /&gt;&lt;/Session&gt;</s:String>
 	
 	<s:Boolean x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=DFDF32E702B84FA78B33EA1E039F9410/@KeyIndexDefined">True</s:Boolean>
 	<s:Int64 x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=DFDF32E702B84FA78B33EA1E039F9410/GroupingIndex/@EntryValue">4</s:Int64>
 	<s:String x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=DFDF32E702B84FA78B33EA1E039F9410/Name/@EntryValue">TextOrDefault</s:String>
-	<s:String x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=DFDF32E702B84FA78B33EA1E039F9410/XmlSerializedElements/@EntryValue">&lt;Session&gt;&lt;e Id="AryxUtilsTest.DateUtilsTest" Project="5887C441-06CE-422D-A32C-21A772FEBC7A" Provider="MSTest" /&gt;&lt;e Id="AryxUtilsTest.DateUtilsTest.GetRelativePath" Project="5887C441-06CE-422D-A32C-21A772FEBC7A" Provider="MSTest" /&gt;&lt;/Session&gt;</s:String></wpf:ResourceDictionary>
+	<s:String x:Key="/Default/Housekeeping/UnitTestingMru/UnitTestSessionPersistentData/=DFDF32E702B84FA78B33EA1E039F9410/XmlSerializedElements/@EntryValue">&lt;Session&gt;&lt;/Session&gt;</s:String></wpf:ResourceDictionary>

BIN
AryxDevLibrary.v12.suo


+ 8 - 1
AryxDevViewLibrary/AryxDevViewLibrary.csproj

@@ -54,9 +54,16 @@
     <Compile Include="utils\ImageUtils.cs" />
     <Compile Include="utils\MessageBoxUtils.cs" />
     <Compile Include="utils\ShellUtils.cs" />
+    <Compile Include="views\InputBoxView.xaml.cs">
+      <DependentUpon>InputBoxView.xaml</DependentUpon>
+    </Compile>
   </ItemGroup>
+  <ItemGroup />
   <ItemGroup>
-    <Folder Include="views\" />
+    <Page Include="views\InputBoxView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 

+ 18 - 0
AryxDevViewLibrary/views/InputBoxView.xaml

@@ -0,0 +1,18 @@
+<Window x:Class="AryxDevViewLibrary.views.InputBoxView"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        Title="InputBoxView" Width="323.2" ResizeMode="NoResize" SizeToContent="Height">
+    <StackPanel>
+        <TextBlock x:Name="txtContent" Margin="10,10,9.8,10" TextWrapping="Wrap" VerticalAlignment="Top" MinHeight="16">
+            TextBlock T
+
+        </TextBlock>
+        <TextBox x:Name="tboxValue" Height="23"  TextWrapping="Wrap" VerticalAlignment="Top" Margin="10,0,9.8,0"/>
+
+        <Grid Height="35" Margin="0,0,-0.2,0">
+            <Button x:Name="btnOk" Content="OK" HorizontalAlignment="Right" Margin="0,0,9.8,10" VerticalAlignment="Bottom" Width="75" IsDefault="True" Click="btnOk_Click"/>
+            <Button x:Name="btnCancel" Content="Annuler" HorizontalAlignment="Right" Margin="0,0,89.8,10" VerticalAlignment="Bottom" Width="75" IsCancel="True" Click="btnCancel_Click"/>
+        </Grid>
+    </StackPanel>
+</Window>
+

+ 69 - 0
AryxDevViewLibrary/views/InputBoxView.xaml.cs

@@ -0,0 +1,69 @@
+
+
+
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+
+namespace AryxDevViewLibrary.views
+{
+    /// <summary>
+    /// Logique d'interaction pour InputBoxView.xaml
+    /// </summary>
+    public partial class InputBoxView : Window
+    {
+
+        public static String InputBox(string content, string title)
+        {
+            InputBoxView n = new InputBoxView();
+            n.Loads(content, title);
+
+            n.ShowDialog();
+
+            return n.IsOkClose ? n.Value : null;
+        }
+
+        public string Value { get; private set; }
+
+        public bool IsOkClose { get; private set; }
+
+
+        public InputBoxView()
+        {
+            InitializeComponent();
+        }
+
+        private void Loads(string content, string title)
+        {
+            txtContent.Text = content;
+            this.Title = title;
+        }
+
+        private void btnCancel_Click(object sender, RoutedEventArgs e)
+        {
+            IsOkClose = false;
+            Close();
+        }
+
+        private void btnOk_Click(object sender, RoutedEventArgs e)
+        {
+            Value = tboxValue.Text;
+
+            IsOkClose = true;
+            Close();
+        }
+
+
+    }
+}
+

+ 2 - 2
AssemblyTTempl.cs

@@ -6,6 +6,6 @@
 using System.Reflection;
 
 
-[assembly: AssemblyVersion("1.0.4.0")]
-[assembly: AssemblyFileVersion("1.0.4.0")]
+[assembly: AssemblyVersion("1.0.4.331")]
+[assembly: AssemblyFileVersion("1.0.4.331")]
 

+ 20 - 0
extensions/DateUtilsExt.cs

@@ -14,6 +14,26 @@ namespace AryxDevLibrary.extensions
     {
 
         /// <summary>
+        /// Returns the last date of month of a date.
+        /// </summary>
+        /// <param name="date">the date</param>
+        /// <returns></returns>
+        public static DateTime LastDayOfMonth(this DateTime date)
+        {
+            return DateUtils.LastDayOfMonth(date);
+        }
+
+        /// <summary>
+        /// Returns the first date of month of a date.
+        /// </summary>
+        /// <param name="date">the date</param>
+        /// <returns></returns>
+        public static DateTime FirstDayOfMonth(this DateTime date)
+        {
+            return DateUtils.FirstDayOfMonth(date);
+        }
+
+        /// <summary>
         /// Test if a DateTime object is After an other.
         /// </summary>
         /// <param name="date">the date to test is after</param>

+ 6 - 11
extensions/StringUtilsExt.cs

@@ -14,6 +14,12 @@ namespace AryxDevLibrary.extensions
     public static class StringUtilsExt
     {
 
+
+        public static string SafeSubstring(this string str, int startIndex, int lenght)
+        {
+            return StringUtils.SafeSubstring(str, startIndex, lenght);
+        }
+
         /// <summary>
         /// Split a string by another string
         /// </summary>
@@ -61,17 +67,6 @@ namespace AryxDevLibrary.extensions
             return StringUtils.IsEmpty(value);
         }
 
-        /// <summary>
-        /// Truncate the string.
-        /// </summary>
-        /// <param name="str">the string to truncate</param>
-        /// <param name="limit">le lenght to truncate</param>
-        /// <returns></returns>
-        [System.Obsolete("Error type. Use Truncate instead.")]
-        public static string Tronc(this string str, int limit)
-        {
-            return StringUtils.Truncate(str, limit);
-        }
 
         /// <summary>
         /// Truncate the string.

+ 72 - 0
utils/BooleansContainers.cs

@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace AryxDevLibrary.utils
+{
+    /// <summary>
+    /// Liste de booléens. Permet d'utiliser des méthodes les méthodes And() et Or().
+    /// </summary>
+    public class BooleansList
+    {
+
+        private readonly List<bool> _innerList = new List<bool>();
+
+        /// <summary>
+        /// Liste de boolean. Initialisée avec l'instance.
+        /// </summary>
+        public List<bool> List
+        {
+            get { return _innerList; }
+
+        }
+
+
+        /// <summary>
+        /// Permet d'ajouter un booléen à la liste
+        /// </summary>
+        /// <param name="b"></param>
+        public void Add(bool b)
+        {
+            _innerList.Add(b);
+        }
+
+        /// <summary>
+        /// Détermine si tous les éléments sont true.
+        /// </summary>
+        /// <returns></returns>
+        public bool And()
+        {
+            return !_innerList.Contains(false);
+        }
+
+        /// <summary>
+        /// Déterminer s'il existe au moins un élément à true.
+        /// </summary>
+        /// <returns></returns>
+        public bool Or()
+        {
+            return _innerList.Contains(true);
+        }
+
+        /// <summary>
+        /// Compte les éléments à true.
+        /// </summary>
+        /// <returns></returns>
+        public int CountTrue()
+        {
+            return _innerList.Count(r => r);
+        }
+
+        /// <summary>
+        /// Compte les éléments à false.
+        /// </summary>
+        /// <returns></returns>
+        public int CountFalse()
+        {
+            return _innerList.Count(r => !r);
+        }
+
+    }
+}

+ 50 - 0
utils/DateUtils.cs

@@ -2,13 +2,41 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using AryxDevLibrary.extensions;
 
 namespace AryxDevLibrary.utils
 {
+    /// <summary>
+    /// Methods to handle Dates 
+    /// </summary>
     public static class DateUtils
     {
 
         /// <summary>
+        /// Returns the last date of month of a date.
+        /// </summary>
+        /// <param name="date">the date</param>
+        /// <returns></returns>
+        public static DateTime LastDayOfMonth(DateTime date)
+        {
+            DateTime tpDt = date.AddMonths(1);
+            return tpDt.AddDays(-tpDt.Day);
+
+        }
+
+        /// <summary>
+        /// Returns the first date of month of a date.
+        /// </summary>
+        /// <param name="date">the date</param>
+        /// <returns></returns>
+        public static DateTime FirstDayOfMonth(DateTime date)
+        {
+
+            return date.AddDays(-date.Day + 1);
+
+        }
+
+        /// <summary>
         /// Test if a DateTime object is After an other.
         /// </summary>
         /// <param name="date">the date to test is after</param>
@@ -52,5 +80,27 @@ namespace AryxDevLibrary.utils
 
         }
 
+        /// <summary>
+        /// Returns the earliest date between two dates.
+        /// </summary>
+        /// <param name="dateA"></param>
+        /// <param name="dateB"></param>
+        /// <returns></returns>
+        public static DateTime MinDateTime(DateTime dateA, DateTime dateB)
+        {
+            return dateA.IsBefore(dateB) ? dateA : dateB;
+        }
+
+        /// <summary>
+        /// Returns the most recent date between two dates.
+        /// </summary>
+        /// <param name="dateA"></param>
+        /// <param name="dateB"></param>
+        /// <returns></returns>
+        public static DateTime MaxDateTime(DateTime dateA, DateTime dateB)
+        {
+            return dateA.IsBefore(dateB) ? dateB : dateA;
+        }
+
     }
 }

+ 118 - 0
utils/ExceptionHandlingUtils.cs

@@ -0,0 +1,118 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using AryxDevLibrary.utils.logger;
+
+namespace AryxDevLibrary.utils
+{
+    public class ExceptionHandlingUtils
+    {
+        public static Logger Logger
+        {
+            get
+            {
+                if (_logger == null)
+                {
+                    throw new Exception("ExceptionHandlingUtils : for using this class utils, you must set Logger instance to ExceptionHandlingUtils::Logger.");
+                }
+                return _logger;
+            }
+            set { _logger = value; }
+        }
+
+        public static bool ShowStackTrace = true;
+        private static Logger _logger;
+
+        public static void LogAndRethrows(Exception ex, string moreMsg = null)
+        {
+
+
+            Logger.Error("Erreur :");
+            if (moreMsg != null)
+            {
+                Logger.Error(moreMsg);
+            }
+            Logger.Error("Type d'exception : {0}, Message : {1}", ex.GetType().Name, ex.Message);
+
+            if (ShowStackTrace)
+            {
+                Logger.Error("Stack Trace : {0}", ex.StackTrace);
+            }
+            throw ex;
+        }
+
+
+
+
+        public static void LogAndHideException(Exception ex, string moreMsg = null, bool isWarnMsgAndDebugStack = false)
+        {
+            if (!isWarnMsgAndDebugStack)
+            {
+                Logger.Error("Erreur :");
+            }
+            else
+            {
+                Logger.Warn("Erreur :");
+            }
+
+            if (moreMsg != null)
+            {
+                if (!isWarnMsgAndDebugStack)
+                {
+                    Logger.Error(moreMsg);
+                }
+                else
+                {
+                    Logger.Warn(moreMsg);
+                }
+            }
+
+            if (!isWarnMsgAndDebugStack)
+            {
+
+                Logger.Error("Type d'exception : {0}, Message : {1}", ex.GetType().Name, ex.Message);
+                if (ShowStackTrace)
+                {
+                    Logger.Error("Stack Trace : {0}", ex.StackTrace);
+                }
+            }
+            else
+            {
+                Logger.Debug("Type d'exception : {0}, Message : {1}", ex.GetType().Name, ex.Message);
+                Logger.Debug("Stack Trace : {0}", ex.StackTrace);
+            }
+
+
+
+
+        }
+
+        public static void LogAndEndsProgram(Exception ex, int exitCode, string moreMsg = null)
+        {
+            Logger.Error("Erreur fatale :");
+            if (moreMsg != null)
+            {
+                Logger.Error(moreMsg);
+            }
+            Logger.Error("Type d'exception : {0}, Message : {1}", ex.GetType().Name, ex.Message);
+            if (ShowStackTrace)
+            {
+                Logger.Error("Stack Trace : {0}", ex.StackTrace);
+            }
+
+            Environment.Exit(exitCode);
+        }
+
+        public static void LogAndNewException(string moreMsg, Exception innerException = null)
+        {
+            Logger.Error("Erreur :");
+            Logger.Error(moreMsg);
+            throw new Exception(moreMsg, innerException);
+
+        }
+
+
+
+    }
+}

+ 2 - 0
utils/FileUtils.cs

@@ -311,5 +311,7 @@ namespace AryxDevLibrary.utils
         {
             return new StreamWriter(File.Open(filename, filemode), Encoding.GetEncoding(encodingName));
         }
+
+
     }
 }

+ 12 - 0
utils/ProcessUtils.cs

@@ -67,5 +67,17 @@ namespace AryxDevLibrary.utils
 
         }
 
+        /// <summary>
+        /// Open explorer to point a file.
+        /// </summary>
+        /// <param name="text"></param>
+        public static void GoTo(string text)
+        {
+            if (!StringUtils.IsNullOrWhiteSpace(text))
+            {
+                Process.Start(text);
+            }
+        }
+
     }
 }

+ 47 - 0
utils/SevenZipBootstraper.cs

@@ -0,0 +1,47 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace AryxDevLibrary.utils
+{
+    public class SevenZipBootstrapper
+    {
+
+        public string ExecutableFilePath { get; private set; }
+
+        public SevenZipBootstrapper(string exeOf7zFilePath)
+        {
+            ExecutableFilePath = exeOf7zFilePath;
+
+            if (!File.Exists(exeOf7zFilePath))
+            {
+                throw new FileNotFoundException("Exe file of 7z doesn't exist or is not readable", exeOf7zFilePath);
+            }
+
+
+        }
+
+        public static SevenZipArchive CreateArchive(string archiveName)
+        {
+            FileInfo archiveFi = new FileInfo(archiveName);
+            SevenZipArchive s = new SevenZipArchive(archiveFi);
+            return s;
+        }
+
+
+
+        public class SevenZipArchive
+        {
+            public FileInfo ArchiveFile { get; private set; }
+
+            public SevenZipArchive(FileInfo archiveFi)
+            {
+                ArchiveFile = archiveFi;
+            }
+
+
+        }
+    }
+}

+ 27 - 49
utils/StringUtils.cs

@@ -19,6 +19,16 @@ namespace AryxDevLibrary.utils
     "ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+&é()è_ç[]{}=^¨,;§!µ%ù£$€&~²";
         private static List<string> _listRandomString;
 
+
+        public static string SafeSubstring(string str, int startIndex, int lenght)
+        {
+            if (str == null || startIndex >= str.Length) return null;
+
+            return startIndex + lenght >= str.Length ?
+                str.Substring(startIndex)
+                : str.Substring(startIndex, lenght);
+        }
+
         /// <summary>
         /// Cuts a string, and n parts of delimited lengths.
         /// </summary>
@@ -79,55 +89,6 @@ namespace AryxDevLibrary.utils
             return fl;
         }
 
-        /// <summary>
-        /// Truncate the string.
-        /// </summary>
-        /// <param name="str">the string to truncate</param>
-        /// <param name="limit">le lenght to truncate</param>
-        /// <returns>The string with truncate</returns>
-        [Obsolete("Error type. Use Truncate instead.")]
-        public static string Tronc(string str, int limit)
-        {
-            if (str == null)
-            {
-                return null;
-            }
-
-            if (limit == 0)
-            {
-                return "";
-            }
-
-            if (limit > 0)
-            {
-                return str.Substring(0, str.Length < limit ? str.Length : limit);
-            }
-
-            return TroncRight(str, limit);
-        }
-
-        /// <summary>
-        /// Trunc a string from the right if string's lenght greater than defined lenght. A suffix can be use for indicate trunc.
-        /// </summary>
-        /// <param name="str">The string to truncate</param>
-        /// <param name="maxLenght">The length from which to truncate</param>
-        /// <param name="suffix">The suffix to indicate truncate. Default=""</param>
-        /// <returns>The string with truncate</returns>
-        [Obsolete("Error type. Use TruncRight instead.")]
-        public static string TroncRight(string str, int maxLenght, string suffix = "")
-        {
-            int start = maxLenght < str.Length ? str.Length - maxLenght : 0;
-            int lenght = str.Length - start;
-
-            if (start == 0)
-            {
-                return str;
-            }
-            return suffix + str.Substring(start, lenght);
-        }
-
-
-
 
 
         /// <summary>
@@ -324,6 +285,10 @@ namespace AryxDevLibrary.utils
 
             if (ensureUnique)
             {
+                if (_listRandomString == null)
+                {
+                    _listRandomString = new List<string>(1);
+                }
                 while (_listRandomString.Contains(retString))
                 {
                     retString = RandomString(length, charSet, false);
@@ -342,6 +307,19 @@ namespace AryxDevLibrary.utils
             _listRandomString = new List<string>();
         }
 
+        /// <summary>
+        /// Safe string equality. Can handle two null strings
+        /// </summary>
+        /// <param name="strA"></param>
+        /// <param name="strB"></param>
+        /// <returns></returns>
+        public static bool SafeEquals(string strA, string strB)
+        {
+            if (strA == null && strB == null) return true;
+
+            return strA != null && strA.Equals(strB);
+        }
+
 
         /// <summary>
         /// Converts an integer into its textual form. The output is only in France-French.