diff --git a/.github/workflows/dotnetcore.yml b/.github/workflows/dotnetcore.yml index 47d29bc..b11467d 100644 --- a/.github/workflows/dotnetcore.yml +++ b/.github/workflows/dotnetcore.yml @@ -66,6 +66,7 @@ jobs: done shell: bash + - name: push packages (nuget) if: github.event_name == 'push' && startsWith(github.ref, 'refs/heads/v') run: | @@ -80,4 +81,3 @@ jobs: exit 1 fi done - diff --git a/SharpHelpers/SharpHelpers.UnitTest/Byte/ByteTest.cs b/SharpHelpers/SharpHelpers.UnitTest/Byte/ByteTest.cs index 3d4c4bd..d327942 100644 --- a/SharpHelpers/SharpHelpers.UnitTest/Byte/ByteTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/Byte/ByteTest.cs @@ -30,7 +30,7 @@ public void TestToByteArray() Assert.IsNotNull(str); - Assert.IsTrue(obj == (string) str); + Assert.IsTrue(obj == (string)str); } } } diff --git a/SharpHelpers/SharpHelpers.UnitTest/Dictionary/DictionaryTest.cs b/SharpHelpers/SharpHelpers.UnitTest/Dictionary/DictionaryTest.cs index 6e63f7e..b1ebce9 100644 --- a/SharpHelpers/SharpHelpers.UnitTest/Dictionary/DictionaryTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/Dictionary/DictionaryTest.cs @@ -16,24 +16,24 @@ public class DictionaryTest public void TestAddFormat() { var dic = new Dictionary() { { 1, DateTime.Now }, { 2, DateTime.Now } }; - + } [TestMethod] public void TestRemoveAll() { var dic = new Dictionary() { { 1, DateTime.Now }, { 2, DateTime.Now } }; - dic.RemoveAll(a=> a.Key < 2 ); + dic.RemoveAll(a => a.Key < 2); Assert.IsTrue(dic.Count() == 1); } [TestMethod] public void TestGetOrCreate() { - var dic = new Dictionary() { { 1, DateTime.Now }, { 2, DateTime.Now} }; + var dic = new Dictionary() { { 1, DateTime.Now }, { 2, DateTime.Now } }; Assert.IsNotNull(dic.GetOrCreate(1)); Assert.IsNotNull(dic.GetOrCreate(3)); - + } } diff --git a/SharpHelpers/SharpHelpers.UnitTest/Enumerable/EnumerableTest.cs b/SharpHelpers/SharpHelpers.UnitTest/Enumerable/EnumerableTest.cs index 6af529d..81a2866 100644 --- a/SharpHelpers/SharpHelpers.UnitTest/Enumerable/EnumerableTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/Enumerable/EnumerableTest.cs @@ -2,7 +2,6 @@ // This code is licensed under MIT license (see LICENSE.txt for details) using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpCoding.SharpHelpers; -using System; using System.Collections.Generic; using System.Linq; @@ -24,12 +23,12 @@ public void TestAddOrSet() [TestMethod] public void TestDistinctBy() { - var list = new List {10, 5, 10, 6}; + var list = new List { 10, 5, 10, 6 }; var result = list.DistinctBy().ToList(); Assert.IsNotNull(result); Assert.IsTrue(result.Count < list.Count); } - + [TestMethod] public void TestDistinctByPropertySelector() { @@ -38,8 +37,8 @@ public void TestDistinctByPropertySelector() var l3 = new List() { 10, 11 }; var l4 = new List() { 6, 5, 5 }; - var list = new List>(){l1 ,l2 ,l3 ,l4 }; - + var list = new List>() { l1, l2, l3, l4 }; + var result = list.DistinctBy(p => p.Count).ToList(); Assert.IsNotNull(result); Assert.IsTrue(result.Count < list.Count); @@ -61,8 +60,8 @@ public void TestToString() var result = list.ToString(","); Assert.IsNotNull(result); } - - [TestMethod] + + [TestMethod] public void TestIsSerializable() { var list = new List { 10, 5, 10, 6 }; @@ -80,14 +79,14 @@ public void TestGetDuplicates() { var list = new List { 10, 5, 10, 6 }; - var result = list.GetDuplicates(a => a) ; + var result = list.GetDuplicates(a => a); Assert.IsTrue(result.Count() == 1); Assert.IsTrue(result.ToList()[0] == 10); var listN = new List { new NonSerializableObj("Obj1"), new NonSerializableObj("Obj3"), new NonSerializableObj("Obj2"), new NonSerializableObj("Obj2") }; var resultN = listN.GetDuplicates(a => a.Name); Assert.IsTrue(resultN.Count() == 1); - Assert.AreEqual("Obj2",resultN.ToList()[0].Name); + Assert.AreEqual("Obj2", resultN.ToList()[0].Name); } [TestMethod] @@ -109,10 +108,10 @@ public void TestCountDuplicates() public class NonSerializableObj { - + public string Name { get; set; } - - public NonSerializableObj(string name) + + public NonSerializableObj(string name) { this.Name = name; } diff --git a/SharpHelpers/SharpHelpers.UnitTest/File/FileTest.cs b/SharpHelpers/SharpHelpers.UnitTest/File/FileTest.cs index d7380cc..49d850d 100755 --- a/SharpHelpers/SharpHelpers.UnitTest/File/FileTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/File/FileTest.cs @@ -1,7 +1,6 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) using Microsoft.VisualStudio.TestTools.UnitTesting; -using SharpCoding.SharpHelpers; namespace SharpHelpers.UnitTest.File { diff --git a/SharpHelpers/SharpHelpers.UnitTest/Object/ObjectTest.cs b/SharpHelpers/SharpHelpers.UnitTest/Object/ObjectTest.cs index 9669ced..802f694 100644 --- a/SharpHelpers/SharpHelpers.UnitTest/Object/ObjectTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/Object/ObjectTest.cs @@ -2,10 +2,10 @@ // This code is licensed under MIT license (see LICENSE.txt for details) using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpCoding.SharpHelpers; -using System; -using System.Collections.Generic; using SharpCoding.SharpHelpers.ObjectExtensions; using SharpHelpers.UnitTest.Mock; +using System; +using System.Collections.Generic; using static SharpHelpers.UnitTest.TestClass.JsonClassTest; namespace SharpHelpers.UnitTest.Object @@ -17,11 +17,11 @@ public class ObjectTest public void TestIsSystemType() { var guid = new Guid(); - + Assert.IsTrue(guid.GetType().IsSystemType()); - + var glossary = new Glossary(); - + Assert.IsFalse(glossary.GetType().IsSystemType()); } @@ -41,7 +41,7 @@ public void TestClone() var f1Str = foo1.SerializeToJson(); var f2Str = foo2.SerializeToJson(); - Assert.IsTrue(f1Str==f2Str); + Assert.IsTrue(f1Str == f2Str); var foo21 = new Foo2 { @@ -56,7 +56,7 @@ public void TestClone() var f11Str = foo21.SerializeToJson(); var f22Str = foo22.SerializeToJson(); - Assert.IsTrue(f11Str==f22Str); + Assert.IsTrue(f11Str == f22Str); var foo31 = new Foo2() { @@ -66,12 +66,12 @@ public void TestClone() FooItem = foo1 }; - var foo32 = foo31.Clone(new List {"Prop1"}); + var foo32 = foo31.Clone(new List { "Prop1" }); var f31Str = foo31.SerializeToJson(); var f32Str = foo32.SerializeToJson(); - Assert.IsTrue(f31Str!=f32Str); + Assert.IsTrue(f31Str != f32Str); Assert.IsTrue(string.IsNullOrEmpty(foo32.Prop1) && string.IsNullOrEmpty(foo32.FooItem.Prop1)); } diff --git a/SharpHelpers/SharpHelpers.UnitTest/String/StringTest.cs b/SharpHelpers/SharpHelpers.UnitTest/String/StringTest.cs index c3abd62..741d88c 100755 --- a/SharpHelpers/SharpHelpers.UnitTest/String/StringTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/String/StringTest.cs @@ -1,11 +1,10 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) -using System.Globalization; -using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpCoding.SharpHelpers; using SharpCoding.SharpHelpers.DomainModel; +using System.Globalization; using static SharpHelpers.UnitTest.TestClass.JsonClassTest; namespace SharpHelpers.UnitTest.String diff --git a/SharpHelpers/SharpHelpers.UnitTest/TestClass/JsonClassTest.cs b/SharpHelpers/SharpHelpers.UnitTest/TestClass/JsonClassTest.cs index 2c5baa2..ea41531 100755 --- a/SharpHelpers/SharpHelpers.UnitTest/TestClass/JsonClassTest.cs +++ b/SharpHelpers/SharpHelpers.UnitTest/TestClass/JsonClassTest.cs @@ -1,8 +1,6 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) -using System; using System.Collections.Generic; -using System.Text; namespace SharpHelpers.UnitTest.TestClass { diff --git a/SharpHelpers/SharpHelpers/ByteHelper.cs b/SharpHelpers/SharpHelpers/ByteHelper.cs index 0dbe83a..6191299 100644 --- a/SharpHelpers/SharpHelpers/ByteHelper.cs +++ b/SharpHelpers/SharpHelpers/ByteHelper.cs @@ -7,7 +7,7 @@ namespace SharpCoding.SharpHelpers { public static class ByteHerlper - { + { /// /// Given a byte array, this method returns the specified object /// diff --git a/SharpHelpers/SharpHelpers/DateTimeHelper.cs b/SharpHelpers/SharpHelpers/DateTimeHelper.cs index 63260e6..1207d58 100644 --- a/SharpHelpers/SharpHelpers/DateTimeHelper.cs +++ b/SharpHelpers/SharpHelpers/DateTimeHelper.cs @@ -1,8 +1,8 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) using System; -using System.Globalization; - +using System.Globalization; + namespace SharpCoding.SharpHelpers { public static class DateTimeHelper @@ -46,56 +46,53 @@ public static DateTime AbsoluteEnd(this DateTime dateTime) public static DateTime? ToUniversalTime(this DateTime? dateTime) { return dateTime?.ToUniversalTime(); - } - - /// - /// Return the start of the current day - /// - /// - /// - public static DateTime GetStartOfDay(this DateTime dateTime) - { - return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0); } - /// - /// Return the end of the current day - /// - /// + /// + /// Return the start of the current day + /// + /// /// - public static DateTime GetEndOfDay(this DateTime dateTime) - { - return new DateTime(dateTime.Year, dateTime.Month, - dateTime.Day, 23, 59, 59, 999); + public static DateTime GetStartOfDay(this DateTime dateTime) + { + return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0); } - /// - /// Try to parse the string value with specific DateTime formats - /// - /// - /// + /// + /// Return the end of the current day + /// + /// /// - public static DateTime? AsDateTime(this string value, string[] formats) - { - if (DateTime.TryParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, - out DateTime utcDateTime)) - { - return utcDateTime; - } - - return null; + public static DateTime GetEndOfDay(this DateTime dateTime) + { + return new DateTime(dateTime.Year, dateTime.Month, + dateTime.Day, 23, 59, 59, 999); } - /// - /// Check if a date is between two dates - /// - /// - /// - /// + /// + /// Try to parse the string value with specific DateTime formats + /// + /// + /// /// - public static bool IsBetween(this DateTime dt, DateTime rangeBeg, DateTime rangeEnd) - { - return dt.Ticks >= rangeBeg.Ticks && dt.Ticks <= rangeEnd.Ticks; + public static DateTime? AsDateTime(this string value, string[] formats) + { + if (DateTime.TryParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, + out var utcDateTime)) return utcDateTime; + + return null; + } + + /// + /// Check if a date is between two dates + /// + /// + /// + /// + /// + public static bool IsBetween(this DateTime dt, DateTime rangeBeg, DateTime rangeEnd) + { + return dt.Ticks >= rangeBeg.Ticks && dt.Ticks <= rangeEnd.Ticks; } } } diff --git a/SharpHelpers/SharpHelpers/DictionaryHelper.cs b/SharpHelpers/SharpHelpers/DictionaryHelper.cs index 2a61b50..0e911fb 100644 --- a/SharpHelpers/SharpHelpers/DictionaryHelper.cs +++ b/SharpHelpers/SharpHelpers/DictionaryHelper.cs @@ -1,68 +1,85 @@ // (c) 2019 SharpCoding -// This code is licensed under MIT license (see LICENSE.txt for details) +// This code is licensed under MIT license (see LICENSE.txt for details) using System; -using System.Collections.Generic; -using System.Linq; - -namespace SharpCoding.SharpHelpers -{ - public static class DictionaryHelper - { - /// - /// This method add the TKey with the specific format - /// - /// - /// - /// - /// - /// - public static void AddFormat(this Dictionary dictionary, - TKey key, - string formatString, - params object[] argList) - { - if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); - dictionary.Add(key, string.Format(formatString, argList)); - } - - /// - /// This method remove items by the specific predicate - /// - /// - /// - /// - /// - public static void RemoveAll(this Dictionary dictionary, - Func, bool> condition) - { - if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); - if (condition == null) throw new ArgumentNullException(nameof(condition)); - - foreach (var cur in dictionary.Where(condition).ToList()) - { - dictionary.Remove(cur.Key); - } - } - - /// - /// This method get or create the value related to the specific key - /// - /// - /// - /// - /// - /// - public static TValue GetOrCreate(this IDictionary dictionary, - TKey key) where TValue : new() - { - if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); - - if (!dictionary.TryGetValue(key, out TValue ret)) - { - ret = new TValue(); - dictionary[key] = ret; - } - return ret; - } - } -} +using System.Collections.Generic; +using System.Linq; + +namespace SharpCoding.SharpHelpers +{ + public static class DictionaryHelper + { + /// + /// This method add the TKey with the specific format + /// + /// + /// + /// + /// + /// + public static void AddFormat(this Dictionary dictionary, + TKey key, + string formatString, + params object[] argList) + { + if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); + dictionary.Add(key, string.Format(formatString, argList)); + } + + /// + /// This method remove items by the specific predicate + /// + /// + /// + /// + /// + public static void RemoveAll(this Dictionary dictionary, + Func, bool> condition) + { + if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); + if (condition == null) throw new ArgumentNullException(nameof(condition)); + + foreach (var cur in dictionary.Where(condition).ToList()) + { + dictionary.Remove(cur.Key); + } + } + + /// + /// This method get or create the value related to the specific key + /// + /// + /// + /// + /// + /// + public static TValue GetOrCreate(this IDictionary dictionary, + TKey key) where TValue : new() + { + if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); + + if (!dictionary.TryGetValue(key, out TValue ret)) + { + ret = new TValue(); + dictionary[key] = ret; + } + return ret; + } + + /// + /// This method get the value related to the specific key or a default value + /// + /// + /// + /// + /// + /// + /// + public static TValue GetOrCreate(this IDictionary dictionary, + TKey key, TValue defaultValue) where TValue : new() + { + if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); + + return !dictionary.TryGetValue(key, out var ret) ? defaultValue : ret; + } + } +} diff --git a/SharpHelpers/SharpHelpers/DomainModel/EnumClasses.cs b/SharpHelpers/SharpHelpers/DomainModel/EnumClasses.cs index e5a3b3c..29ecf8e 100644 --- a/SharpHelpers/SharpHelpers/DomainModel/EnumClasses.cs +++ b/SharpHelpers/SharpHelpers/DomainModel/EnumClasses.cs @@ -5,6 +5,7 @@ namespace SharpCoding.SharpHelpers.DomainModel public enum CleanTextMode { AllHtmlTags, - ScriptTagx + ScriptTagx, + None } } diff --git a/SharpHelpers/SharpHelpers/EnumHelper.cs b/SharpHelpers/SharpHelpers/EnumHelper.cs deleted file mode 100755 index bcf9832..0000000 --- a/SharpHelpers/SharpHelpers/EnumHelper.cs +++ /dev/null @@ -1,95 +0,0 @@ -// (c) 2019 SharpCoding -// This code is licensed under MIT license (see LICENSE.txt for details) -using System; -using System.ComponentModel; -using System.Linq; - -namespace SharpCoding.SharpHelpers -{ - public static class EnumHelper - { - /// - /// This method returns the description as string of the enum that invokes the method - /// - /// - /// - public static string GetDescription(this Enum value) - { - var description = GetAttribute(value); - return description?.Description; - } - - /// - /// This method returns the specific attribute of type TAttribute of the Enum that invokes the method, - /// - /// - /// - /// - public static TAttribute GetAttribute(this Enum value) - where TAttribute : Attribute - { - - var type = value.GetType(); - var name = Enum.GetName(type, value); - return type.GetField(name) - .GetCustomAttributes(false) - .OfType() - .SingleOrDefault(); - } - - /// - /// This method returns the default value of the specified TEnum - /// - /// - /// - public static TEnum GetDefaultValue() where TEnum : struct - { - var t = typeof(TEnum); - var attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false); - if (attributes.Length > 0) - { - return (TEnum)attributes[0].Value; - } - return default; - } - - /// - /// this method returns the specified struct T from the string that invokes the method - /// If the value is null or T is not an enum, the method returns the default value of the T - /// - /// - /// - /// - public static T GetEnumFromDescription(this string value) where T : struct - { - var enumStringValue = string.Empty; - var enumType = typeof (T); - - if ((!enumType.IsEnum) || string.IsNullOrEmpty(value)) - return default; - - foreach (var fieldInfo in enumType.GetFields()) - { - //Get the StringValueAttribute for each enum member - if (fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), - false) is DescriptionAttribute[] attribs && attribs.Length > 0) - enumStringValue = attribs[0].Description; - - if (string.Compare(enumStringValue, value, StringComparison.OrdinalIgnoreCase) == 0) - return (T)Enum.Parse(enumType, fieldInfo.Name); - } - return default; - } - - /// - /// Given a string this method returns the parsed enum T - /// - /// - /// - /// - public static T ParseEnum(string value) - { - return (T)Enum.Parse(typeof(T), value, true); - } - } -} diff --git a/SharpHelpers/SharpHelpers/EnumerableHelper.cs b/SharpHelpers/SharpHelpers/EnumerableHelper.cs index 0b5423b..ca3d512 100644 --- a/SharpHelpers/SharpHelpers/EnumerableHelper.cs +++ b/SharpHelpers/SharpHelpers/EnumerableHelper.cs @@ -2,10 +2,11 @@ // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; namespace SharpCoding.SharpHelpers -{ +{ public static class EnumerableHelper { /// @@ -49,16 +50,16 @@ public static IEnumerable DistinctBy(this IEnumerable enumerable) /// public static IEnumerable GetDuplicates(this IEnumerable enumerable, Func propertySelector) { - if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); - if (propertySelector == null) throw new ArgumentNullException(nameof(propertySelector)); - - var enumer = enumerable - .GroupBy(propertySelector) - .Where(k=>k.Count()>1) - .Select(g =>(T)g.First()); - + if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); + if (propertySelector == null) throw new ArgumentNullException(nameof(propertySelector)); + + var enumer = enumerable + .GroupBy(propertySelector) + .Where(k => k.Count() > 1) + .Select(g => (T)g.First()); + return enumer; - + } /// @@ -76,7 +77,7 @@ public static int CountDuplicates(this IEnumerable enumerable, Func k.Count() > 1) .Select(g => g.Count()).Sum(); - + } /// @@ -88,9 +89,9 @@ public static int CountDuplicates(this IEnumerable enumerable, Func /// public static bool AddOrSet(this IEnumerable enumerable, int index, T value) - { + { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); - + if ((enumerable as List).Count < index) return false; if ((enumerable as List).Count > index) { @@ -98,7 +99,7 @@ public static bool AddOrSet(this IEnumerable enumerable, int index, T valu return true; } (enumerable as List).Add(value); - + return true; } @@ -109,7 +110,7 @@ public static bool AddOrSet(this IEnumerable enumerable, int index, T valu /// /// public static bool IsSerializable(this IEnumerable enumerable) - { + { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); return enumerable.All(item => item.GetType().IsSerializable); @@ -148,5 +149,89 @@ public static IEnumerable> Split(this IEnumerable enumerable, int } return splitList; } + + /// + /// This method returns the description as string of the enum that invokes the method + /// + /// + /// + public static string GetDescription(this Enum value) + { + var description = GetAttribute(value); + return description?.Description; + } + + /// + /// This method returns the specific attribute of type TAttribute of the Enum that invokes the method, + /// + /// + /// + /// + public static TAttribute GetAttribute(this Enum value) + where TAttribute : Attribute + { + + var type = value.GetType(); + var name = Enum.GetName(type, value); + return type.GetField(name) + .GetCustomAttributes(false) + .OfType() + .SingleOrDefault(); + } + + /// + /// This method returns the default value of the specified TEnum + /// + /// + /// + public static TEnum GetDefaultValue() where TEnum : struct + { + var t = typeof(TEnum); + var attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false); + if (attributes.Length > 0) + { + return (TEnum)attributes[0].Value; + } + return default; + } + + /// + /// this method returns the specified struct T from the string that invokes the method + /// If the value is null or T is not an enum, the method returns the default value of the T + /// + /// + /// + /// + public static T GetEnumFromDescription(this string value) where T : struct + { + var enumStringValue = string.Empty; + var enumType = typeof(T); + + if ((!enumType.IsEnum) || string.IsNullOrEmpty(value)) + return default; + + foreach (var fieldInfo in enumType.GetFields()) + { + //Get the StringValueAttribute for each enum member + if (fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), + false) is DescriptionAttribute[] attribs && attribs.Length > 0) + enumStringValue = attribs[0].Description; + + if (string.Compare(enumStringValue, value, StringComparison.OrdinalIgnoreCase) == 0) + return (T)Enum.Parse(enumType, fieldInfo.Name); + } + return default; + } + + /// + /// Given a string this method returns the parsed enum T + /// + /// + /// + /// + public static T ParseEnum(string value) + { + return (T)Enum.Parse(typeof(T), value, true); + } } } diff --git a/SharpHelpers/SharpHelpers/FileHelper.cs b/SharpHelpers/SharpHelpers/FileHelper.cs index 5b67844..8d00386 100644 --- a/SharpHelpers/SharpHelpers/FileHelper.cs +++ b/SharpHelpers/SharpHelpers/FileHelper.cs @@ -68,7 +68,6 @@ public static long GetFileLenght(this string url) return fi.Length; } - /// /// The method returns true if the file is already in use and locked /// @@ -152,6 +151,32 @@ public static string ToFileSize(this long size) if (size < Math.Pow(1024, 6)) { return (size / Math.Pow(1024, 5)).ToString("F0") + "PB"; } return (size / Math.Pow(1024, 6)).ToString("F0") + "EB"; } + + /// + /// Return the file size metric + /// + /// + /// + public static string ToFileSize(this int size) + { + if (size < 1024) { return (size).ToString("F0") + " bytes"; } + if (size < Math.Pow(1024, 2)) { return (size / 1024).ToString("F0") + "KB"; } + if (size < Math.Pow(1024, 3)) { return (size / Math.Pow(1024, 2)).ToString("F0") + "MB"; } + if (size < Math.Pow(1024, 4)) { return (size / Math.Pow(1024, 3)).ToString("F0") + "GB"; } + if (size < Math.Pow(1024, 5)) { return (size / Math.Pow(1024, 4)).ToString("F0") + "TB"; } + if (size < Math.Pow(1024, 6)) { return (size / Math.Pow(1024, 5)).ToString("F0") + "PB"; } + return (size / Math.Pow(1024, 6)).ToString("F0") + "EB"; + } + + /// + /// Return the file size metric + /// + /// + /// + public static string ToFileSize(this string fileUri) + { + return fileUri.GetFileLenght().ToFileSize(); + } } /// diff --git a/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectCloneHelper.cs b/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectCloneHelper.cs index a67391d..a4f01b3 100644 --- a/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectCloneHelper.cs +++ b/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectCloneHelper.cs @@ -19,12 +19,12 @@ public static class ObjectCloneHelper #endregion - public static T Clone(this object istance,ICollection propertyExcludeList = null) + public static T Clone(this object istance, ICollection propertyExcludeList = null) { if (istance == null) return default; - return (T) DeepClone(istance,propertyExcludeList); + return (T)DeepClone(istance, propertyExcludeList); } public static object Clone(this object istance) @@ -35,14 +35,14 @@ public static object Clone(this object istance) #region Privat Method Deep Clone // Clone the object Properties and its children recursively - private static object DeepClone(object istance,ICollection propertyExcludeList = null) + private static object DeepClone(object istance, ICollection propertyExcludeList = null) { var desireObjectToBeCloned = istance; var primaryType = istance.GetType(); if (primaryType.IsArray) - return ((Array) desireObjectToBeCloned).Clone(); + return ((Array)desireObjectToBeCloned).Clone(); object tObject = desireObjectToBeCloned as IList; if (tObject != null) @@ -51,14 +51,14 @@ private static object DeepClone(object istance,ICollection propertyExclu // Get the IList Type of the object var customList = typeof(List<>).MakeGenericType ((properties[properties.Length - 1]).PropertyType); - tObject = (IList) Activator.CreateInstance(customList); - var list = (IList) tObject; + tObject = (IList)Activator.CreateInstance(customList); + var list = (IList)tObject; // loop throw each object in the list and clone it - foreach (var item in ((IList) desireObjectToBeCloned)) + foreach (var item in ((IList)desireObjectToBeCloned)) { if (item == null) continue; - var value = DeepClone(item,propertyExcludeList); + var value = DeepClone(item, propertyExcludeList); list?.Add(value); } } @@ -73,8 +73,8 @@ private static object DeepClone(object istance,ICollection propertyExclu var fields = desireObjectToBeCloned.GetType().GetFields(Binding); foreach (var property in fields) { - if((propertyExcludeList!=null) && (propertyExcludeList.Any())) - if (propertyExcludeList.Contains(property.Name.ExtractBetween("<",">")?.FirstOrDefault())) + if ((propertyExcludeList != null) && (propertyExcludeList.Any())) + if (propertyExcludeList.Contains(property.Name.ExtractBetween("<", ">")?.FirstOrDefault())) continue; if (property.IsInitOnly) // Validate if the property is a writable one. @@ -82,7 +82,7 @@ private static object DeepClone(object istance,ICollection propertyExclu var value = property.GetValue(desireObjectToBeCloned); if (property.FieldType.IsClass && property.FieldType != typeof(string)) tObject.GetType().GetField(property.Name, Binding)?.SetValue - (tObject, DeepClone(value,propertyExcludeList)); + (tObject, DeepClone(value, propertyExcludeList)); else tObject.GetType().GetField(property.Name, Binding)?.SetValue(tObject, value); } diff --git a/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectConverterHelper.cs b/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectConverterHelper.cs index c61694c..b15e07d 100755 --- a/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectConverterHelper.cs +++ b/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectConverterHelper.cs @@ -18,7 +18,7 @@ public static int ToInt32(this object istance) return valueTemp.ToInt32(); } - public static int ToInt32(this Enum istance ) + public static int ToInt32(this Enum istance) { return Convert.ToInt32(istance); } @@ -39,7 +39,7 @@ public static long ToInt64(this object istance) return valueTemp.ToInt64(); } - public static long ToInt64(this Enum istance ) + public static long ToInt64(this Enum istance) { return Convert.ToInt64(istance); } @@ -54,7 +54,7 @@ public static bool ToBoolean(this string istance) { return bool.TryParse(istance, out var outValue) && outValue; } - + public static DateTime ToDateTime(this string istance) { return DateTime.TryParse(istance, out var outValue) ? outValue : default; @@ -62,12 +62,12 @@ public static DateTime ToDateTime(this string istance) public static T ToEnum(this string istance) { - return (T) Enum.Parse(typeof (T), istance); + return (T)Enum.Parse(typeof(T), istance); } - public static T ToObject(this byte[] istance) where T:class + public static T ToObject(this byte[] istance) where T : class { - return (T) istance.ToObject(); + return (T)istance.ToObject(); } private static object ToObject(this byte[] istance) @@ -75,7 +75,7 @@ private static object ToObject(this byte[] istance) using (var memoryStream = new MemoryStream(istance)) { var binaryFormatter = new BinaryFormatter(); - + return binaryFormatter.Deserialize(memoryStream); } } @@ -104,6 +104,13 @@ public static string ToBase(this int number, int targetBase) return rtn.PadLeft(5, '0'); } + public static Guid ToGuid(this object value) + { + var isValidLong = Guid.TryParse(value.ToString(), out var result); + + return isValidLong ? result : Guid.Empty; + } + /// /// This method returns the byte array of the specific object /// @@ -114,11 +121,9 @@ public static byte[] ToByteArray(this object obj) if (obj == null) return null; var binaryFormatter = new BinaryFormatter(); - using (var memoryStream = new MemoryStream()) - { - binaryFormatter.Serialize(memoryStream, obj); - return memoryStream.ToArray(); - } + using var memoryStream = new MemoryStream(); + binaryFormatter.Serialize(memoryStream, obj); + return memoryStream.ToArray(); } } } diff --git a/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectSerializationhelper.cs b/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectSerializationhelper.cs index f7bcc05..89a92c7 100755 --- a/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectSerializationhelper.cs +++ b/SharpHelpers/SharpHelpers/ObjectExtensions/ObjectSerializationhelper.cs @@ -1,9 +1,9 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) +using Newtonsoft.Json; using System.IO; using System.Xml; using System.Xml.Serialization; -using Newtonsoft.Json; namespace SharpCoding.SharpHelpers.ObjectExtensions { diff --git a/SharpHelpers/SharpHelpers/PrivateMethods/InnerClasses.cs b/SharpHelpers/SharpHelpers/PrivateMethods/InnerClasses.cs index 82e46b8..865f0ea 100644 --- a/SharpHelpers/SharpHelpers/PrivateMethods/InnerClasses.cs +++ b/SharpHelpers/SharpHelpers/PrivateMethods/InnerClasses.cs @@ -1,16 +1,34 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) + +using System.Linq; using System.Text.RegularExpressions; namespace SharpCoding.SharpHelpers.PrivateMethods { public static class InnerClassesExtension { - internal static string StripHtml(this string input) + //internal static string StripHtml(this string input) + //{ + // return string.IsNullOrEmpty(input) + // ? string.Empty + // : Regex.Replace(input, "<.*?>", string.Empty); + //} + + internal static string StripHtml(this string input, params string[] allowedTags) { - return string.IsNullOrEmpty(input) - ? string.Empty - : Regex.Replace(input, "<.*?>", string.Empty); + if (string.IsNullOrEmpty(input)) return input; + + MatchEvaluator evaluator = m => string.Empty; + input = Regex.Replace(input, @"<%[^>]+?\/?%>", evaluator); + + if (allowedTags != null && allowedTags.Length > 0) + { + Regex reAllowed = new Regex(string.Format(@"^<(?:{0})\b|\/(?:{0})>$", string.Join("|", allowedTags.Select(x => Regex.Escape(x)).ToArray()))); + evaluator = m => reAllowed.IsMatch(m.Value) ? m.Value : string.Empty; + } + + return Regex.Replace(Regex.Replace(input, @"<[^>]+?\/?>", evaluator), @"[\s\r\n]+", " "); } internal static string RemoveScriptTag(this string input) diff --git a/SharpHelpers/SharpHelpers/RegexHelper.cs b/SharpHelpers/SharpHelpers/RegexHelper.cs index 37f8f6a..e1c4abc 100755 --- a/SharpHelpers/SharpHelpers/RegexHelper.cs +++ b/SharpHelpers/SharpHelpers/RegexHelper.cs @@ -4,7 +4,7 @@ namespace SharpCoding.SharpHelpers { - public static class RegexHelper + public static class RegexHelper { /// /// Return true if the value match the Regex pattern diff --git a/SharpHelpers/SharpHelpers/StringHelper.cs b/SharpHelpers/SharpHelpers/StringHelper.cs index 74ba2f5..58a406f 100644 --- a/SharpHelpers/SharpHelpers/StringHelper.cs +++ b/SharpHelpers/SharpHelpers/StringHelper.cs @@ -1,14 +1,16 @@ // (c) 2019 SharpCoding // This code is licensed under MIT license (see LICENSE.txt for details) +using Newtonsoft.Json; +using SharpCoding.SharpHelpers.DomainModel; +using SharpCoding.SharpHelpers.PrivateMethods; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; -using Newtonsoft.Json; using System.Text.RegularExpressions; -using SharpCoding.SharpHelpers.DomainModel; -using SharpCoding.SharpHelpers.PrivateMethods; +using System.Web; +using System.Xml; namespace SharpCoding.SharpHelpers { @@ -155,6 +157,94 @@ public static string Truncate(this string str, int maxLength, out bool truncated return substr; } + public static string ReplaceNotAsciiChar(this string input) + { + return input.Replace("’", "'").Replace("“", "\"") + .Replace("”", "\"") + .Replace("\r", "") + .Replace("\n", " "); + } + + public static string StripHtmlTags(string source) + { + if (string.IsNullOrEmpty(source)) + { + return string.Empty; + } + + var array = new char[source.Length]; + int arrayIndex = 0; + bool inside = false; + for (int i = 0; i < source.Length; i++) + { + char let = source[i]; + if (let == '<') + { + inside = true; + continue; + } + + if (let == '>') + { + inside = false; + continue; + } + + if (!inside) + { + array[arrayIndex] = let; + arrayIndex++; + } + } + + return new string(array, 0, arrayIndex); + } + + public static string Truncate(this string istance, int maxLength, string suffix = "...") + { + if (string.IsNullOrEmpty(istance)) return string.Empty; + + var temStr = istance; + + var tagRegex = new Regex(@"<[^>]+>"); + var hasTags = tagRegex.IsMatch(istance); + + var cleanLenght = hasTags ? temStr.StripHtml().Length : temStr.Length; + + var diff = temStr.Length - cleanLenght; + + var minValue = Math.Min(cleanLenght, maxLength); + + if (cleanLenght <= minValue) return temStr; + + var myTempStr = temStr.Substring(0, minValue + diff).TrimEnd(); + + hasTags = tagRegex.IsMatch(myTempStr); + + int firstSpaceFromRight; + + if (hasTags) + { + var indexOfTruncateTag = myTempStr.LastIndexOf(">", StringComparison.OrdinalIgnoreCase)+1; + var indexOfTruncate = myTempStr.LastIndexOf(" ", StringComparison.OrdinalIgnoreCase); + firstSpaceFromRight = Math.Max(indexOfTruncateTag, indexOfTruncate); + } + else + { + firstSpaceFromRight = myTempStr.LastIndexOf(" ", StringComparison.OrdinalIgnoreCase); + } + + var outcome = myTempStr.Substring(0, firstSpaceFromRight) + suffix; + + if(hasTags && (outcome.Length-suffix.Length)>maxLength+diff) + return myTempStr.Truncate(maxLength, suffix); + + if (!hasTags && outcome.Length-suffix.Length > maxLength) + return myTempStr.Truncate(maxLength, suffix); + + return outcome; + } + /// /// The method parses the instance to a nullable int /// @@ -307,19 +397,33 @@ public static bool IsValidUrl(this string str) /// This method clears string from Html Tags or from block /// /// - /// CleanTextMode option: AllHtmlTags/ScriptTags + /// CleanTextMode option: AllHtmlTags/ScriptTags/None + /// /// Thrown when a not supported value is passed for /// Cleared string - public static string CleanText(this string input,CleanTextMode mode) + public static string CleanText(this string input, CleanTextMode mode, params string[] htmlTagsPermitted) { return mode switch { - CleanTextMode.AllHtmlTags => input.StripHtml(), + CleanTextMode.AllHtmlTags => input.StripHtml(htmlTagsPermitted), CleanTextMode.ScriptTagx => input.RemoveScriptTag(), - _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null), + CleanTextMode.None => input, + _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null) }; } + /// + /// This method converts a string to an HTML-encoded string and clears it + /// + /// + /// CleanTextMode option: AllHtmlTags/ScriptTags + /// Thrown when a not supported value is passed for + /// Cleared and HTML-encoded string + public static string HtmlEncode(this string input, CleanTextMode mode) + { + return string.IsNullOrEmpty(input) ? input : HttpUtility.HtmlEncode(input.CleanText(mode)); + } + /// /// Gets the matches between delimiters. /// @@ -328,7 +432,7 @@ public static string CleanText(this string input,CleanTextMode mode) /// The end string delimiter. /// - public static IEnumerable ExtractBetween(this string input,string beginDelim, string endDelim) + public static IEnumerable ExtractBetween(this string input, string beginDelim, string endDelim) { var reg = new Regex($"(?<={Regex.Escape(beginDelim)})(.+?)(?={Regex.Escape(endDelim)})"); var matches = reg.Matches(input); @@ -364,15 +468,49 @@ public static bool IsSqlInjection(this string input) /// Returns an int from an input string. /// /// - public static int ToInt32(this string value,CultureInfo culture = null) + public static int ToInt32(this string value, CultureInfo culture = null) { var isValidInt = int.TryParse(value, NumberStyles.AllowThousands | NumberStyles.AllowParentheses | - NumberStyles.AllowCurrencySymbol| + NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, culture ?? CultureInfo.CurrentCulture, out var result); return isValidInt ? result : 0; } + + /// + /// Returns a long from an input string. + /// + /// + public static long ToLong(this string value, CultureInfo culture = null) + { + var isValidLong = long.TryParse(value, NumberStyles.AllowThousands | + NumberStyles.AllowParentheses | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowLeadingSign, culture ?? CultureInfo.CurrentCulture, + out var result); + + return isValidLong ? result : 0; + } + + + /// + /// Returns a Guid from an input string. + /// + /// + public static Guid ToGuid(this string value) + { + var isValidLong = Guid.TryParse(value, out var result); + + return isValidLong ? result : Guid.Empty; + } + + /// + /// + public static bool StringEquals(this string value,string valueToCompare,StringComparison compareOption=StringComparison.OrdinalIgnoreCase) + { + return string.Equals(value, valueToCompare, compareOption); + } } } diff --git a/version.json b/version.json index 3313b11..746baa7 100644 --- a/version.json +++ b/version.json @@ -1,13 +1,11 @@ { "$schema": "https://raw.githubusercontent.com/AArnott/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", - "version": "1.0-beta", + "version": "1.0", "publicReleaseRefSpec": [ "^refs/heads/master$", - "^refs/heads/v\\d+(?:\\.\\d+)?$" + "^refs/heads/v\\d+\\.\\d+" ], - "cloudBuild": { - "buildNumber": { - "enabled": false - } + "nugetPackageVersion": { + "semVer": 2 } -} +} \ No newline at end of file