diff --git a/ExtensionsEx.cs b/ExtensionsEx.cs index e5b9d53..ae86166 100644 --- a/ExtensionsEx.cs +++ b/ExtensionsEx.cs @@ -1,25 +1,25 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 27-08-2016 -// -// Last Modified By : Frede H. -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** @@ -27,23 +27,22 @@ using System; using System.Collections.Generic; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Class ExtensionsEx. +/// +public static class ExtensionsEx { /// - /// Class ExtensionsEx. + /// ForEach loop /// - public static class ExtensionsEx + /// + /// The items. + /// The action. + public static void ForEach(this IEnumerable items, Action action) { - /// - /// ForEach loop - /// - /// - /// The items. - /// The action. - public static void ForEach(this IEnumerable items, Action action) - { - foreach (var item in items) - action(item); - } + foreach (var item in items) + action(item); } } \ No newline at end of file diff --git a/Generators.cs b/Generators.cs index 3e8644f..96cf7a8 100644 --- a/Generators.cs +++ b/Generators.cs @@ -1,25 +1,25 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 2020-07-01 -// -// Last Modified By : FH -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2023 02 02 06:59 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2023-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** @@ -29,295 +29,292 @@ using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Generators +/// +public static class Generators { /// - /// Generators + /// Generate 6 character shortUrl /// - public static class Generators + /// of 6 characters + public static string ShortUrlGenerator() { - /// - /// Generate 6 character shortUrl - /// - /// of 6 characters - public static string ShortUrlGenerator() + return ShortUrlGenerator(6); + } + + /// + /// Generate shortUrl with length + /// + /// The length. + /// + /// derived from https://sourceforge.net/projects/shorturl-dotnet/ + public static string ShortUrlGenerator(int length) + { + const string charsLower = "abcdefghijkmnopqrstuvwxyz"; + const string charsUpper = "ABCDFEGHJKLMNPQRSTUVWXYZ-"; + const string charsNumeric = "1234567890"; + + // Create a local array containing supported short-url characters + // grouped by types. + var charGroups = new[] { - return ShortUrlGenerator(6); - } + charsLower.ToCharArray(), + charsUpper.ToCharArray(), + charsNumeric.ToCharArray() + }; - /// - /// Generate shortUrl with length - /// - /// The length. - /// - /// derived from https://sourceforge.net/projects/shorturl-dotnet/ - public static string ShortUrlGenerator(int length) + // Use this array to track the number of unused characters in each + // character group. + var charsLeftInGroup = new int[charGroups.Length]; + + // Initially, all characters in each group are not used. + for (var i = 0; i < charsLeftInGroup.Length; i++) + charsLeftInGroup[i] = charGroups[i].Length; + + // Use this array to track (iterate through) unused character groups. + var leftGroupsOrder = new int[charGroups.Length]; + + // Initially, all character groups are not used. + for (var i = 0; i < leftGroupsOrder.Length; i++) + leftGroupsOrder[i] = i; + + // Using our private random number generator + var random = RandomSeed(); + + // This array will hold short-url characters. + // Allocate appropriate memory for the short-url. + var shortUrl = new char[random.Next(length, length)]; + + // Index of the last non-processed group. + var lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1; + + // Generate short-url characters one at a time. + for (var i = 0; i < shortUrl.Length; i++) { - const string charsLower = "abcdefghijkmnopqrstuvwxyz"; - const string charsUpper = "ABCDFEGHJKLMNPQRSTUVWXYZ-"; - const string charsNumeric = "1234567890"; + // If only one character group remained unprocessed, process it; + // otherwise, pick a random character group from the unprocessed + // group list. To allow a special character to appear in the + // first position, increment the second parameter of the Next + // function call by one, i.e. lastLeftGroupsOrderIdx + 1. + int nextLeftGroupsOrderIdx; + if (lastLeftGroupsOrderIdx == 0) + nextLeftGroupsOrderIdx = 0; + else + nextLeftGroupsOrderIdx = random.Next(0, + lastLeftGroupsOrderIdx); - // Create a local array containing supported short-url characters - // grouped by types. - var charGroups = new[] + // Get the actual index of the character group, from which we will + // pick the next character. + var nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx]; + + // Get the index of the last unprocessed characters in this group. + var lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1; + + // If only one unprocessed character is left, pick it; otherwise, + // get a random character from the unused character list. + var nextCharIdx = lastCharIdx == 0 ? 0 : random.Next(0, lastCharIdx + 1); + + // Add this character to the short-url. + shortUrl[i] = charGroups[nextGroupIdx][nextCharIdx]; + + // If we processed the last character in this group, start over. + if (lastCharIdx == 0) { - charsLower.ToCharArray(), - charsUpper.ToCharArray(), - charsNumeric.ToCharArray() - }; - - // Use this array to track the number of unused characters in each - // character group. - var charsLeftInGroup = new int[charGroups.Length]; - - // Initially, all characters in each group are not used. - for (var i = 0; i < charsLeftInGroup.Length; i++) - charsLeftInGroup[i] = charGroups[i].Length; - - // Use this array to track (iterate through) unused character groups. - var leftGroupsOrder = new int[charGroups.Length]; - - // Initially, all character groups are not used. - for (var i = 0; i < leftGroupsOrder.Length; i++) - leftGroupsOrder[i] = i; - - // Using our private randomizer - var random = RandomSeed(); - - // This array will hold short-url characters. - // Allocate appropriate memory for the short-url. - var shortUrl = new char[random.Next(length, length)]; - - // Index of the last non-processed group. - var lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1; - - // Generate short-url characters one at a time. - for (var i = 0; i < shortUrl.Length; i++) + charsLeftInGroup[nextGroupIdx] = + charGroups[nextGroupIdx].Length; + } + // There are more unprocessed characters left. + else { - // If only one character group remained unprocessed, process it; - // otherwise, pick a random character group from the unprocessed - // group list. To allow a special character to appear in the - // first position, increment the second parameter of the Next - // function call by one, i.e. lastLeftGroupsOrderIdx + 1. - int nextLeftGroupsOrderIdx; - if (lastLeftGroupsOrderIdx == 0) - nextLeftGroupsOrderIdx = 0; - else - nextLeftGroupsOrderIdx = random.Next(0, - lastLeftGroupsOrderIdx); + // Swap processed character with the last unprocessed character + // so that we don't pick it until we process all characters in + // this group. + if (lastCharIdx != nextCharIdx) + (charGroups[nextGroupIdx][lastCharIdx], charGroups[nextGroupIdx][nextCharIdx]) = ( + charGroups[nextGroupIdx][nextCharIdx], charGroups[nextGroupIdx][lastCharIdx]); - // Get the actual index of the character group, from which we will - // pick the next character. - var nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx]; - - // Get the index of the last unprocessed characters in this group. - var lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1; - - // If only one unprocessed character is left, pick it; otherwise, - // get a random character from the unused character list. - var nextCharIdx = lastCharIdx == 0 ? 0 : random.Next(0, lastCharIdx + 1); - - // Add this character to the short-url. - shortUrl[i] = charGroups[nextGroupIdx][nextCharIdx]; - - // If we processed the last character in this group, start over. - if (lastCharIdx == 0) - { - charsLeftInGroup[nextGroupIdx] = - charGroups[nextGroupIdx].Length; - } - // There are more unprocessed characters left. - else - { - // Swap processed character with the last unprocessed character - // so that we don't pick it until we process all characters in - // this group. - if (lastCharIdx != nextCharIdx) - { - (charGroups[nextGroupIdx][lastCharIdx], charGroups[nextGroupIdx][nextCharIdx]) = (charGroups[nextGroupIdx][nextCharIdx], charGroups[nextGroupIdx][lastCharIdx]); - } - - // Decrement the number of unprocessed characters in - // this group. - charsLeftInGroup[nextGroupIdx]--; - } - - // If we processed the last group, start all over. - if (lastLeftGroupsOrderIdx == 0) - { - lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1; - } - // There are more unprocessed groups left. - else - { - // Swap processed group with the last unprocessed group - // so that we don't pick it until we process all groups. - if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx) - { - (leftGroupsOrder[lastLeftGroupsOrderIdx], leftGroupsOrder[nextLeftGroupsOrderIdx]) = (leftGroupsOrder[nextLeftGroupsOrderIdx], leftGroupsOrder[lastLeftGroupsOrderIdx]); - } - - // Decrement the number of unprocessed groups. - lastLeftGroupsOrderIdx--; - } + // Decrement the number of unprocessed characters in + // this group. + charsLeftInGroup[nextGroupIdx]--; } - // Convert password characters into a string and return the result. - return new string(shortUrl); - } - - /// - /// Username generator - /// - /// The options. - /// - /// - public static string GenerateUsername(StringOptions options = null) - { - options ??= new StringOptions + // If we processed the last group, start all over. + if (lastLeftGroupsOrderIdx == 0) { - RequiredLength = 10, - RequireDigit = true, - RequireLowercase = true, - RequireUppercase = true, - RequiredUniqueChars = 4, - RequireNonLetterOrDigit = false, - RequireNonAlphanumeric = false - }; - return GenerateRandomString(options); - } - - /// - /// Password generator - /// - /// The options. - /// - /// - public static string GeneratePassword(StringOptions options = null) - { - options ??= new StringOptions - { - RequiredLength = 10, - RequireDigit = true, - RequireLowercase = true, - RequireUppercase = true, - RequiredUniqueChars = 4, - RequireNonLetterOrDigit = true, - RequireNonAlphanumeric = true - }; - return GenerateRandomString(options); - } - - /// - /// Random string generator with length - /// - /// The length. - /// - public static string GenerateRandomText(int length) - { - const string consonants = "bcdfghjklmnprstvxzBDFGHJKLMNPRSTVXZ"; - const string vowels = "aeiouyAEIOUY"; - - var rndString = ""; - var randomNum = RandomSeed(); - - while (rndString.Length < length) - { - rndString += consonants[randomNum.Next(consonants.Length)]; - if (rndString.Length < length) - rndString += vowels[randomNum.Next(vowels.Length)]; + lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1; } - - return rndString; - } - - /// - /// Random string generator - string options - /// - /// The options. - /// - public static string GenerateRandomString(StringOptions options = null) - { - options ??= new StringOptions + // There are more unprocessed groups left. + else { - RequiredLength = 10, - RequireDigit = true, - RequireLowercase = true, - RequireUppercase = true, - RequiredUniqueChars = 4, - RequireNonLetterOrDigit = true, - RequireNonAlphanumeric = true - }; + // Swap processed group with the last unprocessed group + // so that we don't pick it until we process all groups. + if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx) + (leftGroupsOrder[lastLeftGroupsOrderIdx], leftGroupsOrder[nextLeftGroupsOrderIdx]) = ( + leftGroupsOrder[nextLeftGroupsOrderIdx], leftGroupsOrder[lastLeftGroupsOrderIdx]); - var randomChars = new[] - { - "ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase - "abcdefghijkmnopqrstuvwxyz", // lowercase - "0123456789", // digits - "!@$?_-" // non-alphanumeric - }; - - // Using our private randomizer - var rand = RandomSeed(); - - var chars = new List(); - - if (options.RequireUppercase) - chars.Insert(rand.Next(0, chars.Count), - randomChars[0][rand.Next(0, randomChars[0].Length)]); - - if (options.RequireLowercase) - chars.Insert(rand.Next(0, chars.Count), - randomChars[1][rand.Next(0, randomChars[1].Length)]); - - if (options.RequireDigit) - chars.Insert(rand.Next(0, chars.Count), - randomChars[2][rand.Next(0, randomChars[2].Length)]); - - if (options.RequireNonAlphanumeric) - chars.Insert(rand.Next(0, chars.Count), - randomChars[3][rand.Next(0, randomChars[3].Length)]); - - var rcs = randomChars[rand.Next(0, randomChars.Length)]; - for (var i = chars.Count; - i < options.RequiredLength - || chars.Distinct().Count() < options.RequiredUniqueChars; - i++) - chars.Insert(rand.Next(0, chars.Count), - rcs[rand.Next(0, rcs.Length)]); - - return new string(chars.ToArray()); - } - - /// - /// Randomize random using RNGCrypto - /// - /// - /// derived from https://sourceforge.net/projects/shorturl-dotnet/ - /// - public static Random RandomSeed() - { - // As the default Random is based on the current time - // so it produces the same "random" number within a second - // Use a crypto service to create the seed value - - // 4-byte array to fill with random bytes - var randomBytes = new byte[4]; - - // Generate 4 random bytes. - using (var rng = new RNGCryptoServiceProvider()) - { - rng.GetBytes(randomBytes); + // Decrement the number of unprocessed groups. + lastLeftGroupsOrderIdx--; } - - // Convert 4 bytes into a 32-bit integer value. - var seed = ((randomBytes[0] & 0x7f) << 24) | - (randomBytes[1] << 16) | - (randomBytes[2] << 8) | - randomBytes[3]; - - // Return a truly randomized random generator - return new Random(seed); } + + // Convert password characters into a string and return the result. + return new string(shortUrl); + } + + /// + /// Username generator + /// + /// The options. + /// + /// + public static string GenerateUsername(StringOptions options = null) + { + options ??= new StringOptions + { + RequiredLength = 16, + RequireDigit = true, + RequireLowercase = true, + RequireUppercase = true, + RequiredUniqueChars = 4, + RequireNonLetterOrDigit = false, + RequireNonAlphanumeric = false + }; + return GenerateRandomString(options); + } + + /// + /// Password generator + /// + /// The options. + /// + /// + public static string GeneratePassword(StringOptions options = null) + { + options ??= new StringOptions + { + RequiredLength = 16, + RequireDigit = true, + RequireLowercase = true, + RequireUppercase = true, + RequiredUniqueChars = 8, + RequireNonLetterOrDigit = false, + RequireNonAlphanumeric = false + }; + return GenerateRandomString(options); + } + + /// + /// Random string generator with length + /// + /// The length. + /// + public static string GenerateRandomText(int length) + { + const string consonants = "bcdfghjklmnprstvxzBDFGHJKLMNPRSTVXZ"; + const string vowels = "aeiouyAEIOUY"; + + var rndString = ""; + var randomNum = RandomSeed(); + + while (rndString.Length < length) + { + rndString += consonants[randomNum.Next(consonants.Length)]; + if (rndString.Length < length) + rndString += vowels[randomNum.Next(vowels.Length)]; + } + + return rndString; + } + + /// + /// Random string generator - string options + /// + /// The options. + /// + public static string GenerateRandomString(StringOptions options = null) + { + options ??= new StringOptions + { + RequiredLength = 16, + RequireDigit = true, + RequireLowercase = true, + RequireUppercase = true, + RequiredUniqueChars = 4, + RequireNonLetterOrDigit = true, + RequireNonAlphanumeric = true + }; + + var randomChars = new[] + { + "ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase + "abcdefghijkmnopqrstuvwxyz", // lowercase + "0123456789", // digits + "!@$?_-" // non-alphanumeric + }; + + // Using our private random number generator + var rand = RandomSeed(); + + var chars = new List(); + + if (options.RequireUppercase) + chars.Insert(rand.Next(0, chars.Count), + randomChars[0][rand.Next(0, randomChars[0].Length)]); + + if (options.RequireLowercase) + chars.Insert(rand.Next(0, chars.Count), + randomChars[1][rand.Next(0, randomChars[1].Length)]); + + if (options.RequireDigit) + chars.Insert(rand.Next(0, chars.Count), + randomChars[2][rand.Next(0, randomChars[2].Length)]); + + if (options.RequireNonAlphanumeric) + chars.Insert(rand.Next(0, chars.Count), + randomChars[3][rand.Next(0, randomChars[3].Length)]); + + var rcs = randomChars[rand.Next(0, randomChars.Length)]; + for (var i = chars.Count; + i < options.RequiredLength + || chars.Distinct().Count() < options.RequiredUniqueChars; + i++) + chars.Insert(rand.Next(0, chars.Count), + rcs[rand.Next(0, rcs.Length)]); + + return new string(chars.ToArray()); + } + + /// + /// Randomize random using RNGCrypto + /// + /// + /// derived from https://sourceforge.net/projects/shorturl-dotnet/ + /// + public static Random RandomSeed() + { + // As the default Random is based on the current time + // so it produces the same "random" number within a second + // Use a crypto service to create the seed value + + // 4-byte array to fill with random bytes + var randomBytes = new byte[4]; + + // Generate 4 random bytes. + using (var rng = new RNGCryptoServiceProvider()) + { + rng.GetBytes(randomBytes); + } + + // Convert 4 bytes into a 32-bit integer value. + var seed = ((randomBytes[0] & 0x7f) << 24) | + (randomBytes[1] << 16) | + (randomBytes[2] << 8) | + randomBytes[3]; + + // Return a truly randomized random generator + return new Random(seed); } } \ No newline at end of file diff --git a/GuidGenerator.cs b/GuidGenerator.cs index 6808e8f..cabc71d 100644 --- a/GuidGenerator.cs +++ b/GuidGenerator.cs @@ -1,251 +1,276 @@ -using System; +// *********************************************************************** +// Assembly : FCS.Lib.Utility +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 +// *********************************************************************** +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] +// +// +// *********************************************************************** + +using System; using System.Text; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Used for generating UUID based on RFC 4122. +/// +/// RFC 4122 - A Universally Unique IDentifier (UUID) URN Namespace +public static class GuidGenerator { /// - /// Used for generating UUID based on RFC 4122. + /// number of bytes in guid /// - /// RFC 4122 - A Universally Unique IDentifier (UUID) URN Namespace - public static class GuidGenerator + public const int ByteArraySize = 16; + + /// + /// multiplex variant info - variant byte + /// + public const int VariantByte = 8; + + /// + /// multiplex variant info - variant byte mask + /// + public const int VariantByteMask = 0x3f; + + /// + /// multiplex variant info - variant byte shift + /// + public const int VariantByteShift = 0x80; + + /// + /// multiplex version info - version byte + /// + public const int VersionByte = 7; + + /// + /// multiplex version info - version byte mask + /// + public const int VersionByteMask = 0x0f; + + /// + /// multiplex version info version byte shift + /// + public const int VersionByteShift = 4; + + // indexes within the uuid array for certain boundaries + private const byte TimestampByte = 0; + private const byte GuidClockSequenceByte = 8; + private const byte NodeByte = 10; + + // offset to move from 1/1/0001, which is 0-time for .NET, to gregorian 0-time of 10/15/1582 + private static readonly DateTimeOffset GregorianCalendarStart = new(1582, 10, 15, 0, 0, 0, TimeSpan.Zero); + + static GuidGenerator() { - - /// - /// number of bytes in guid - /// - public const int ByteArraySize = 16; + DefaultClockSequence = new byte[2]; + DefaultNode = new byte[6]; - /// - /// multiplex variant info - variant byte - /// - public const int VariantByte = 8; - - /// - /// multiplex variant info - variant byte mask - /// - public const int VariantByteMask = 0x3f; - - /// - /// multiplex variant info - variant byte shift - /// - public const int VariantByteShift = 0x80; - - /// - /// multiplex version info - version byte - /// - public const int VersionByte = 7; - - /// - /// multiplex version info - version byte mask - /// - public const int VersionByteMask = 0x0f; - - /// - /// multiplex version info version byte shift - /// - public const int VersionByteShift = 4; - - // indexes within the uuid array for certain boundaries - private const byte TimestampByte = 0; - private const byte GuidClockSequenceByte = 8; - private const byte NodeByte = 10; - - // offset to move from 1/1/0001, which is 0-time for .NET, to gregorian 0-time of 10/15/1582 - private static readonly DateTimeOffset GregorianCalendarStart = new(1582, 10, 15, 0, 0, 0, TimeSpan.Zero); - - - /// - /// Default clock sequence - /// - public static byte[] DefaultClockSequence { get; set; } - /// - /// Default node - /// - public static byte[] DefaultNode { get; set; } - - static GuidGenerator() - { - DefaultClockSequence = new byte[2]; - DefaultNode = new byte[6]; - - var random = new Random(); - random.NextBytes(DefaultClockSequence); - random.NextBytes(DefaultNode); - } - - /// - /// Set default node - /// - /// - public static void SetDefaultNode(string nodeName) - { - var x = nodeName.GetHashCode(); - var node = $"{x:X}"; - DefaultNode = Encoding.UTF8.GetBytes(node.ToCharArray(), 0, 6); - } - - /// - /// Get version - /// - /// - /// - public static GuidVersion GetVersion(this Guid guid) - { - var bytes = guid.ToByteArray(); - return (GuidVersion)((bytes[VersionByte] & 0xFF) >> VersionByteShift); - } - - /// - /// Get date time offset from guid - /// - /// - /// - public static DateTimeOffset GetDateTimeOffset(Guid guid) - { - var bytes = guid.ToByteArray(); - - // reverse the version - bytes[VersionByte] &= VersionByteMask; - bytes[VersionByte] |= (byte)GuidVersion.TimeBased >> VersionByteShift; - - var timestampBytes = new byte[8]; - Array.Copy(bytes, TimestampByte, timestampBytes, 0, 8); - - var timestamp = BitConverter.ToInt64(timestampBytes, 0); - var ticks = timestamp + GregorianCalendarStart.Ticks; - - return new DateTimeOffset(ticks, TimeSpan.Zero); - } - - /// - /// get date time from guid - /// - /// - /// - public static DateTime GetDateTime(Guid guid) - { - return GetDateTimeOffset(guid).DateTime; - } - - /// - /// get local date time from guid - /// - /// - /// - public static DateTime GetLocalDateTime(Guid guid) - { - return GetDateTimeOffset(guid).LocalDateTime; - } - - /// - /// get utc date time from guid - /// - /// - /// - public static DateTime GetUtcDateTime(Guid guid) - { - return GetDateTimeOffset(guid).UtcDateTime; - } - - /// - /// Generate time based guid - /// - /// - public static Guid GenerateTimeBasedGuid() - { - return GenerateTimeBasedGuid(DateTimeOffset.UtcNow, DefaultClockSequence, DefaultNode); - } - - /// - /// Generate time based guid providing a NodeName string - /// - /// - /// - public static Guid GenerateTimeBasedGuid(string nodeName) - { - var x = nodeName.GetHashCode(); - var node = $"{x:X}"; - var defaultNode = Encoding.UTF8.GetBytes(node.ToCharArray(), 0, 6); - return GenerateTimeBasedGuid(DateTimeOffset.UtcNow, DefaultClockSequence, defaultNode); - } - - /// - /// Generate time based guid providing a valid DateTime object - /// - /// - /// - public static Guid GenerateTimeBasedGuid(DateTime dateTime) - { - return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode); - } - - /// - /// Generate time base guid providing a valid DateTimeOffset object - /// - /// - /// - public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime) - { - return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode); - } - - /// - /// Generate time based guid providing a date time, byte array for clock sequence and node - /// - /// - /// - /// - /// - public static Guid GenerateTimeBasedGuid(DateTime dateTime, byte[] clockSequence, byte[] node) - { - return GenerateTimeBasedGuid(new DateTimeOffset(dateTime), clockSequence, node); - } - - /// - /// Generate time based guid providing a valid DateTimeOffset Object and byte arrays for clock sequence and node - /// - /// - /// - /// - /// - /// - /// - public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime, byte[] clockSequence, byte[] node) - { - if (clockSequence == null) - throw new ArgumentNullException(nameof(clockSequence)); - - if (node == null) - throw new ArgumentNullException(nameof(node)); - - if (clockSequence.Length != 2) - throw new ArgumentOutOfRangeException(nameof(clockSequence), "The clockSequence must be 2 bytes."); - - if (node.Length != 6) - throw new ArgumentOutOfRangeException(nameof(node), "The node must be 6 bytes."); - - var ticks = (dateTime - GregorianCalendarStart).Ticks; - var guid = new byte[ByteArraySize]; - var timestamp = BitConverter.GetBytes(ticks); - - // copy node - Array.Copy(node, 0, guid, NodeByte, Math.Min(6, node.Length)); - - // copy clock sequence - Array.Copy(clockSequence, 0, guid, GuidClockSequenceByte, Math.Min(2, clockSequence.Length)); - - // copy timestamp - Array.Copy(timestamp, 0, guid, TimestampByte, Math.Min(8, timestamp.Length)); - - // set the variant - guid[VariantByte] &= VariantByteMask; - guid[VariantByte] |= VariantByteShift; - - // set the version - guid[VersionByte] &= VersionByteMask; - guid[VersionByte] |= (byte)GuidVersion.TimeBased << VersionByteShift; - - return new Guid(guid); - } + var random = new Random(); + random.NextBytes(DefaultClockSequence); + random.NextBytes(DefaultNode); } -} + + + /// + /// Default clock sequence + /// + public static byte[] DefaultClockSequence { get; set; } + + /// + /// Default node + /// + public static byte[] DefaultNode { get; set; } + + /// + /// Set default node + /// + /// + public static void SetDefaultNode(string nodeName) + { + var x = nodeName.GetHashCode(); + var node = $"{x:X}"; + DefaultNode = Encoding.UTF8.GetBytes(node.ToCharArray(), 0, 6); + } + + /// + /// Get version + /// + /// + /// + public static GuidVersion GetVersion(this Guid guid) + { + var bytes = guid.ToByteArray(); + return (GuidVersion)((bytes[VersionByte] & 0xFF) >> VersionByteShift); + } + + /// + /// Get date time offset from guid + /// + /// + /// + public static DateTimeOffset GetDateTimeOffset(Guid guid) + { + var bytes = guid.ToByteArray(); + + // reverse the version + bytes[VersionByte] &= VersionByteMask; + bytes[VersionByte] |= (byte)GuidVersion.TimeBased >> VersionByteShift; + + var timestampBytes = new byte[8]; + Array.Copy(bytes, TimestampByte, timestampBytes, 0, 8); + + var timestamp = BitConverter.ToInt64(timestampBytes, 0); + var ticks = timestamp + GregorianCalendarStart.Ticks; + + return new DateTimeOffset(ticks, TimeSpan.Zero); + } + + /// + /// get date time from guid + /// + /// + /// + public static DateTime GetDateTime(Guid guid) + { + return GetDateTimeOffset(guid).DateTime; + } + + /// + /// get local date time from guid + /// + /// + /// + public static DateTime GetLocalDateTime(Guid guid) + { + return GetDateTimeOffset(guid).LocalDateTime; + } + + /// + /// get utc date time from guid + /// + /// + /// + public static DateTime GetUtcDateTime(Guid guid) + { + return GetDateTimeOffset(guid).UtcDateTime; + } + + /// + /// Generate time based guid + /// + /// + public static Guid GenerateTimeBasedGuid() + { + return GenerateTimeBasedGuid(DateTimeOffset.UtcNow, DefaultClockSequence, DefaultNode); + } + + /// + /// Generate time based guid providing a NodeName string + /// + /// + /// + public static Guid GenerateTimeBasedGuid(string nodeName) + { + var x = nodeName.GetHashCode(); + var node = $"{x:X}"; + var defaultNode = Encoding.UTF8.GetBytes(node.ToCharArray(), 0, 6); + return GenerateTimeBasedGuid(DateTimeOffset.UtcNow, DefaultClockSequence, defaultNode); + } + + /// + /// Generate time based guid providing a valid DateTime object + /// + /// + /// + public static Guid GenerateTimeBasedGuid(DateTime dateTime) + { + return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode); + } + + /// + /// Generate time base guid providing a valid DateTimeOffset object + /// + /// + /// + public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime) + { + return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode); + } + + /// + /// Generate time based guid providing a date time, byte array for clock sequence and node + /// + /// + /// + /// + /// + public static Guid GenerateTimeBasedGuid(DateTime dateTime, byte[] clockSequence, byte[] node) + { + return GenerateTimeBasedGuid(new DateTimeOffset(dateTime), clockSequence, node); + } + + /// + /// Generate time based guid providing a valid DateTimeOffset Object and byte arrays for clock sequence and node + /// + /// + /// + /// + /// + /// + /// + public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime, byte[] clockSequence, byte[] node) + { + if (clockSequence == null) + throw new ArgumentNullException(nameof(clockSequence)); + + if (node == null) + throw new ArgumentNullException(nameof(node)); + + if (clockSequence.Length != 2) + throw new ArgumentOutOfRangeException(nameof(clockSequence), "The clockSequence must be 2 bytes."); + + if (node.Length != 6) + throw new ArgumentOutOfRangeException(nameof(node), "The node must be 6 bytes."); + + var ticks = (dateTime - GregorianCalendarStart).Ticks; + var guid = new byte[ByteArraySize]; + var timestamp = BitConverter.GetBytes(ticks); + + // copy node + Array.Copy(node, 0, guid, NodeByte, Math.Min(6, node.Length)); + + // copy clock sequence + Array.Copy(clockSequence, 0, guid, GuidClockSequenceByte, Math.Min(2, clockSequence.Length)); + + // copy timestamp + Array.Copy(timestamp, 0, guid, TimestampByte, Math.Min(8, timestamp.Length)); + + // set the variant + guid[VariantByte] &= VariantByteMask; + guid[VariantByte] |= VariantByteShift; + + // set the version + guid[VersionByte] &= VersionByteMask; + guid[VersionByte] |= (byte)GuidVersion.TimeBased << VersionByteShift; + + return new Guid(guid); + } +} \ No newline at end of file diff --git a/GuidVersion.cs b/GuidVersion.cs index f9212ab..2ea52a6 100644 --- a/GuidVersion.cs +++ b/GuidVersion.cs @@ -1,25 +1,53 @@ -namespace FCS.Lib.Utility +// *********************************************************************** +// Assembly : FCS.Lib.Utility +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 +// *********************************************************************** +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] +// +// +// *********************************************************************** + +namespace FCS.Lib.Utility; + +/// +/// Guid Version Enum +/// +public enum GuidVersion { /// - /// Guid Version Enum + /// Time /// - public enum GuidVersion - { - /// - /// Time - /// - TimeBased = 0x01, - /// - /// Reserved - /// - Reserved = 0x02, - /// - /// Name - /// - NameBased = 0x03, - /// - /// Random - /// - Random = 0x04 - } + TimeBased = 0x01, + + /// + /// Reserved + /// + Reserved = 0x02, + + /// + /// Name + /// + NameBased = 0x03, + + /// + /// Random + /// + Random = 0x04 } \ No newline at end of file diff --git a/IAsyncReadonlyRepo.cs b/IAsyncReadonlyRepo.cs index ad927e2..f681970 100644 --- a/IAsyncReadonlyRepo.cs +++ b/IAsyncReadonlyRepo.cs @@ -1,25 +1,25 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 03-10-2015 -// -// Last Modified By : FH -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2023 01 23 07:31 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2023-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** @@ -30,67 +30,66 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Interface IRepositoryAsync +/// +/// The type of the t entity. +public interface IAsyncReadonlyRepo where TEntity : class { /// - /// Interface IRepositoryAsync + /// Queryable /// - /// The type of the t entity. - public interface IAsyncReadonlyRepo where TEntity : class - { - /// - /// Queryable - /// - /// IQueryable<TEntity>. - IQueryable All(); + /// IQueryable<TEntity>. + IQueryable All(); - /// - /// All items asynchronous. - /// - /// The predicate. - /// Task<IList<TEntity>>. - Task> AllAsync(Expression> predicate); + /// + /// All items asynchronous. + /// + /// The predicate. + /// Task<IList<TEntity>>. + Task> AllAsync(Expression> predicate); - /// - /// Any item asynchronous. - /// - /// The predicate. - /// Task<System.Boolean>. - Task AnyAsync(Expression> predicate); + /// + /// Any item asynchronous. + /// + /// The predicate. + /// Task<System.Boolean>. + Task AnyAsync(Expression> predicate); - /// - /// Finds the asynchronous. - /// - /// The predicate. - /// Task<TEntity>. - Task FindAsync(Expression> predicate); + /// + /// Finds the asynchronous. + /// + /// The predicate. + /// Task<TEntity>. + Task FindAsync(Expression> predicate); - /// - /// Firsts the asynchronous. - /// - /// The predicate. - /// Task<TEntity>. - Task FirstAsync(Expression> predicate); + /// + /// Firsts the asynchronous. + /// + /// The predicate. + /// Task<TEntity>. + Task FirstAsync(Expression> predicate); - /// - /// Firsts the or default asynchronous. - /// - /// The predicate. - /// Task<TEntity>. - Task FirstOrDefaultAsync(Expression> predicate); + /// + /// Firsts the or default asynchronous. + /// + /// The predicate. + /// Task<TEntity>. + Task FirstOrDefaultAsync(Expression> predicate); - /// - /// Anies the specified predicate. - /// - /// The predicate. - /// true if XXXX, false otherwise. - bool Any(Expression> predicate); + /// + /// Anies the specified predicate. + /// + /// The predicate. + /// true if XXXX, false otherwise. + bool Any(Expression> predicate); - /// - /// Gets the by identifier. - /// - /// The identifier. - /// TEntity. - TEntity GetById(string id); - } + /// + /// Gets the by identifier. + /// + /// The identifier. + /// TEntity. + TEntity GetById(string id); } \ No newline at end of file diff --git a/IRepository.cs b/IRepository.cs index 74e892e..021c2a7 100644 --- a/IRepository.cs +++ b/IRepository.cs @@ -1,61 +1,60 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 05-13-2020 -// -// Last Modified By : FH -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Interface IRepository +/// +/// +/// The type of the TKey. +public interface IRepository where T : class { /// - /// Interface IRepository + /// Gets the specified identifier. /// - /// - /// The type of the TKey. - public interface IRepository where T : class - { - /// - /// Gets the specified identifier. - /// - /// The identifier. - /// T. - T GetById(TKey id); + /// The identifier. + /// T. + T GetById(TKey id); - /// - /// Creates the specified entity. - /// - /// The entity. - void Create(T entity); + /// + /// Creates the specified entity. + /// + /// The entity. + void Create(T entity); - /// - /// Updates the specified entity. - /// - /// The entity. - void Update(T entity); + /// + /// Updates the specified entity. + /// + /// The entity. + void Update(T entity); - /// - /// Deletes the specified identifier. - /// - /// The identifier. - void Delete(TKey id); - } + /// + /// Deletes the specified identifier. + /// + /// The identifier. + void Delete(TKey id); } \ No newline at end of file diff --git a/IRepositoryEx.cs b/IRepositoryEx.cs index 20fc021..c712475 100644 --- a/IRepositoryEx.cs +++ b/IRepositoryEx.cs @@ -1,25 +1,25 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 03-10-2015 -// -// Last Modified By : FH -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** @@ -29,99 +29,98 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Interface IRepositoryEx +/// +/// The type of the t entity +public interface IRepositoryEx where TEntity : class { /// - /// Interface IRepositoryEx + /// Get all entities synchronous /// - /// The type of the t entity - public interface IRepositoryEx where TEntity : class - { - /// - /// Get all entities synchronous - /// - /// Predicate - /// Task<System.Boolean> - Task AnyAsync(Expression> predicate); + /// Predicate + /// Task<System.Boolean> + Task AnyAsync(Expression> predicate); - /// - /// Find matching entity asynchronous - /// - /// Predicate - /// Task<TEntity> - Task FindAsync(Expression> predicate); + /// + /// Find matching entity asynchronous + /// + /// Predicate + /// Task<TEntity> + Task FindAsync(Expression> predicate); - /// - /// Find first matching entity asynchronous - /// - /// Predicate - /// Task<TEntity> - Task FirstAsync(Expression> predicate); + /// + /// Find first matching entity asynchronous + /// + /// Predicate + /// Task<TEntity> + Task FirstAsync(Expression> predicate); - /// - /// Get first entity matching query or default entity asynchronous - /// - /// Predicate - /// Task<TEntity> - Task FirstOrDefaultAsync(Expression> predicate); + /// + /// Get first entity matching query or default entity asynchronous + /// + /// Predicate + /// Task<TEntity> + Task FirstOrDefaultAsync(Expression> predicate); - /// - /// Add an entity - /// - /// The entity. - void Add(TEntity entity); + /// + /// Add an entity + /// + /// The entity. + void Add(TEntity entity); - /// - /// Attach the entity - /// - /// The entity. - void Attach(TEntity entity); + /// + /// Attach the entity + /// + /// The entity. + void Attach(TEntity entity); - /// - /// Delete the entity - /// - /// The entity. - void Delete(TEntity entity); + /// + /// Delete the entity + /// + /// The entity. + void Delete(TEntity entity); - /// - /// Anies the specified predicate. - /// - /// The predicate. - /// true if XXXX, false otherwise. - bool Any(Expression> predicate); + /// + /// Anies the specified predicate. + /// + /// The predicate. + /// true if XXXX, false otherwise. + bool Any(Expression> predicate); - /// - /// Get entity by id - /// - /// The identifier. - /// TEntity - TEntity GetById(string id); + /// + /// Get entity by id + /// + /// The identifier. + /// TEntity + TEntity GetById(string id); - /// - /// Find first entity matching query - /// - /// Predicate - /// TEntity - TEntity First(Expression> predicate); + /// + /// Find first entity matching query + /// + /// Predicate + /// TEntity + TEntity First(Expression> predicate); - /// - /// Find first matching entity or default entity - /// - /// Predicate - /// TEntity - TEntity FirstOrDefault(Expression> predicate); + /// + /// Find first matching entity or default entity + /// + /// Predicate + /// TEntity + TEntity FirstOrDefault(Expression> predicate); - /// - /// Find all matching entities matching query - /// - /// Predicate - /// IQueryable<TEntity> - IQueryable Find(Expression> predicate); + /// + /// Find all matching entities matching query + /// + /// Predicate + /// IQueryable<TEntity> + IQueryable Find(Expression> predicate); - /// - /// Get all entities - /// - /// IQueryable<TEntity> - IQueryable All(); - } + /// + /// Get all entities + /// + /// IQueryable<TEntity> + IQueryable All(); } \ No newline at end of file diff --git a/Mogrify.cs b/Mogrify.cs index b53b95c..75568e8 100644 --- a/Mogrify.cs +++ b/Mogrify.cs @@ -1,25 +1,25 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 27-08-2016 -// -// Last Modified By : Frede H. -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2023 03 02 09:52 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2023-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** @@ -33,446 +33,462 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Mogrify between units +/// +public static class Mogrify { /// - /// Mogrify between units + /// Remove everything but digits and country code /// - public static class Mogrify + /// + /// + public static string SanitizePhone(string phone) { - /// - /// Get month from timestamp - /// - /// - /// integer - public static int MonthFromTimestamp(long timeStamp) - { - return TimeStampToDateTime(timeStamp).Month; - } - - /// - /// validate if timestamp occurs in month - /// - /// - /// - /// boolean - public static bool TimestampInMonth(long timestamp, int month) - { - return TimeStampToDateTime(timestamp).Month == month; - } - - /// - /// return iso8601 string from timestamp - /// - /// - /// - public static string TimestampToIso8601(long timestamp) - { - return DateTimeIso8601(TimeStampToDateTime(timestamp)); - } - /// - /// return date as ISO - /// - /// - /// - public static string DateTimeIso8601(DateTime date) - { - return date.ToString("o",CultureInfo.InvariantCulture); - } - - /// - /// Get timestamp range for given datetime - /// - /// - /// dictionary - public static Dictionary DateToTimestampRange(DateTime dateTime) - { - var dt1 = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day,0,0,0); - var dt2 = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59); - return new Dictionary{ - { "lower", DateTimeToTimeStamp(dt1) }, - { "upper", DateTimeToTimeStamp(dt2) } - }; - } - - /// - /// ISO date to timestamp - /// - /// - /// long - public static long IsoDateToTimestamp(string isoDateString) - { - var result = DateTime.TryParse(isoDateString, out var test); - if (!result) - return 0; - return $"{test:yyyy-MM-dd}" == isoDateString ? DateTimeToTimeStamp(test) : 0; - } - - /// - /// ISO date from timestamp - /// - /// - /// string yyyy-MM-dd - public static string TimestampToIsoDate(long timestamp) - { - return $"{TimeStampToDateTime(timestamp):yyyy-MM-dd}"; - } - - /// - /// get timestamp from current date time - /// - /// - public static long CurrentDateTimeToTimeStamp() - { - return Convert.ToUInt32(DateTimeToTimeStamp(DateTime.Now)); - } - - /// - /// get timestamp from date time - /// - /// - /// - public static long DateTimeToTimeStamp(DateTime dateTime) - { - var bigDate = new DateTime(2038, 1, 19, 0, 0, 0, 0); - var nixDate = new DateTime(1970, 1, 1, 0, 0, 0, 0); - - if (dateTime >= bigDate) - return Convert.ToInt64((bigDate - nixDate).TotalSeconds) + - Convert.ToInt64((dateTime - bigDate).TotalSeconds); - - return Convert.ToInt64((dateTime - nixDate).TotalSeconds); - } - - /// - /// get date time from timestamp - /// - /// - /// - public static DateTime TimeStampToDateTime(long timeStamp) - { - var nixDate = new DateTime(1970, 1, 1, 0, 0, 0, 0); - return nixDate.AddSeconds(timeStamp); - } - - /// - /// get seconds from timespan - /// - /// - /// - public static long TimeSpanToSeconds(TimeSpan timespan) - { - return Convert.ToUInt32(timespan.Ticks / 10000000L); - } - - /// - /// get timespan from seconds - /// - /// - /// - public static TimeSpan SecondsToTimeSpan(long seconds) - { - return TimeSpan.FromTicks(10000000L * seconds); - } - - /// - /// get minutes from timespan - /// - /// - /// - public static long TimespanToMinutes(TimeSpan timespan) - { - return Convert.ToUInt32(timespan.Ticks / 10000000L) / 60; - } - - /// - /// reverse boolean - /// - /// - /// bool - public static bool BoolReverse(bool value) - { - return !value; - } - - /// - /// number from bool - /// - /// - /// integer - public static int BoolToInt(bool value) - { - return value ? 1 : 0; - } - - /// - /// string from bool - /// - /// - /// string true/false - public static string BoolToString(bool value) - { - return value ? "true" : "false"; - } - - /// - /// get bool from integer - /// - /// - /// - public static bool IntToBool(int value) - { - return value is > 0 or < 0; - } - - /// - /// get the number value from enum - /// - /// - /// int - public static int EnumToInt(object enumeration) - { - return Convert.ToInt32(enumeration, CultureInfo.InvariantCulture); - } - - /// - /// get string from enum - /// - /// - /// string - name of the enum - public static string EnumToString(Enum value) - { - return value == null ? string.Empty : value.ToString(); - } - - /// - /// get list of enum of type T - /// - /// - /// list of enum - public static IEnumerable GetEnumList() - { - return (T[])Enum.GetValues(typeof(T)); - } - - - /// - /// get enum from integer of type T - /// - /// - /// - /// - public static T IntToEnum(int value) - { - return (T) Enum.ToObject(typeof(T), value); - } - - /// - /// get string from list using semicolon separator - /// - /// - /// - /// - public static string ListToString(List list) - { - return ListToString(list, ";"); - } - - /// - /// get string from list using delimiter - /// - /// - /// - /// - /// - public static string ListToString(List list, string delimiter) - { - var empty = string.Empty; - if (list == null) return empty; - var enumerator = (IEnumerator) list.GetType().GetMethod("GetEnumerator")?.Invoke(list, null); - while (enumerator != null && enumerator.MoveNext()) - if (enumerator.Current != null) - empty = string.Concat(empty, enumerator.Current.ToString(), delimiter); - - return empty; - } - - /// - /// get lowercase dash separated string from Pascal case - /// - /// - /// - public static string PascalToLower(string value) - { - var result = string.Join("-", Regex.Split(value, @"(? - /// get bool from string - /// - /// - /// - public static bool StringToBool(string value) - { - if (string.IsNullOrEmpty(value)) - return false; - - var flag = false; - var upper = value.ToUpperInvariant(); - if (string.Compare(upper, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - flag = true; - } - else if (string.CompareOrdinal(upper, "false") == 0) - { - } - else if (string.CompareOrdinal(upper, "1") == 0) - { - flag = true; - } - - return flag; - } - /// - /// get decimal from string - /// - /// - /// - public static decimal? StringToDecimal(string inString) - { - if (string.IsNullOrEmpty(inString)) return 0; - return - !decimal.TryParse(inString.Replace(",", "").Replace(".", ""), NumberStyles.Number, - CultureInfo.InvariantCulture, out var num) - ? (decimal?) null - : decimal.Divide(num, new decimal((long) 100)); - } - - /// - /// get enum of type T from string - /// - /// - /// - /// - public static T StringToEnum(string value) - { - return (T)Enum.Parse(typeof(T), value, true); - } - - /// - /// get list from string using semicolon - /// - /// - /// - /// - public static List StringToList(string value) - { - return StringToList(value, ";"); - } - - /// - /// get list from string using delimiter - /// - /// - /// - /// - /// - /// - public static List StringToList(string value, string delimiter) - { - if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value)); - if (string.IsNullOrEmpty(delimiter)) throw new ArgumentNullException(nameof(delimiter)); - - var ts = new List(); - var strArrays = value.Split(delimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - foreach (var str in strArrays) - { - var o = typeof(T).FullName; - if (o == null) continue; - var upperInvariant = o.ToUpperInvariant(); - if (string.CompareOrdinal(upperInvariant, "system.string") == 0) - { - ts.Add((T) Convert.ChangeType(str, typeof(T), CultureInfo.InvariantCulture)); - } - else if (string.CompareOrdinal(upperInvariant, "system.int32") == 0) - { - ts.Add((T) Convert.ChangeType(str, typeof(T), CultureInfo.InvariantCulture)); - } - else if (string.CompareOrdinal(upperInvariant, "system.guid") == 0) - { - var guid = new Guid(str); - ts.Add((T) Convert.ChangeType(guid, typeof(T), CultureInfo.InvariantCulture)); - } - } - - return ts; - } - - /// - /// get string from stream (default encoding) - /// - /// - /// - public static Stream StringToStream(string value) - { - return StringToStream(value, Encoding.Default); - } - - /// - /// get stream from string (using encoding) - /// - /// - /// - /// - public static Stream StringToStream(string value, Encoding encoding) - { - return encoding == null ? null : new MemoryStream(encoding.GetBytes(value ?? "")); - } - - - ///// - ///// get string from date time - ///// - ///// - //public static string CurrentDateTimeToAlpha() - //{ - // var dt = DateTime.UtcNow.ToString("yy MM dd HH MM ss"); - // var sb = new StringBuilder(); - // var dts = dt.Split(' '); - // sb.Append((char) int.Parse(dts[0]) + 65); - // sb.Append((char) int.Parse(dts[1]) + 65); - // sb.Append((char) int.Parse(dts[2]) + 97); - // sb.Append((char) int.Parse(dts[3]) + 65); - // sb.Append((char) int.Parse(dts[4]) + 97); - // sb.Append((char) int.Parse(dts[5]) + 97); - // return sb.ToString(); - //} - - ///// - ///// integer to letter - ///// - ///// - ///// string - //public static string IntToLetter(int value) - //{ - // var empty = string.Empty; - // var num = 97; - // var str = ""; - // var num1 = 0; - // var num2 = 97; - // for (var i = 0; i <= value; i++) - // { - // num1++; - // empty = string.Concat(str, Convert.ToString(Convert.ToChar(num), CultureInfo.InvariantCulture)); - // num++; - // if (num1 != 26) continue; - // num1 = 0; - // str = Convert.ToChar(num2).ToString(CultureInfo.InvariantCulture); - // num2++; - // num = 97; - // } - // return empty; - //} + if (string.IsNullOrWhiteSpace(phone)) + return ""; + phone = phone.Replace("+45", "").Replace("+46", "").Replace("+47", ""); + var regexObj = new Regex(@"[^\d]"); + return regexObj.Replace(phone, ""); } + + /// + /// Get month from timestamp + /// + /// + /// integer + public static int MonthFromTimestamp(long timeStamp) + { + return TimeStampToDateTime(timeStamp).Month; + } + + /// + /// validate if timestamp occurs in month + /// + /// + /// + /// boolean + public static bool TimestampInMonth(long timestamp, int month) + { + return TimeStampToDateTime(timestamp).Month == month; + } + + /// + /// return iso8601 string from timestamp + /// + /// + /// + public static string TimestampToIso8601(long timestamp) + { + return DateTimeIso8601(TimeStampToDateTime(timestamp)); + } + + /// + /// return date as ISO + /// + /// + /// + public static string DateTimeIso8601(DateTime date) + { + return date.ToString("o", CultureInfo.InvariantCulture); + } + + /// + /// Get timestamp range for given datetime + /// + /// + /// dictionary + public static Dictionary DateToTimestampRange(DateTime dateTime) + { + var dt1 = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0); + var dt2 = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59); + return new Dictionary + { + { "lower", DateTimeToTimeStamp(dt1) }, + { "upper", DateTimeToTimeStamp(dt2) } + }; + } + + /// + /// ISO date to timestamp + /// + /// + /// long + public static long IsoDateToTimestamp(string isoDateString) + { + var result = DateTime.TryParse(isoDateString, out var test); + if (!result) + return 0; + return $"{test:yyyy-MM-dd}" == isoDateString ? DateTimeToTimeStamp(test) : 0; + } + + /// + /// ISO date from timestamp + /// + /// + /// string yyyy-MM-dd + public static string TimestampToIsoDate(long timestamp) + { + return $"{TimeStampToDateTime(timestamp):yyyy-MM-dd}"; + } + + /// + /// get timestamp from current date time + /// + /// + public static long CurrentDateTimeToTimeStamp() + { + return Convert.ToUInt32(DateTimeToTimeStamp(DateTime.Now)); + } + + /// + /// get timestamp from date time + /// + /// + /// + public static long DateTimeToTimeStamp(DateTime dateTime) + { + var bigDate = new DateTime(2038, 1, 19, 0, 0, 0, 0); + var nixDate = new DateTime(1970, 1, 1, 0, 0, 0, 0); + + if (dateTime >= bigDate) + return Convert.ToInt64((bigDate - nixDate).TotalSeconds) + + Convert.ToInt64((dateTime - bigDate).TotalSeconds); + + return Convert.ToInt64((dateTime - nixDate).TotalSeconds); + } + + /// + /// get date time from timestamp + /// + /// + /// + public static DateTime TimeStampToDateTime(long timeStamp) + { + var nixDate = new DateTime(1970, 1, 1, 0, 0, 0, 0); + return nixDate.AddSeconds(timeStamp); + } + + /// + /// get seconds from timespan + /// + /// + /// + public static long TimeSpanToSeconds(TimeSpan timespan) + { + return Convert.ToUInt32(timespan.Ticks / 10000000L); + } + + /// + /// get timespan from seconds + /// + /// + /// + public static TimeSpan SecondsToTimeSpan(long seconds) + { + return TimeSpan.FromTicks(10000000L * seconds); + } + + /// + /// get minutes from timespan + /// + /// + /// + public static long TimespanToMinutes(TimeSpan timespan) + { + return Convert.ToUInt32(timespan.Ticks / 10000000L) / 60; + } + + /// + /// reverse boolean + /// + /// + /// bool + public static bool BoolReverse(bool value) + { + return !value; + } + + /// + /// number from bool + /// + /// + /// integer + public static int BoolToInt(bool value) + { + return value ? 1 : 0; + } + + /// + /// string from bool + /// + /// + /// string true/false + public static string BoolToString(bool value) + { + return value ? "true" : "false"; + } + + /// + /// get bool from integer + /// + /// + /// + public static bool IntToBool(int value) + { + return value is > 0 or < 0; + } + + /// + /// get the number value from enum + /// + /// + /// int + public static int EnumToInt(object enumeration) + { + return Convert.ToInt32(enumeration, CultureInfo.InvariantCulture); + } + + /// + /// get string from enum + /// + /// + /// string - name of the enum + public static string EnumToString(Enum value) + { + return value == null ? string.Empty : value.ToString(); + } + + /// + /// get list of enum of type T + /// + /// + /// list of enum + public static IEnumerable GetEnumList() + { + return (T[])Enum.GetValues(typeof(T)); + } + + + /// + /// get enum from integer of type T + /// + /// + /// + /// + public static T IntToEnum(int value) + { + return (T)Enum.ToObject(typeof(T), value); + } + + /// + /// get string from list using semicolon separator + /// + /// + /// + /// + public static string ListToString(List list) + { + return ListToString(list, ";"); + } + + /// + /// get string from list using delimiter + /// + /// + /// + /// + /// + public static string ListToString(List list, string delimiter) + { + var empty = string.Empty; + if (list == null) return empty; + var enumerator = (IEnumerator)list.GetType().GetMethod("GetEnumerator")?.Invoke(list, null); + while (enumerator != null && enumerator.MoveNext()) + if (enumerator.Current != null) + empty = string.Concat(empty, enumerator.Current.ToString(), delimiter); + + return empty; + } + + /// + /// get lowercase dash separated string from Pascal case + /// + /// + /// + public static string PascalToLower(string value) + { + var result = string.Join("-", Regex.Split(value, @"(? + /// get bool from string + /// + /// + /// + public static bool StringToBool(string value) + { + if (string.IsNullOrEmpty(value)) + return false; + + var flag = false; + var upper = value.ToUpperInvariant(); + if (string.Compare(upper, "true", StringComparison.OrdinalIgnoreCase) == 0) + { + flag = true; + } + else if (string.CompareOrdinal(upper, "false") == 0) + { + } + else if (string.CompareOrdinal(upper, "1") == 0) + { + flag = true; + } + + return flag; + } + + /// + /// get decimal from string + /// + /// + /// + public static decimal? StringToDecimal(string inString) + { + if (string.IsNullOrEmpty(inString)) return 0; + return + !decimal.TryParse(inString.Replace(",", "").Replace(".", ""), NumberStyles.Number, + CultureInfo.InvariantCulture, out var num) + ? null + : decimal.Divide(num, new decimal((long)100)); + } + + /// + /// get enum of type T from string + /// + /// + /// + /// + public static T StringToEnum(string value) + { + return (T)Enum.Parse(typeof(T), value, true); + } + + /// + /// get list from string using semicolon + /// + /// + /// + /// + public static List StringToList(string value) + { + return StringToList(value, ";"); + } + + /// + /// get list from string using delimiter + /// + /// + /// + /// + /// + /// + public static List StringToList(string value, string delimiter) + { + if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value)); + if (string.IsNullOrEmpty(delimiter)) throw new ArgumentNullException(nameof(delimiter)); + + var ts = new List(); + var strArrays = value.Split(delimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); + foreach (var str in strArrays) + { + var o = typeof(T).FullName; + if (o == null) continue; + var upperInvariant = o.ToUpperInvariant(); + if (string.CompareOrdinal(upperInvariant, "system.string") == 0) + { + ts.Add((T)Convert.ChangeType(str, typeof(T), CultureInfo.InvariantCulture)); + } + else if (string.CompareOrdinal(upperInvariant, "system.int32") == 0) + { + ts.Add((T)Convert.ChangeType(str, typeof(T), CultureInfo.InvariantCulture)); + } + else if (string.CompareOrdinal(upperInvariant, "system.guid") == 0) + { + var guid = new Guid(str); + ts.Add((T)Convert.ChangeType(guid, typeof(T), CultureInfo.InvariantCulture)); + } + } + + return ts; + } + + /// + /// get string from stream (default encoding) + /// + /// + /// + public static Stream StringToStream(string value) + { + return StringToStream(value, Encoding.Default); + } + + /// + /// get stream from string (using encoding) + /// + /// + /// + /// + public static Stream StringToStream(string value, Encoding encoding) + { + return encoding == null ? null : new MemoryStream(encoding.GetBytes(value ?? "")); + } + + + ///// + ///// get string from date time + ///// + ///// + //public static string CurrentDateTimeToAlpha() + //{ + // var dt = DateTime.UtcNow.ToString("yy MM dd HH MM ss"); + // var sb = new StringBuilder(); + // var dts = dt.Split(' '); + // sb.Append((char) int.Parse(dts[0]) + 65); + // sb.Append((char) int.Parse(dts[1]) + 65); + // sb.Append((char) int.Parse(dts[2]) + 97); + // sb.Append((char) int.Parse(dts[3]) + 65); + // sb.Append((char) int.Parse(dts[4]) + 97); + // sb.Append((char) int.Parse(dts[5]) + 97); + // return sb.ToString(); + //} + + ///// + ///// integer to letter + ///// + ///// + ///// string + //public static string IntToLetter(int value) + //{ + // var empty = string.Empty; + // var num = 97; + // var str = ""; + // var num1 = 0; + // var num2 = 97; + // for (var i = 0; i <= value; i++) + // { + // num1++; + // empty = string.Concat(str, Convert.ToString(Convert.ToChar(num), CultureInfo.InvariantCulture)); + // num++; + // if (num1 != 26) continue; + // num1 = 0; + // str = Convert.ToChar(num2).ToString(CultureInfo.InvariantCulture); + // num2++; + // num = 97; + // } + // return empty; + //} } \ No newline at end of file diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index a7d03cd..7323968 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -17,5 +17,5 @@ using System.Runtime.InteropServices; [assembly: ComVisible(false)] [assembly: Guid("8D850197-78DB-4D16-A91F-E5BB6E8880A7")] -[assembly: AssemblyVersion("1.0.23023.0820")] -[assembly: AssemblyFileVersion("1.0.23023.0820")] \ No newline at end of file +[assembly: AssemblyVersion("1.0.23077.1334")] +[assembly: AssemblyFileVersion("1.0.23077.1334")] \ No newline at end of file diff --git a/QueryHelper.cs b/QueryHelper.cs index eb522fd..79a0f03 100644 --- a/QueryHelper.cs +++ b/QueryHelper.cs @@ -1,25 +1,25 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 01-01-2022 -// -// Last Modified By : FH -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** @@ -29,70 +29,69 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Class QueryHelper. +/// +public static class QueryHelper { + // https://stackoverflow.com/a/45761590 + /// - /// Class QueryHelper. + /// OrderBy /// - public static class QueryHelper + /// + /// + /// + /// + /// + public static IQueryable OrderBy(this IQueryable q, string name, bool desc) { - // https://stackoverflow.com/a/45761590 + var entityType = typeof(TModel); + var p = entityType.GetProperty(name); + var m = typeof(QueryHelper) + .GetMethod("OrderByProperty") + ?.MakeGenericMethod(entityType, p.PropertyType); - /// - /// OrderBy - /// - /// - /// - /// - /// - /// - public static IQueryable OrderBy (this IQueryable q, string name, bool desc) - { - var entityType = typeof(TModel); - var p = entityType.GetProperty(name); - var m = typeof(QueryHelper) - .GetMethod("OrderByProperty") - ?.MakeGenericMethod(entityType, p.PropertyType); + return (IQueryable)m.Invoke(null, new object[] { q, p, desc }); + } - return(IQueryable) m.Invoke(null, new object[] { q, p , desc }); - } + /// + /// ThenBy + /// + /// + /// + /// + /// + /// + public static IQueryable ThenBy(this IQueryable q, string name, bool desc) + { + var entityType = typeof(TModel); + var p = entityType.GetProperty(name); + var m = typeof(QueryHelper) + .GetMethod("OrderByProperty") + ?.MakeGenericMethod(entityType, p.PropertyType); - /// - /// ThenBy - /// - /// - /// - /// - /// - /// - public static IQueryable ThenBy (this IQueryable q, string name, bool desc) - { - var entityType = typeof(TModel); - var p = entityType.GetProperty(name); - var m = typeof(QueryHelper) - .GetMethod("OrderByProperty") - ?.MakeGenericMethod(entityType, p.PropertyType); - - return(IQueryable) m.Invoke(null, new object[] { q, p , desc }); - } + return (IQueryable)m.Invoke(null, new object[] { q, p, desc }); + } - /// - /// OrderByProperty - /// - /// - /// - /// - /// - /// - /// - public static IQueryable OrderByProperty(IQueryable q, PropertyInfo p, bool desc) - { - var pe = Expression.Parameter(typeof(TModel)); - Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object)); - var exp = Expression.Lambda>(se, pe); - - return desc ? q.OrderByDescending(exp) : q.OrderBy(exp); - } + /// + /// OrderByProperty + /// + /// + /// + /// + /// + /// + /// + public static IQueryable OrderByProperty(IQueryable q, PropertyInfo p, bool desc) + { + var pe = Expression.Parameter(typeof(TModel)); + Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object)); + var exp = Expression.Lambda>(se, pe); - }} \ No newline at end of file + return desc ? q.OrderByDescending(exp) : q.OrderBy(exp); + } +} \ No newline at end of file diff --git a/Squid.cs b/Squid.cs index 5ac1b69..1a46c3e 100644 --- a/Squid.cs +++ b/Squid.cs @@ -1,395 +1,394 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 2020-07-01 -// -// Last Modified By : FH -// Last Modified On : 02-24-2022 +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the Affero GNU General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// Affero GNU General Public License for more details. -// -// You should have received a copy of the Affero GNU General Public License -// along with this program. If not, see [https://www.gnu.org/licenses/agpl-3.0.en.html] +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // -// Derived from https:github.com/csharpvitamins/CSharpVitamins.ShortGuid +// // *********************************************************************** using System; using System.Diagnostics; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// A wrapper for handling URL-safe Base64 encoded globally unique identifiers (GUID). +/// +/// Special characters are replaced (/, +) or removed (==). +/// Derived from https:github.com/csharpvitamins/CSharpVitamins.ShortGuid +[DebuggerDisplay("{" + nameof(Value) + "}")] +public readonly struct Squid : IEquatable { /// - /// A wrapper for handling URL-safe Base64 encoded globally unique identifiers (GUID). + /// A read-only object of the Squid struct. + /// Value is guaranteed to be all zeroes. + /// Equivalent to . /// - /// Special characters are replaced (/, +) or removed (==). - /// Derived from https:github.com/csharpvitamins/CSharpVitamins.ShortGuid - [DebuggerDisplay("{" + nameof(Value) + "}")] - public readonly struct Squid : IEquatable + public static readonly Squid Empty = new(Guid.Empty); + + /// + /// Creates a new Squid from a Squid encoded string. + /// + /// A valid Squid encodd string. + public Squid(string value) { - /// - /// A read-only object of the Squid struct. - /// Value is guaranteed to be all zeroes. - /// Equivalent to . - /// - public static readonly Squid Empty = new(Guid.Empty); + Value = value; + Guid = DecodeSquid(value); + } - /// - /// Creates a new Squid from a Squid encoded string. - /// - /// A valid Squid encodd string. - public Squid(string value) - { - Value = value; - Guid = DecodeSquid(value); - } + /// + /// Creates a new Squid with the given . + /// + /// A valid System.Guid object. + public Squid(Guid obj) + { + Value = EncodeGuid(obj); + Guid = obj; + } - /// - /// Creates a new Squid with the given . - /// - /// A valid System.Guid object. - public Squid(Guid obj) - { - Value = EncodeGuid(obj); - Guid = obj; - } - - /// - /// Gets the underlying for the encoded Squid. - /// - /// The unique identifier. + /// + /// Gets the underlying for the encoded Squid. + /// + /// The unique identifier. #pragma warning disable CA1720 // Identifier contains type name - public Guid Guid { get; } + public Guid Guid { get; } #pragma warning restore CA1720 // Identifier contains type name - /// - /// The encoded string value of the - /// as an URL-safe Base64 string. - /// - /// The value. - public string Value { get; } + /// + /// The encoded string value of the + /// as an URL-safe Base64 string. + /// + /// The value. + public string Value { get; } - /// - /// Returns the encoded URL-safe Base64 string. - /// - /// A that represents this instance. - public override string ToString() + /// + /// Returns the encoded URL-safe Base64 string. + /// + /// A that represents this instance. + public override string ToString() + { + return Value; + } + + /// + /// Returns a value indicating whether this object and a specified object represent the same type and value. + /// Compares for equality against other string, Guid and Squid types. + /// + /// A Systerm.String, System.Guid or Squid object + /// true if the specified is equal to this instance; otherwise, false. + public override bool Equals(object obj) + { + return obj is Squid other && Equals(other); + } + + /// + /// Equality comparison + /// + /// A valid Squid object + /// A boolean indicating equality. + public bool Equals(Squid obj) + { + return Guid.Equals(obj.Guid) && Value == obj.Value; + } + + /// + /// Returns the hash code for the underlying . + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + public override int GetHashCode() + { + unchecked { - return Value; + return (Guid.GetHashCode() * 397) ^ (Value != null ? Value.GetHashCode() : 0); } + } - /// - /// Returns a value indicating whether this object and a specified object represent the same type and value. - /// Compares for equality against other string, Guid and Squid types. - /// - /// A Systerm.String, System.Guid or Squid object - /// true if the specified is equal to this instance; otherwise, false. - public override bool Equals(object obj) + /// + /// Initialises a new object of the Squid using . + /// + /// New Squid object + public static Squid NewGuid() + { + return new Squid(Guid.NewGuid()); + } + + /// + /// Encode string as a new Squid encoded string. + /// The encoding is similar to Base64 with + /// non-URL safe characters replaced, and padding removed. + /// + /// A valid .Tostring(). + /// A 22 character URL-safe Base64 string. + public static string EncodeString(string value) + { + var guid = new Guid(value); + return EncodeGuid(guid); + } + + /// + /// Encode a object to Squid. + /// The encoding is similar to Base64 with + /// non-URL safe characters replaced, and padding removed. + /// + /// A valid object. + /// A 22 character URL-safe Base64 string. + public static string EncodeGuid(Guid obj) + { + var encoded = Convert.ToBase64String(obj.ToByteArray()); + encoded = encoded + .Replace("/", "_") + .Replace("+", "-"); + return encoded.Substring(0, 22); + } + + /// + /// Decode Squid string to a . + /// See also or + /// . + /// + /// A valid Squid encoded string. + /// A new object from the parsed string. + public static Guid DecodeSquid(string value) + { + if (value == null) return Empty; + value = value + .Replace("_", "/") + .Replace("-", "+"); + + var blob = Convert.FromBase64String(value + "=="); + return new Guid(blob); + } + + /// + /// Squid to Guid. + /// + /// A valid Squid object. + /// System.Guid object. + public static Guid FromSquid(Squid obj) + { + return obj.Guid; + } + + /// + /// String to Squid. + /// + /// String value to convert + /// A Squid object. + public static Squid FromString(string value) + { + if (string.IsNullOrEmpty(value)) + return Empty; + return TryParse(value, out Squid obj) ? obj : Empty; + } + + /// + /// Decodes the given value to a . + /// + /// The Squid encoded string to decode. + /// A new object from the parsed string. + /// A boolean indicating if the decode was successful. + public static bool TryDecode(string value, out Guid obj) + { + try { - return obj is Squid other && Equals(other); + // Decode as Squid + obj = DecodeSquid(value); + return true; } - - /// - /// Equality comparison - /// - /// A valid Squid object - /// A boolean indicating equality. - public bool Equals(Squid obj) - { - return Guid.Equals(obj.Guid) && Value == obj.Value; - } - - /// - /// Returns the hash code for the underlying . - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - public override int GetHashCode() - { - unchecked - { - return (Guid.GetHashCode() * 397) ^ (Value != null ? Value.GetHashCode() : 0); - } - } - - /// - /// Initialises a new object of the Squid using . - /// - /// New Squid object - public static Squid NewGuid() - { - return new(Guid.NewGuid()); - } - - /// - /// Encode string as a new Squid encoded string. - /// The encoding is similar to Base64 with - /// non-URL safe characters replaced, and padding removed. - /// - /// A valid .Tostring(). - /// A 22 character URL-safe Base64 string. - public static string EncodeString(string value) - { - var guid = new Guid(value); - return EncodeGuid(guid); - } - - /// - /// Encode a object to Squid. - /// The encoding is similar to Base64 with - /// non-URL safe characters replaced, and padding removed. - /// - /// A valid object. - /// A 22 character URL-safe Base64 string. - public static string EncodeGuid(Guid obj) - { - var encoded = Convert.ToBase64String(obj.ToByteArray()); - encoded = encoded - .Replace("/", "_") - .Replace("+", "-"); - return encoded.Substring(0, 22); - } - - /// - /// Decode Squid string to a . - /// See also or - /// . - /// - /// A valid Squid encoded string. - /// A new object from the parsed string. - public static Guid DecodeSquid(string value) - { - if (value == null) return Empty; - value = value - .Replace("_", "/") - .Replace("-", "+"); - - var blob = Convert.FromBase64String(value + "=="); - return new Guid(blob); - } - - /// - /// Squid to Guid. - /// - /// A valid Squid object. - /// System.Guid object. - public static Guid FromSquid(Squid obj) - { - return obj.Guid; - } - - /// - /// String to Squid. - /// - /// String value to convert - /// A Squid object. - public static Squid FromString(string value) - { - if (string.IsNullOrEmpty(value)) - return Empty; - return TryParse(value, out Squid obj) ? obj : Empty; - } - - /// - /// Decodes the given value to a . - /// - /// The Squid encoded string to decode. - /// A new object from the parsed string. - /// A boolean indicating if the decode was successful. - public static bool TryDecode(string value, out Guid obj) - { - try - { - // Decode as Squid - obj = DecodeSquid(value); - return true; - } #pragma warning disable CA1031 // Do not catch general exception types - catch (Exception) + catch (Exception) #pragma warning restore CA1031 // Do not catch general exception types - { - // Return empty Guid - obj = Guid.Empty; - return false; - } - } - - /// - /// Tries to parse the given string value and - /// outputs the object. - /// - /// The Squid encoded string or string representation of a Guid. - /// A new object from the parsed string. - /// A boolean indicating if the parse was successful. - public static bool TryParse(string value, out Squid obj) { - // Parse as Squid string. - if (TryDecode(value, out var oGuid)) - { - obj = oGuid; - return true; - } - - // Parse as Guid string. - if (Guid.TryParse(value, out oGuid)) - { - obj = oGuid; - return true; - } - - obj = Empty; - return false; - } - - /// - /// Tries to parse the string value and - /// outputs the underlying object. - /// - /// The Squid encoded string or string representation of a Guid. - /// A new object from the parsed string. - /// A boolean indicating if the parse was successful. - public static bool TryParse(string value, out Guid obj) - { - // Try a Squid string. - if (TryDecode(value, out obj)) - return true; - - // Try a Guid string. - if (Guid.TryParse(value, out obj)) - return true; - + // Return empty Guid obj = Guid.Empty; return false; } - - #region Operators - - /// - /// Determines if both Squid objects have the same - /// underlying value. - /// - /// The x. - /// The y. - /// The result of the operator. - public static bool operator ==(Squid x, Squid y) - { - return x.Guid == y.Guid; - } - - /// - /// Determines if both objects have the same - /// underlying value. - /// - /// The x. - /// The y. - /// The result of the operator. - public static bool operator ==(Squid x, Guid y) - { - return x.Guid == y; - } - - /// - /// Determines if both objects have the same - /// underlying value. - /// - /// The x. - /// The y. - /// The result of the operator. - public static bool operator ==(Guid x, Squid y) - { - return y == x; // NB: order of arguments - } - - /// - /// Determines if both Squid objects do not have the same - /// underlying value. - /// - /// The x. - /// The y. - /// The result of the operator. - public static bool operator !=(Squid x, Squid y) - { - return !(x == y); - } - - /// - /// Determines if both objects do not have the same - /// underlying value. - /// - /// The x. - /// The y. - /// The result of the operator. - public static bool operator !=(Squid x, Guid y) - { - return !(x == y); - } - - /// - /// Determines if both objects do not have the same - /// underlying value. - /// - /// The x. - /// The y. - /// The result of the operator. - public static bool operator !=(Guid x, Squid y) - { - return !(x == y); - } - - /// - /// Implicitly converts the Squid to - /// its string equivalent. - /// - /// The o squid. - /// The result of the conversion. - public static implicit operator string(Squid oSquid) - { - return oSquid.Value; - } - - /// - /// Implicitly converts the Squid to - /// its equivalent. - /// - /// The o squid. - /// The result of the conversion. - public static implicit operator Guid(Squid oSquid) - { - return oSquid.Guid; - } - - /// - /// Implicitly converts the string to a Squid. - /// - /// The value. - /// The result of the conversion. - public static implicit operator Squid(string value) - { - if (string.IsNullOrEmpty(value)) - return Empty; - - return TryParse(value, out Squid oSquid) ? oSquid : Empty; - } - - /// - /// Implicitly converts the to a Squid. - /// - /// The o unique identifier. - /// The result of the conversion. - public static implicit operator Squid(Guid oGuid) - { - return oGuid == Guid.Empty ? Empty : new Squid(oGuid); - } - - #endregion } + + /// + /// Tries to parse the given string value and + /// outputs the object. + /// + /// The Squid encoded string or string representation of a Guid. + /// A new object from the parsed string. + /// A boolean indicating if the parse was successful. + public static bool TryParse(string value, out Squid obj) + { + // Parse as Squid string. + if (TryDecode(value, out var oGuid)) + { + obj = oGuid; + return true; + } + + // Parse as Guid string. + if (Guid.TryParse(value, out oGuid)) + { + obj = oGuid; + return true; + } + + obj = Empty; + return false; + } + + /// + /// Tries to parse the string value and + /// outputs the underlying object. + /// + /// The Squid encoded string or string representation of a Guid. + /// A new object from the parsed string. + /// A boolean indicating if the parse was successful. + public static bool TryParse(string value, out Guid obj) + { + // Try a Squid string. + if (TryDecode(value, out obj)) + return true; + + // Try a Guid string. + if (Guid.TryParse(value, out obj)) + return true; + + obj = Guid.Empty; + return false; + } + + #region Operators + + /// + /// Determines if both Squid objects have the same + /// underlying value. + /// + /// The x. + /// The y. + /// The result of the operator. + public static bool operator ==(Squid x, Squid y) + { + return x.Guid == y.Guid; + } + + /// + /// Determines if both objects have the same + /// underlying value. + /// + /// The x. + /// The y. + /// The result of the operator. + public static bool operator ==(Squid x, Guid y) + { + return x.Guid == y; + } + + /// + /// Determines if both objects have the same + /// underlying value. + /// + /// The x. + /// The y. + /// The result of the operator. + public static bool operator ==(Guid x, Squid y) + { + return y == x; // NB: order of arguments + } + + /// + /// Determines if both Squid objects do not have the same + /// underlying value. + /// + /// The x. + /// The y. + /// The result of the operator. + public static bool operator !=(Squid x, Squid y) + { + return !(x == y); + } + + /// + /// Determines if both objects do not have the same + /// underlying value. + /// + /// The x. + /// The y. + /// The result of the operator. + public static bool operator !=(Squid x, Guid y) + { + return !(x == y); + } + + /// + /// Determines if both objects do not have the same + /// underlying value. + /// + /// The x. + /// The y. + /// The result of the operator. + public static bool operator !=(Guid x, Squid y) + { + return !(x == y); + } + + /// + /// Implicitly converts the Squid to + /// its string equivalent. + /// + /// The o squid. + /// The result of the conversion. + public static implicit operator string(Squid oSquid) + { + return oSquid.Value; + } + + /// + /// Implicitly converts the Squid to + /// its equivalent. + /// + /// The o squid. + /// The result of the conversion. + public static implicit operator Guid(Squid oSquid) + { + return oSquid.Guid; + } + + /// + /// Implicitly converts the string to a Squid. + /// + /// The value. + /// The result of the conversion. + public static implicit operator Squid(string value) + { + if (string.IsNullOrEmpty(value)) + return Empty; + + return TryParse(value, out Squid oSquid) ? oSquid : Empty; + } + + /// + /// Implicitly converts the to a Squid. + /// + /// The o unique identifier. + /// The result of the conversion. + public static implicit operator Squid(Guid oGuid) + { + return oGuid == Guid.Empty ? Empty : new Squid(oGuid); + } + + #endregion } \ No newline at end of file diff --git a/StringOptions.cs b/StringOptions.cs index d53c6dd..afdbaf4 100644 --- a/StringOptions.cs +++ b/StringOptions.cs @@ -1,76 +1,75 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 2020-09-09 -// -// Last Modified By : FH -// Last Modified On : 03-14-2022 +// Author : fhdk +// Created : 2022 12 17 13:33 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see [https://www.gnu.org/licenses] +// +// Copyright (C) 2022-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Class StringOptions. +/// +public class StringOptions { /// - /// Class StringOptions. + /// Gets or sets the required length of a string /// - public class StringOptions - { - /// - /// Gets or sets the required length of a string - /// - /// The length of the required. - public int RequiredLength { get; set; } + /// The length of the required. + public int RequiredLength { get; set; } - /// - /// Gets or sets a value indicating whether to [require non letter or digit]. - /// - /// true if [require non letter or digit]; otherwise, false. - public bool RequireNonLetterOrDigit { get; set; } + /// + /// Gets or sets a value indicating whether to [require non letter or digit]. + /// + /// true if [require non letter or digit]; otherwise, false. + public bool RequireNonLetterOrDigit { get; set; } - /// - /// Gets or sets a value indicating whether to [require digit]. - /// - /// true if [require digit]; otherwise, false. - public bool RequireDigit { get; set; } + /// + /// Gets or sets a value indicating whether to [require digit]. + /// + /// true if [require digit]; otherwise, false. + public bool RequireDigit { get; set; } - /// - /// Gets or sets a value indicating whether to [require lowercase]. - /// - /// true if [require lowercase]; otherwise, false. - public bool RequireLowercase { get; set; } + /// + /// Gets or sets a value indicating whether to [require lowercase]. + /// + /// true if [require lowercase]; otherwise, false. + public bool RequireLowercase { get; set; } - /// - /// Gets or sets a value indicating whether to [require uppercase]. - /// - /// true if [require uppercase]; otherwise, false. - public bool RequireUppercase { get; set; } + /// + /// Gets or sets a value indicating whether to [require uppercase]. + /// + /// true if [require uppercase]; otherwise, false. + public bool RequireUppercase { get; set; } - /// - /// Gets or sets the required unique chars. - /// - /// The required unique chars. - public int RequiredUniqueChars { get; set; } + /// + /// Gets or sets the required unique chars. + /// + /// The required unique chars. + public int RequiredUniqueChars { get; set; } - /// - /// Gets or sets a value indicating whether to [require non alphanumeric]. - /// - /// true if [require non alphanumeric]; otherwise, false. - public bool RequireNonAlphanumeric { get; set; } - } + /// + /// Gets or sets a value indicating whether to [require non alphanumeric]. + /// + /// true if [require non alphanumeric]; otherwise, false. + public bool RequireNonAlphanumeric { get; set; } } \ No newline at end of file diff --git a/VatFormatValidator.cs b/VatFormatValidator.cs index 748a0b6..6d79288 100644 --- a/VatFormatValidator.cs +++ b/VatFormatValidator.cs @@ -1,362 +1,358 @@ // *********************************************************************** // Assembly : FCS.Lib.Utility -// Author : FH -// Created : 03-30-2022 -// -// Last Modified By : FH -// Last Modified On : 04-19-2022 +// Author : fhdk +// Created : 2023 03 09 17:42 +// +// Last Modified By: fhdk +// Last Modified On : 2023 03 14 09:16 // *********************************************************************** -// -// Copyright (C) 2022 FCS Frede's Computer Services. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see [https://www.gnu.org/licenses] +// +// Copyright (C) 2023-2023 FCS Frede's Computer Services. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see [https://www.gnu.org/licenses] // // // *********************************************************************** -using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -namespace FCS.Lib.Utility +namespace FCS.Lib.Utility; + +/// +/// Vat format validator +/// +public static class VatFormatValidator { + // https://ec.europa.eu/taxation_customs/vies/faqvies.do#item_11 + // https://ec.europa.eu/taxation_customs/vies/ + + + //https://www.bolagsverket.se/apierochoppnadata.2531.html + /// - /// Vat format validator + /// Check vat number format /// - public static class VatFormatValidator + /// + /// + /// bool indicating if the vat number conform to country specification + public static bool CheckVat(string countryCode, string vatNumber) { - // https://ec.europa.eu/taxation_customs/vies/faqvies.do#item_11 - // https://ec.europa.eu/taxation_customs/vies/ + if (string.IsNullOrWhiteSpace(vatNumber)) + return false; + var sanitizedVat = SanitizeVatNumber(vatNumber); - //https://www.bolagsverket.se/apierochoppnadata.2531.html - - /// - /// Check vat number format - /// - /// - /// - /// bool indicating if the vat number conform to country specification - public static bool CheckVat(string countryCode, string vatNumber) + return countryCode.ToUpperInvariant() switch { - if (string.IsNullOrWhiteSpace(vatNumber)) - return false; + "DK" => ValidateDkVat(sanitizedVat), + "NO" => ValidateNoOrg(sanitizedVat), + "SE" => ValidateSeOrg(sanitizedVat), + _ => false + }; + } - var sanitizedVat = SanitizeVatNumber(vatNumber); + /// + /// sanitize vat number + /// + /// + /// sanitized string + public static string SanitizeVatNumber(string vatNumber) + { + if (string.IsNullOrWhiteSpace(vatNumber)) + return ""; + // remove anything but digits + var regexObj = new Regex(@"[^\d]"); + return regexObj.Replace(vatNumber, ""); + } - return countryCode.ToUpperInvariant() switch - { - "DK" => ValidateDkVat(sanitizedVat), - "NO" => ValidateNoOrg(sanitizedVat), - "SE" => ValidateSeOrg(sanitizedVat), - _ => false - }; - } + private static bool ValidateDkVat(string vatNumber) + { + // https://wiki.scn.sap.com/wiki/display/CRM/Denmark + // 8 digits 0 to 9 + // C1..C7 + // C8 check-digit MOD11 + // C1 > 0 + // R = (2*C1 + 7*C2 + 6*C3 + 5*C4 + 4*C5 + 3*C6 + 2*C7 + C8) + if (vatNumber.Length == 8 && long.TryParse(vatNumber, out _)) + return ValidateMod11(vatNumber); + return false; + } - /// - /// sanitize vat number - /// - /// - /// sanitized string - public static string SanitizeVatNumber(string vatNumber) + private static bool ValidateNoOrg(string vatNumber) + { + // https://wiki.scn.sap.com/wiki/display/CRM/Norway + // 12 digits + // C1..C8 random 0 to 9 + // C9 check-digit MOD11 + // C10 C11 C12 chars == MVA + try { - if (string.IsNullOrWhiteSpace(vatNumber)) - return ""; - // remove anything but digits - var regexObj = new Regex(@"[^\d]"); - return regexObj.Replace(vatNumber, ""); - } - - private static bool ValidateDkVat(string vatNumber) - { - // https://wiki.scn.sap.com/wiki/display/CRM/Denmark - // 8 digits 0 to 9 - // C1..C7 - // C8 check-digit MOD11 - // C1 > 0 - // R = (2*C1 + 7*C2 + 6*C3 + 5*C4 + 4*C5 + 3*C6 + 2*C7 + C8) - if(vatNumber.Length == 8 && long.TryParse(vatNumber, out _)) - return ValidateMod11(vatNumber); + if (vatNumber.Length == 9 && long.TryParse(vatNumber, out _)) + return ValidateMod11(vatNumber); return false; } - - private static bool ValidateNoOrg(string vatNumber) + catch { - // https://wiki.scn.sap.com/wiki/display/CRM/Norway - // 12 digits - // C1..C8 random 0 to 9 - // C9 check-digit MOD11 - // C10 C11 C12 chars == MVA - try - { - if (vatNumber.Length == 9 && long.TryParse(vatNumber, out _)) - return ValidateMod11(vatNumber); - return false; - } - catch - { - return false; - } + return false; } - - private static bool ValidateSeOrg(string orgNumber) - { - // https://wiki.scn.sap.com/wiki/display/CRM/Sweden - // 12 digits 0 to 9 - // C10 = (10 – (18 + 5 + 1 + 8 + 4)MOD10 10) MOD10 - // R = S1 + S3 + S5 + S7 + S9 - // Si = int(Ci/5) + (Ci*2)MOD10) - // https://www.skatteverket.se/skatter/mervardesskattmoms/momsregistreringsnummer.4.18e1b10334ebe8bc80002649.html - // EU MOMS => C11 C12 == 01 (De två sista siffrorna är alltid 01) - // C11 C12 is not used inside Sweden - // C1 is type of org and C2 to C9 is org number - // C10 is check digit - - var orgToCheck = orgNumber; - if (long.Parse(orgToCheck) == 0) - return false; - - switch (orgToCheck.Length) - { - // personal vat se - case 6: - return ValidateFormatSeExt(orgToCheck); - - case < 10: - return false; - - // strip EU extension `01` - case 12: - orgNumber = orgNumber.Substring(0, 10); - break; - } - - var c10 = C10(orgToCheck); - - // compare calculated org number with incoming org number - return $"{orgToCheck.Substring(0, 9)}{c10}" == orgNumber; - } - - private static int C10(string vatToCheck) - { - // check digit calculation - var r = new[] { 0, 2, 4, 6, 8 } - .Sum(m => (int)char.GetNumericValue(vatToCheck[m]) / 5 + - (int)char.GetNumericValue(vatToCheck[m]) * 2 % 10); - var c1 = new[] { 1, 3, 5, 7 }.Sum(m => (int)char.GetNumericValue(vatToCheck[m])); - var c10 = (10 - (r + c1) % 10) % 10; - return c10; - } - - private static bool ValidateFormatSeExt(string ssn) - { - // Swedish personally held companies uses SSN number - // a relaxed validation is required as only first 6 digits is supplied - // birthday format e.g. 991231 - - if (ssn.Length is not 6 or 10 || int.Parse(ssn) == 0) - return false; - - var y = int.Parse(ssn.Substring(0,2)); - var m = int.Parse(ssn.Substring(2,2)); - var d = int.Parse(ssn.Substring(4,2)); - // this calculation is only valid within 21st century - var leap = y % 4 == 0; // 2000 was a leap year; - // day - if(d is < 1 or > 31) - return false; - // month - switch (m) - { - // feb - case 2: - { - if (leap) - return d <= 29; - return d <= 28; - } - // apr, jun, sep, nov - case 4 or 6 or 9 or 11: - return d <= 30; - // jan, mar, may, july, aug, oct, dec - case 1 or 3 or 5 or 7 or 8 or 10 or 12: - return true; - // does not exist - default: - return false; - } - } - - private static bool ValidateMod11(string number) - { - try - { - if (long.Parse(number) == 0) - return false; - var sum = 0; - for (int i = number.Length - 1, multiplier = 1; i >= 0; i--) - { - // Console.WriteLine($"char: {number[i]} multiplier: {multiplier}"); - sum += (int)char.GetNumericValue(number[i]) * multiplier; - if (++multiplier > 7) multiplier = 2; - } - - return sum % 11 == 0; - } - catch - { - return false; - } - - } - - - ///// - ///// - ///// - ///// - ///// - //public static string FakeVatSsnSe(string ssn) - //{ - // var fake = ssn.PadRight(9, '8'); - // var c10 = SeGenerateCheckDigit(fake); - // return $"{fake}{c10}"; - //} - - ///// - ///// - ///// - ///// - ///// - //public static bool OrgIsPrivate(string org) - //{ - // var orgType = new List() { }; - - // return ValidateFormatSeExt(org.Substring(0, 5)); - //} - - ///// - ///// - ///// - ///// - ///// - //public static bool CheckLuhn(string vatNumber) - //{ - // // https://www.geeksforgeeks.org/luhn-algorithm/ - - // var nDigits = vatNumber.Length; - // var nSum = 0; - // var isSecond = false; - // for (var i = nDigits - 1; i >= 0; i--) - // { - // var d = (int)char.GetNumericValue(vatNumber[i]) - '0'; - // if (isSecond) - // d *= 2; - // // We add two digits to handle - // // cases that make two digits - // // after doubling - // nSum += d / 10; - // nSum += d % 10; - - // isSecond = !isSecond; - // } - - // return nSum % 10 == 0; - //} - - - //private static bool ValidateMod10(string number) - //{ - // if (long.Parse(number) == 0) - // return false; - - // var nDigits = number.Length; - // var nSum = 0; - // var isSecond = false; - // for (var i = nDigits - 1; i >= 0; i--) - // { - // var d = (int)char.GetNumericValue(number[i]) - '0'; - // if (isSecond) - // d *= 2; - // nSum += d / 10; - // nSum += d % 10; - // isSecond = !isSecond; - // } - // return nSum % 10 == 0; - //} - - //private static string GetMod10CheckDigit(string number) - //{ - // var sum = 0; - // var alt = true; - // var digits = number.ToCharArray(); - // for (var i = digits.Length - 1; i >= 0; i--) - // { - // var curDigit = digits[i] - 48; - // if (alt) - // { - // curDigit *= 2; - // if (curDigit > 9) - // curDigit -= 9; - // } - - // sum += curDigit; - // alt = !alt; - // } - // return sum % 10 == 0 ? "0" : (10 - sum % 10).ToString(); - //} - - //private string AddMod11CheckDigit(string number) - //{ - // return number + GetMod11CheckDigit(number); - //} - - //private static string GetMod11CheckDigit(string number) - //{ - // var sum = 0; - // for (int i = number.Length - 1, multiplier = 2; i >= 0; i--) - // { - // sum += (int)char.GetNumericValue(number[i]) * multiplier; - // if (++multiplier > 7) multiplier = 2; - // } - - // var modulo = sum % 11; - // return modulo is 0 or 1 ? "0" : (11 - modulo).ToString(); - //} - - //private static bool CheckLuhn(string vatNumber) - //{ - // // https://www.geeksforgeeks.org/luhn-algorithm/ - - // var nDigits = vatNumber.Length; - // var nSum = 0; - // var isSecond = false; - // for (var i = nDigits - 1; i >= 0; i--) - // { - // var d = (int)char.GetNumericValue(vatNumber[i]) - '0'; - // if (isSecond) - // d *= 2; - // // We add two digits to handle - // // cases that make two digits - // // after doubling - // nSum += d / 10; - // nSum += d % 10; - - // isSecond = !isSecond; - // } - - // return nSum % 10 == 0; - //} - } + + private static bool ValidateSeOrg(string orgNumber) + { + // https://wiki.scn.sap.com/wiki/display/CRM/Sweden + // 12 digits 0 to 9 + // C10 = (10 – (18 + 5 + 1 + 8 + 4)MOD10 10) MOD10 + // R = S1 + S3 + S5 + S7 + S9 + // Si = int(Ci/5) + (Ci*2)MOD10) + // https://www.skatteverket.se/skatter/mervardesskattmoms/momsregistreringsnummer.4.18e1b10334ebe8bc80002649.html + // EU MOMS => C11 C12 == 01 (De två sista siffrorna är alltid 01) + // C11 C12 is not used inside Sweden + // C1 is type of org and C2 to C9 is org number + // C10 is check digit + + var orgToCheck = orgNumber; + if (!long.TryParse(orgToCheck, out _)) + return false; + + switch (orgToCheck.Length) + { + // personal vat se + case 6: + return ValidateFormatSeExt(orgToCheck); + + case < 10: + return false; + + // strip EU extension `01` + case 12: + orgNumber = orgNumber.Substring(0, 10); + break; + } + + var c10 = C10(orgToCheck); + + // compare calculated org number with incoming org number + return $"{orgToCheck.Substring(0, 9)}{c10}" == orgNumber; + } + + private static int C10(string vatToCheck) + { + // check digit calculation + var r = new[] { 0, 2, 4, 6, 8 } + .Sum(m => (int)char.GetNumericValue(vatToCheck[m]) / 5 + + (int)char.GetNumericValue(vatToCheck[m]) * 2 % 10); + var c1 = new[] { 1, 3, 5, 7 }.Sum(m => (int)char.GetNumericValue(vatToCheck[m])); + var c10 = (10 - (r + c1) % 10) % 10; + return c10; + } + + private static bool ValidateFormatSeExt(string ssn) + { + // Swedish personally held companies uses SSN number + // a relaxed validation is required as only first 6 digits is supplied + // birthday format e.g. 991231 + + if (ssn.Length is not 6 or 10 || int.Parse(ssn) == 0) + return false; + + var y = int.Parse(ssn.Substring(0, 2)); + var m = int.Parse(ssn.Substring(2, 2)); + var d = int.Parse(ssn.Substring(4, 2)); + // this calculation is only valid within 21st century + var leap = y % 4 == 0; // 2000 was a leap year; + // day + if (d is < 1 or > 31) + return false; + // month + switch (m) + { + // feb + case 2: + { + if (leap) + return d <= 29; + return d <= 28; + } + // apr, jun, sep, nov + case 4 or 6 or 9 or 11: + return d <= 30; + // jan, mar, may, july, aug, oct, dec + case 1 or 3 or 5 or 7 or 8 or 10 or 12: + return true; + // does not exist + default: + return false; + } + } + + private static bool ValidateMod11(string number) + { + try + { + if (long.Parse(number) == 0) + return false; + var sum = 0; + for (int i = number.Length - 1, multiplier = 1; i >= 0; i--) + { + // Console.WriteLine($"char: {number[i]} multiplier: {multiplier}"); + sum += (int)char.GetNumericValue(number[i]) * multiplier; + if (++multiplier > 7) multiplier = 2; + } + + return sum % 11 == 0; + } + catch + { + return false; + } + } + + + ///// + ///// + ///// + ///// + ///// + //public static string FakeVatSsnSe(string ssn) + //{ + // var fake = ssn.PadRight(9, '8'); + // var c10 = SeGenerateCheckDigit(fake); + // return $"{fake}{c10}"; + //} + + ///// + ///// + ///// + ///// + ///// + //public static bool OrgIsPrivate(string org) + //{ + // var orgType = new List() { }; + + // return ValidateFormatSeExt(org.Substring(0, 5)); + //} + + ///// + ///// + ///// + ///// + ///// + //public static bool CheckLuhn(string vatNumber) + //{ + // // https://www.geeksforgeeks.org/luhn-algorithm/ + + // var nDigits = vatNumber.Length; + // var nSum = 0; + // var isSecond = false; + // for (var i = nDigits - 1; i >= 0; i--) + // { + // var d = (int)char.GetNumericValue(vatNumber[i]) - '0'; + // if (isSecond) + // d *= 2; + // // We add two digits to handle + // // cases that make two digits + // // after doubling + // nSum += d / 10; + // nSum += d % 10; + + // isSecond = !isSecond; + // } + + // return nSum % 10 == 0; + //} + + + //private static bool ValidateMod10(string number) + //{ + // if (long.Parse(number) == 0) + // return false; + + // var nDigits = number.Length; + // var nSum = 0; + // var isSecond = false; + // for (var i = nDigits - 1; i >= 0; i--) + // { + // var d = (int)char.GetNumericValue(number[i]) - '0'; + // if (isSecond) + // d *= 2; + // nSum += d / 10; + // nSum += d % 10; + // isSecond = !isSecond; + // } + // return nSum % 10 == 0; + //} + + //private static string GetMod10CheckDigit(string number) + //{ + // var sum = 0; + // var alt = true; + // var digits = number.ToCharArray(); + // for (var i = digits.Length - 1; i >= 0; i--) + // { + // var curDigit = digits[i] - 48; + // if (alt) + // { + // curDigit *= 2; + // if (curDigit > 9) + // curDigit -= 9; + // } + + // sum += curDigit; + // alt = !alt; + // } + // return sum % 10 == 0 ? "0" : (10 - sum % 10).ToString(); + //} + + //private string AddMod11CheckDigit(string number) + //{ + // return number + GetMod11CheckDigit(number); + //} + + //private static string GetMod11CheckDigit(string number) + //{ + // var sum = 0; + // for (int i = number.Length - 1, multiplier = 2; i >= 0; i--) + // { + // sum += (int)char.GetNumericValue(number[i]) * multiplier; + // if (++multiplier > 7) multiplier = 2; + // } + + // var modulo = sum % 11; + // return modulo is 0 or 1 ? "0" : (11 - modulo).ToString(); + //} + + //private static bool CheckLuhn(string vatNumber) + //{ + // // https://www.geeksforgeeks.org/luhn-algorithm/ + + // var nDigits = vatNumber.Length; + // var nSum = 0; + // var isSecond = false; + // for (var i = nDigits - 1; i >= 0; i--) + // { + // var d = (int)char.GetNumericValue(vatNumber[i]) - '0'; + // if (isSecond) + // d *= 2; + // // We add two digits to handle + // // cases that make two digits + // // after doubling + // nSum += d / 10; + // nSum += d % 10; + + // isSecond = !isSecond; + // } + + // return nSum % 10 == 0; + //} } \ No newline at end of file