(feature): codebase update with new methods, add separate license file
This commit is contained in:
		
							parent
							
								
									8ac380c7d4
								
							
						
					
					
						commit
						307cce4606
					
				
							
								
								
									
										21
									
								
								LICENSE.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								LICENSE.md
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,21 @@ | |||||||
|  | MIT License | ||||||
|  | 
 | ||||||
|  | Copyright (c) 2024 Maksym Sadovnychyy (MAKS-IT) | ||||||
|  | 
 | ||||||
|  | Permission is hereby granted, free of charge, to any person obtaining a copy | ||||||
|  | of this software and associated documentation files (the "Software"), to deal | ||||||
|  | in the Software without restriction, including without limitation the rights | ||||||
|  | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||||||
|  | copies of the Software, and to permit persons to whom the Software is | ||||||
|  | furnished to do so, subject to the following conditions: | ||||||
|  | 
 | ||||||
|  | The above copyright notice and this permission notice shall be included in all | ||||||
|  | copies or substantial portions of the Software. | ||||||
|  | 
 | ||||||
|  | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||||||
|  | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||||||
|  | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||||||
|  | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||||||
|  | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||||||
|  | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||||||
|  | SOFTWARE. | ||||||
							
								
								
									
										199
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										199
									
								
								README.md
									
									
									
									
									
								
							| @ -1,6 +1,6 @@ | |||||||
| # MaksIT.Core | # MaksIT.Core | ||||||
| 
 | 
 | ||||||
| MaksIT.Core is a collection of helper methods and extensions for .NET projects, designed to simplify common tasks and improve code readability. The library includes extensions for `Guid`, `string`, `Object`, and a base class for creating enumeration types. | MaksIT.Core is a collection of helper methods and extensions for .NET projects, designed to simplify common tasks and improve code readability. The library includes extensions for Guid, string, Object, security methods for password hashing, and a base class for creating enumeration types. | ||||||
| 
 | 
 | ||||||
| ## Table of Contents | ## Table of Contents | ||||||
| 
 | 
 | ||||||
| @ -10,13 +10,20 @@ MaksIT.Core is a collection of helper methods and extensions for .NET projects, | |||||||
|   - [Guid Extensions](#guid-extensions) |   - [Guid Extensions](#guid-extensions) | ||||||
|   - [Object Extensions](#object-extensions) |   - [Object Extensions](#object-extensions) | ||||||
|   - [String Extensions](#string-extensions) |   - [String Extensions](#string-extensions) | ||||||
|  |   - [Password Hasher](#password-hasher) | ||||||
|  |   - [DataTable Extensions](#datatable-extensions) | ||||||
|  |   - [DateTime Extensions](#datetime-extensions) | ||||||
| - [Available Methods](#available-methods) | - [Available Methods](#available-methods) | ||||||
|   - [Enumeration Methods](#enumeration-methods) |   - [Enumeration Methods](#enumeration-methods) | ||||||
|   - [Guid Methods](#guid-methods) |   - [Guid Methods](#guid-methods) | ||||||
|   - [Object Methods](#object-methods) |   - [Object Methods](#object-methods) | ||||||
|   - [String Methods](#string-methods) |   - [String Methods](#string-methods) | ||||||
|  |   - [Security Methods](#security-methods) | ||||||
|  |   - [DataTable Methods](#datatable-methods) | ||||||
|  |   - [DateTime Methods](#datetime-methods) | ||||||
| - [Contributing](#contributing) | - [Contributing](#contributing) | ||||||
| - [License](#license) | - [License](#license) | ||||||
|  | - [Contact](#contact) | ||||||
| 
 | 
 | ||||||
| ## Installation | ## Installation | ||||||
| 
 | 
 | ||||||
| @ -36,7 +43,7 @@ Or manually add it to your `.csproj` file: | |||||||
| 
 | 
 | ||||||
| ### Enumeration | ### Enumeration | ||||||
| 
 | 
 | ||||||
| The `Enumeration` base class provides a way to create strongly-typed enums in C#. This is useful for scenarios where you need more functionality than the default `enum` type. | The Enumeration base class provides a way to create strongly-typed enums in C#. This is useful for scenarios where you need more functionality than the default enum type. | ||||||
| 
 | 
 | ||||||
| **Example:** | **Example:** | ||||||
| 
 | 
 | ||||||
| @ -56,7 +63,7 @@ Console.WriteLine(activeStatus.Name); // Output: Active | |||||||
| 
 | 
 | ||||||
| ### Guid Extensions | ### Guid Extensions | ||||||
| 
 | 
 | ||||||
| The `GuidExtensions` class contains extensions for working with `Guid` types. | The `GuidExtensions` class contains extensions for working with Guid types. | ||||||
| 
 | 
 | ||||||
| **Example:** | **Example:** | ||||||
| 
 | 
 | ||||||
| @ -89,74 +96,152 @@ bool isLike = text.Like("Hello*"); // SQL-like matching | |||||||
| Console.WriteLine(isLike); // Output: True | Console.WriteLine(isLike); // Output: True | ||||||
| ``` | ``` | ||||||
| 
 | 
 | ||||||
|  | ### Password Hasher | ||||||
|  | 
 | ||||||
|  | The `PasswordHasher` class provides methods for creating salted hashes and verifying passwords using PBKDF2 with SHA-256. This is essential for securely storing and validating user passwords. | ||||||
|  | 
 | ||||||
|  | **Example:** | ||||||
|  | 
 | ||||||
|  | ```csharp | ||||||
|  | using MaksIT.Core.Security; | ||||||
|  | 
 | ||||||
|  | string password = "MySecurePassword123!"; | ||||||
|  | 
 | ||||||
|  | // Hash the password | ||||||
|  | if (PasswordHasher.TryHashPassword(password, out string? hashedPassword)) | ||||||
|  | { | ||||||
|  |     Console.WriteLine("Hashed Password: " + hashedPassword); | ||||||
|  |     // Store hashedPassword securely, e.g., in a database | ||||||
|  | } | ||||||
|  | else | ||||||
|  | { | ||||||
|  |     Console.WriteLine("Failed to hash password."); | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | // Later, when verifying the password during login | ||||||
|  | bool isValid = PasswordHasher.VerifyPassword(hashedPassword, password); | ||||||
|  | Console.WriteLine("Password is valid: " + isValid); // Output: True | ||||||
|  | ``` | ||||||
|  | 
 | ||||||
|  | ### DataTable Extensions | ||||||
|  | 
 | ||||||
|  | The `DataTableExtensions` class provides useful extensions for working with `DataTable` objects. | ||||||
|  | 
 | ||||||
|  | **Example:** | ||||||
|  | 
 | ||||||
|  | ```csharp | ||||||
|  | DataTable dt1 = new DataTable(); | ||||||
|  | dt1.Columns.Add("Id"); | ||||||
|  | dt1.Columns.Add("Name"); | ||||||
|  | dt1.Rows.Add("1", "Alice"); | ||||||
|  | dt1.Rows.Add("2", "Bob"); | ||||||
|  | 
 | ||||||
|  | DataTable dt2 = new DataTable(); | ||||||
|  | dt2.Columns.Add("Id"); | ||||||
|  | dt2.Columns.Add("Name"); | ||||||
|  | dt2.Rows.Add("1", "Alice"); | ||||||
|  | dt2.Rows.Add("3", "Charlie"); | ||||||
|  | 
 | ||||||
|  | int duplicateCount = dt1.DuplicatesCount(dt2); // Count duplicates | ||||||
|  | Console.WriteLine(duplicateCount); // Output: 1 | ||||||
|  | 
 | ||||||
|  | DataTable distinctRecords = dt1.DistinctRecords(new[] { "Id", "Name" }); // Get distinct records | ||||||
|  | Console.WriteLine(distinctRecords.Rows.Count); // Output: 2 | ||||||
|  | ``` | ||||||
|  | 
 | ||||||
|  | ### DateTime Extensions | ||||||
|  | 
 | ||||||
|  | The `DateTimeExtensions` class provides a variety of helpful methods for working with `DateTime` objects, such as adding workdays, finding the end of the month, or determining if a date is a holiday. | ||||||
|  | 
 | ||||||
|  | **Example:** | ||||||
|  | 
 | ||||||
|  | ```csharp | ||||||
|  | DateTime startDate = new DateTime(2023, 12, 22); // Friday | ||||||
|  | IHolidayCalendar holidayCalendar = new TestHolidayCalendar(new[] { new DateTime(2023, 12, 25) }); | ||||||
|  | 
 | ||||||
|  | DateTime resultDate = startDate.AddWorkdays(5, holidayCalendar); // Skip weekends and holidays | ||||||
|  | Console.WriteLine(resultDate); // Output: 2023-12-29 | ||||||
|  | 
 | ||||||
|  | DateTime nextThursday = DateTime.Now.NextWeekday(DayOfWeek.Thursday); | ||||||
|  | Console.WriteLine(nextThursday); // Output: Date of the next Thursday | ||||||
|  | ``` | ||||||
|  | 
 | ||||||
| ## Available Methods | ## Available Methods | ||||||
| 
 | 
 | ||||||
| ### Enumeration Methods | ### Enumeration Methods | ||||||
| 
 | 
 | ||||||
| - **`GetAll<T>()`**: Retrieves all static fields of a given type `T` that derive from `Enumeration`. | - **GetAll<T>()**: Retrieves all static fields of a given type T that derive from Enumeration. | ||||||
| - **`Equals(object? obj)`**: Determines whether the specified object is equal to the current object. | - **Equals(object? obj)**: Determines whether the specified object is equal to the current object. | ||||||
| - **`GetHashCode()`**: Returns the hash code for the current object. | - **GetHashCode()**: Returns the hash code for the current object. | ||||||
| - **`AbsoluteDifference(Enumeration firstValue, Enumeration secondValue)`**: Computes the absolute difference between two enumeration values. | - **AbsoluteDifference(Enumeration firstValue, Enumeration secondValue)**: Computes the absolute difference between two enumeration values. | ||||||
| - **`FromValue<T>(int value)`**: Retrieves an instance of type `T` from its integer value. | - **FromValue<T>(int value)**: Retrieves an instance of type T from its integer value. | ||||||
| - **`FromDisplayName<T>(string displayName)`**: Retrieves an instance of type `T` from its display name. | - **FromDisplayName<T>(string displayName)**: Retrieves an instance of type T from its display name. | ||||||
| - **`CompareTo(object? other)`**: Compares the current instance with another object of the same type. | - **CompareTo(object? other)**: Compares the current instance with another object of the same type. | ||||||
| 
 | 
 | ||||||
| ### Guid Methods | ### Guid Methods | ||||||
| 
 | 
 | ||||||
| - **`ToNullable(this Guid id)`**: Converts a `Guid` to a nullable `Guid?`. Returns `null` if the `Guid` is `Guid.Empty`. | - **ToNullable(this Guid id)**: Converts a Guid to a nullable `Guid?`. Returns null if the Guid is `Guid.Empty`. | ||||||
| 
 | 
 | ||||||
| ### Object Methods | ### Object Methods | ||||||
| 
 | 
 | ||||||
| - **`ToJson<T>(this T? obj)`**: Converts an object to a JSON string using default serialization options. | - **ToJson<T>(this T? obj)**: Converts an object to a JSON string using default serialization options. | ||||||
| - **`ToJson<T>(this T? obj, List<JsonConverter>? converters)`**: Converts an object to a JSON string using custom converters. | - **ToJson<T>(this T? obj, List<JsonConverter>? converters)**: Converts an object to a JSON string using custom converters. | ||||||
| 
 | 
 | ||||||
| ### String Methods | ### String Methods | ||||||
| 
 | 
 | ||||||
| - **`Like(this string? text, string? wildcardedText)`**: Determines if a string matches a given wildcard pattern (SQL LIKE). | - **Like(this string? text, string? wildcardedText)**: Determines if a string matches a given wildcard pattern (SQL LIKE). | ||||||
| - **`Left(this string s, int count)`**: Returns the left substring of the specified length. | - **Left(this string s, int count)**: Returns the left substring of the specified length. | ||||||
| - **`Right(this string s, int count)`**: Returns the right substring of the specified length. | - **Right(this string s, int count)**: Returns the right substring of the specified length. | ||||||
| - **`Mid(this string s, int index, int count)`**: Returns a substring starting from the specified index with the specified length. | - **Mid(this string s, int index, int count)**: Returns a substring starting from the specified index with the specified length. | ||||||
| - **`ToInteger(this string s)`**: Converts a string to an integer, returning zero if conversion fails. | - **ToInteger(this string s)**: Converts a string to an integer, returning zero if conversion fails. | ||||||
| - **`IsInteger(this string s)`**: Determines whether the string represents an integer. | - **IsInteger(this string s)**: Determines whether the string represents an integer. | ||||||
| - **`Prepend(this StringBuilder sb, string content)`**: Prepends content to the beginning of a `StringBuilder`. | - **Prepend(this StringBuilder sb, string content)**: Prepends content to the beginning of a `StringBuilder`. | ||||||
| - **`ToEnum<T>(this string input)`**: Converts a string to an enum value of type `T`. | - **ToEnum<T>(this string input)**: Converts a string to an enum value of type T. | ||||||
| - **`ToNullableEnum<T>(this string input)`**: Converts a string to a nullable enum value of type `T`. | - **ToNullableEnum<T>(this string input)**: Converts a string to a nullable enum value of type T. | ||||||
| - **`ToNull(this string s)`**: Returns `null` if the string is empty or whitespace. | - **ToNull(this string s)**: Returns null if the string is empty or whitespace. | ||||||
| - **`NullIfEmptyString(this string s)`**: Returns `null` if the string is empty or whitespace, otherwise returns the original string. | - **ToLong(this string s)**: Converts a string to a long, returning a hash code if conversion fails. | ||||||
| - **`ToLong(this string s)`**: Converts a string to a long, returning a hash code if conversion fails. | - **ToNullableLong(this string s)**: Converts a string to a nullable long, returning null if conversion fails. | ||||||
| - **`ToNullableLong(this string s)`**: Converts a string to a nullable long, returning `null` if conversion fails. | - **ToInt(this string s)**: Converts a string to an int, returning a hash code if conversion fails. | ||||||
| - **`ToInt(this string s)`**: Converts a string to an int, returning a hash code if conversion fails. | - **ToNullableInt(this string s)**: Converts a string to a nullable int, returning null if conversion fails. | ||||||
| - **`ToNullableInt(this string s)`**: Converts a string to a nullable int, returning `null` if conversion fails. | - **ToDecimal(this string s)**: Converts a string to a decimal, returning a hash code if conversion fails. | ||||||
| - **`ToUint(this string s)`**: Converts a string to a uint, returning a hash code if conversion fails. | - **ToNullableDecimal(this string s)**: Converts a string to a nullable decimal, returning null if conversion fails. | ||||||
| - **`ToNullableUint(this string s)`**: Converts a string to a nullable uint, returning `null` if conversion fails. | - **ToDouble(this string s)**: Converts a string to a double, returning a hash code if conversion fails. | ||||||
| - **`ToDecimal(this string s)`**: Converts a string to a decimal, returning a hash code if conversion fails. | - **ToNullableDouble(this string s)**: Converts a string to a nullable double, returning null if conversion fails. | ||||||
| - **`ToNullableDecimal(this string s)`**: Converts a string to a nullable decimal, returning `null` if conversion fails. | - **ToDate(this string s, string[] formats)**: Converts a string to a `DateTime` object using specified formats. | ||||||
| - **`ToDouble(this string s)`**: Converts a string to a double, returning a hash code if conversion fails. | - **ToDate(this string s)**: Converts a string to a `DateTime` object using the default format. | ||||||
| - **`ToNullableDouble(this string s)`**: Converts a string to a nullable double, returning `null` if conversion fails. | - **ToNullableDate(this string s)**: Converts a string to a nullable `DateTime` object using the default format. | ||||||
| - **`ToDate(this string s, string[] formats)`**: Converts a string to a `DateTime` object using a specified format. | - **ToNullableDate(this string s, string[] formats)**: Converts a string to a nullable `DateTime` object using specified formats. | ||||||
| - **`ToDate(this string s)`**: Converts a string to a `DateTime` object using the default format. | - **ToBool(this string s)**: Converts a string to a boolean. | ||||||
| - **`ToNullableDate(this string s)`**: Converts a string to a nullable `DateTime` object using the default format. | - **ToNullableBool(this string s)**: Converts a string to a nullable boolean. | ||||||
| - **`ToNullableDate(this string s, string[] formats)`**: Converts a string to a nullable `DateTime` object using specified formats. | - **ToGuid(this string text)**: Converts a string to a Guid. | ||||||
| - **`ToDateTime(this string s, string[] formats)`**: Converts a string to a `DateTime` object using specified formats. | - **ToNullableGuid(this string s)**: Converts a string to a nullable Guid. | ||||||
| - **`ToDateTime(this string s)`**: Converts a string to a `DateTime` object using the default formats. | - **StringSplit(this string s, char c)**: | ||||||
| - **`ToNullableDateTime(this string s)`**: Converts a string to a nullable `DateTime` object using the default formats. |  | ||||||
| - **`ToNullableDateTime(this string s, string[] formats)`**: Converts a string to a nullable `DateTime` object using specified formats. |  | ||||||
| - **`ToBool(this string s)`**: Converts a string to a boolean. |  | ||||||
| - **`ToNullableBool(this string s)`**: Converts a string to a nullable boolean. |  | ||||||
| - **`ToGuid(this string text)`**: Converts a string to a `Guid`. |  | ||||||
| - **`ToNullableGuid(this string s)`**: Converts a string to a nullable `Guid`. |  | ||||||
| - **`StringSplit(this string s, char c)`**: Splits a string by a specified character and trims each resulting element. |  | ||||||
| - **`ToTitle(this string s)`**: Converts the first character of the string to uppercase. |  | ||||||
| - **`ExtractUrls(this string s)`**: Extracts all URLs from a string. |  | ||||||
| - **`Format(this string s, params object[] args)`**: Formats a string using specified arguments. |  | ||||||
| - **`Excerpt(this string s, int length = 60)`**: Truncates a string to a specified length, adding ellipses if necessary. |  | ||||||
| - **`ToObject<T>(this string s)`**: Deserializes a JSON string into an object of type `T`. |  | ||||||
| - **`ToObject<T>(this string s, List<JsonConverter> converters)`**: Deserializes a JSON string into an object of type `T` using custom converters. |  | ||||||
| - **`IsValidEmail(this string? s)`**: Validates whether the string is a valid email format. |  | ||||||
| - **`HtmlToPlainText(this string htmlCode)`**: Converts HTML content to plain text. |  | ||||||
| - **`ToCamelCase(this string input)`**: Converts a string to camel case. |  | ||||||
| 
 | 
 | ||||||
| ## Contribution |  Splits a string by a specified character and trims each resulting element. | ||||||
|  | - **ToTitle(this string s)**: Converts the first character of the string to uppercase. | ||||||
|  | - **ExtractUrls(this string s)**: Extracts all URLs from a string. | ||||||
|  | - **Format(this string s, params object[] args)**: Formats a string using specified arguments. | ||||||
|  | - **Excerpt(this string s, int length = 60)**: Truncates a string to a specified length, adding ellipses if necessary. | ||||||
|  | - **ToObject<T>(this string s)**: Deserializes a JSON string into an object of type T. | ||||||
|  | - **ToObject<T>(this string s, List<JsonConverter> converters)**: Deserializes a JSON string into an object of type T using custom converters. | ||||||
|  | - **IsValidEmail(this string? s)**: Validates whether the string is a valid email format. | ||||||
|  | - **HtmlToPlainText(this string htmlCode)**: Converts HTML content to plain text. | ||||||
|  | - **ToCamelCase(this string input)**: Converts a string to camel case. | ||||||
|  | 
 | ||||||
|  | ### DataTable Methods | ||||||
|  | 
 | ||||||
|  | - **DuplicatesCount(this DataTable dt1, DataTable dt2)**: Counts the number of duplicate rows between two `DataTable` objects. | ||||||
|  | - **DistinctRecords(this DataTable dt, string[] columns)**: Returns distinct records based on the specified columns. | ||||||
|  | 
 | ||||||
|  | ### DateTime Methods | ||||||
|  | 
 | ||||||
|  | - **AddWorkdays(this DateTime date, int days, IHolidayCalendar holidayCalendar)**: Adds a specified number of workdays to a date, skipping weekends and holidays. | ||||||
|  | - **NextWeekday(this DateTime start, DayOfWeek day)**: Finds the next specified weekday from the given date. | ||||||
|  | - **IsEndOfMonth(this DateTime date)**: Checks if the date is the end of the month. | ||||||
|  | - **IsSameMonth(this DateTime date, DateTime targetDate)**: Checks if two dates are in the same month and year. | ||||||
|  | - **GetDifferenceInYears(this DateTime startDate, DateTime endDate)**: Returns the difference in years between two dates. | ||||||
|  | 
 | ||||||
|  | ## Contributing | ||||||
| 
 | 
 | ||||||
| Contributions to this project are welcome! Please fork the repository and submit a pull request with your changes. If you encounter any issues or have feature requests, feel free to open an issue on GitHub. | Contributions to this project are welcome! Please fork the repository and submit a pull request with your changes. If you encounter any issues or have feature requests, feel free to open an issue on GitHub. | ||||||
| 
 | 
 | ||||||
|  | |||||||
							
								
								
									
										66
									
								
								src/MaksIT.Core.Tests/Extensions/DataTableExtensionsTests.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										66
									
								
								src/MaksIT.Core.Tests/Extensions/DataTableExtensionsTests.cs
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,66 @@ | |||||||
|  | using System.Data; | ||||||
|  | using MaksIT.Core.Extensions; | ||||||
|  | 
 | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Tests.Extensions; | ||||||
|  | 
 | ||||||
|  | public class DataTableExtensionsTests { | ||||||
|  |   [Fact] | ||||||
|  |   public void DuplicatesCount_WithDuplicates_ReturnsCorrectCount() { | ||||||
|  |     // Arrange | ||||||
|  |     var dt1 = new DataTable(); | ||||||
|  |     dt1.Columns.Add("Id"); | ||||||
|  |     dt1.Columns.Add("Name"); | ||||||
|  |     dt1.Rows.Add("1", "Alice"); | ||||||
|  |     dt1.Rows.Add("2", "Bob"); | ||||||
|  | 
 | ||||||
|  |     var dt2 = new DataTable(); | ||||||
|  |     dt2.Columns.Add("Id"); | ||||||
|  |     dt2.Columns.Add("Name"); | ||||||
|  |     dt2.Rows.Add("1", "Alice"); | ||||||
|  |     dt2.Rows.Add("3", "Charlie"); | ||||||
|  | 
 | ||||||
|  |     // Act | ||||||
|  |     var duplicateCount = dt1.DuplicatesCount(dt2); | ||||||
|  | 
 | ||||||
|  |     // Assert | ||||||
|  |     Assert.Equal(1, duplicateCount); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   [Fact] | ||||||
|  |   public void DuplicatesCount_WithNoDuplicates_ReturnsZero() { | ||||||
|  |     // Arrange | ||||||
|  |     var dt1 = new DataTable(); | ||||||
|  |     dt1.Columns.Add("Id"); | ||||||
|  |     dt1.Columns.Add("Name"); | ||||||
|  |     dt1.Rows.Add("1", "Alice"); | ||||||
|  | 
 | ||||||
|  |     var dt2 = new DataTable(); | ||||||
|  |     dt2.Columns.Add("Id"); | ||||||
|  |     dt2.Columns.Add("Name"); | ||||||
|  |     dt2.Rows.Add("2", "Bob"); | ||||||
|  | 
 | ||||||
|  |     // Act | ||||||
|  |     var duplicateCount = dt1.DuplicatesCount(dt2); | ||||||
|  | 
 | ||||||
|  |     // Assert | ||||||
|  |     Assert.Equal(0, duplicateCount); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   [Fact] | ||||||
|  |   public void DistinctRecords_ReturnsDistinctRows() { | ||||||
|  |     // Arrange | ||||||
|  |     var dt = new DataTable(); | ||||||
|  |     dt.Columns.Add("Id"); | ||||||
|  |     dt.Columns.Add("Name"); | ||||||
|  |     dt.Rows.Add("1", "Alice"); | ||||||
|  |     dt.Rows.Add("1", "Alice"); | ||||||
|  |     dt.Rows.Add("2", "Bob"); | ||||||
|  | 
 | ||||||
|  |     // Act | ||||||
|  |     var distinctDt = dt.DistinctRecords(new[] { "Id", "Name" }); | ||||||
|  | 
 | ||||||
|  |     // Assert | ||||||
|  |     Assert.Equal(2, distinctDt.Rows.Count); | ||||||
|  |   } | ||||||
|  | } | ||||||
							
								
								
									
										83
									
								
								src/MaksIT.Core.Tests/Extensions/DateTimeExtensionsTests.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										83
									
								
								src/MaksIT.Core.Tests/Extensions/DateTimeExtensionsTests.cs
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,83 @@ | |||||||
|  | using MaksIT.Core.Extensions; | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Tests.Extensions { | ||||||
|  | 
 | ||||||
|  |   public class DateTimeExtensionsTests { | ||||||
|  |     // Mock implementation of IHolidayCalendar for testing | ||||||
|  |     private class TestHolidayCalendar : IHolidayCalendar { | ||||||
|  |       private readonly HashSet<DateTime> _holidays; | ||||||
|  | 
 | ||||||
|  |       public TestHolidayCalendar(IEnumerable<DateTime> holidays) { | ||||||
|  |         _holidays = new HashSet<DateTime>(holidays); | ||||||
|  |       } | ||||||
|  | 
 | ||||||
|  |       public bool Contains(DateTime date) { | ||||||
|  |         return _holidays.Contains(date.Date); | ||||||
|  |       } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void AddWorkdays_PositiveDays_SkipsWeekendsAndHolidays() { | ||||||
|  |       // Arrange | ||||||
|  |       var startDate = new DateTime(2023, 12, 22); // Friday | ||||||
|  |       int daysToAdd = 5; | ||||||
|  |       var holidays = new List<DateTime> | ||||||
|  |       { | ||||||
|  |                 new DateTime(2023, 12, 25), // Christmas Day (Monday) | ||||||
|  |             }; | ||||||
|  |       var holidayCalendar = new TestHolidayCalendar(holidays); | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var resultDate = startDate.AddWorkdays(daysToAdd, holidayCalendar); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.Equal(new DateTime(2023, 12, 29), resultDate); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void AddWorkdays_NegativeDays_SkipsWeekendsAndHolidays() { | ||||||
|  |       // Arrange | ||||||
|  |       var startDate = new DateTime(2023, 1, 3); // Tuesday | ||||||
|  |       int daysToAdd = -5; | ||||||
|  |       var holidays = new List<DateTime> | ||||||
|  |       { | ||||||
|  |                 new DateTime(2023, 1, 1), // New Year's Day (Sunday) | ||||||
|  |             }; | ||||||
|  |       var holidayCalendar = new TestHolidayCalendar(holidays); | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var resultDate = startDate.AddWorkdays(daysToAdd, holidayCalendar); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.Equal(new DateTime(2022, 12, 28), resultDate); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     // ... rest of your tests remain the same | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void NextWeekday_ReturnsNextWeek_WhenTargetDayIsToday() { | ||||||
|  |       // Arrange | ||||||
|  |       var startDate = new DateTime(2023, 10, 5); // Thursday | ||||||
|  |       var targetDay = DayOfWeek.Thursday; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var resultDate = startDate.NextWeekday(targetDay); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.Equal(new DateTime(2023, 10, 12), resultDate); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ToNextWeekday_ReturnsSevenDays_WhenTargetDayIsToday() { | ||||||
|  |       // Arrange | ||||||
|  |       var startDate = new DateTime(2023, 10, 5); // Thursday | ||||||
|  |       var targetDay = DayOfWeek.Thursday; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var timeSpan = startDate.ToNextWeekday(targetDay); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.Equal(TimeSpan.FromDays(7), timeSpan); | ||||||
|  |     } | ||||||
|  |   } | ||||||
|  | } | ||||||
| @ -1,7 +1,8 @@ | |||||||
| using System; | using MaksIT.Core.Extensions; | ||||||
| using Xunit; | 
 | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Tests.Extensions { | ||||||
| 
 | 
 | ||||||
| namespace MaksIT.Core.Extensions.Tests { |  | ||||||
|   public class GuidExtensionsTests { |   public class GuidExtensionsTests { | ||||||
|     [Fact] |     [Fact] | ||||||
|     public void ToNullable_WithEmptyGuid_ShouldReturnNull() { |     public void ToNullable_WithEmptyGuid_ShouldReturnNull() { | ||||||
|  | |||||||
| @ -1,4 +1,4 @@ | |||||||
| <Project Sdk="Microsoft.NET.Sdk"> | <Project Sdk="Microsoft.NET.Sdk"> | ||||||
| 
 | 
 | ||||||
|   <PropertyGroup> |   <PropertyGroup> | ||||||
|     <TargetFramework>net8.0</TargetFramework> |     <TargetFramework>net8.0</TargetFramework> | ||||||
|  | |||||||
							
								
								
									
										174
									
								
								src/MaksIT.Core.Tests/Security/PasswordHasherTests.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										174
									
								
								src/MaksIT.Core.Tests/Security/PasswordHasherTests.cs
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,174 @@ | |||||||
|  | using MaksIT.Core.Security; | ||||||
|  | using Xunit; | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Tests.Security { | ||||||
|  |   public class PasswordHasherTests { | ||||||
|  |     [Fact] | ||||||
|  |     public void CreateSaltedHash_ValidPassword_ReturnsSaltAndHash() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var result = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(string.IsNullOrWhiteSpace(result.Salt)); | ||||||
|  |       Assert.False(string.IsNullOrWhiteSpace(result.Hash)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void CreateSaltedHash_EmptyPassword_ReturnsSaltAndHash() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = ""; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var result = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(string.IsNullOrWhiteSpace(result.Salt)); | ||||||
|  |       Assert.False(string.IsNullOrWhiteSpace(result.Hash)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void CreateSaltedHash_WhitespacePassword_ReturnsSaltAndHash() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "   "; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var result = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(string.IsNullOrWhiteSpace(result.Salt)); | ||||||
|  |       Assert.False(string.IsNullOrWhiteSpace(result.Hash)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ValidateHash_CorrectPassword_ReturnsTrue() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  |       var hashResult = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var verifyResult = PasswordHasher.ValidateHash(password, hashResult.Salt, hashResult.Hash); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.True(verifyResult); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ValidateHash_IncorrectPassword_ReturnsFalse() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  |       var wrongPassword = "WrongPassword456!"; | ||||||
|  |       var hashResult = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var verifyResult = PasswordHasher.ValidateHash(wrongPassword, hashResult.Salt, hashResult.Hash); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(verifyResult); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ValidateHash_EmptyStoredHash_ReturnsFalse() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  |       var storedHash = ""; | ||||||
|  |       var salt = ""; // Assuming empty salt | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var verifyResult = PasswordHasher.ValidateHash(password, salt, storedHash); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(verifyResult); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ValidateHash_WhitespaceStoredHash_ReturnsFalse() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  |       var storedHash = "   "; | ||||||
|  |       var salt = "   "; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var verifyResult = PasswordHasher.ValidateHash(password, salt, storedHash); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(verifyResult); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ValidateHash_InvalidStoredHash_ReturnsFalse() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  |       var invalidStoredHash = "InvalidHashValue"; | ||||||
|  |       var invalidSalt = "InvalidSaltValue"; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var verifyResult = PasswordHasher.ValidateHash(password, invalidSalt, invalidStoredHash); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(verifyResult); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void CreateSaltedHash_SamePasswordDifferentHashes() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var hashResult1 = PasswordHasher.CreateSaltedHash(password); | ||||||
|  |       var hashResult2 = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.NotEqual(hashResult1.Hash, hashResult2.Hash); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void ValidateHash_ModifiedStoredHash_ReturnsFalse() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  |       var hashResult = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Modify the stored hash | ||||||
|  |       var hashChars = hashResult.Hash.ToCharArray(); | ||||||
|  |       hashChars[10] = (hashChars[10] == 'A') ? 'B' : 'A'; // Change one character | ||||||
|  |       var modifiedHash = new string(hashChars); | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var verifyResult = PasswordHasher.ValidateHash(password, hashResult.Salt, modifiedHash); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.False(verifyResult); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void CreateSaltedHash_DifferentPasswordsHaveDifferentHashes() { | ||||||
|  |       // Arrange | ||||||
|  |       var password1 = "PasswordOne"; | ||||||
|  |       var password2 = "PasswordTwo"; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var hashResult1 = PasswordHasher.CreateSaltedHash(password1); | ||||||
|  |       var hashResult2 = PasswordHasher.CreateSaltedHash(password2); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       Assert.NotEqual(hashResult1.Hash, hashResult2.Hash); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     [Fact] | ||||||
|  |     public void CreateSaltedHash_ReturnsBase64StringsOfExpectedLength() { | ||||||
|  |       // Arrange | ||||||
|  |       var password = "SecurePassword123!"; | ||||||
|  | 
 | ||||||
|  |       // Act | ||||||
|  |       var result = PasswordHasher.CreateSaltedHash(password); | ||||||
|  | 
 | ||||||
|  |       // Assert | ||||||
|  |       // For 16 bytes salt, Base64 length is 24 characters | ||||||
|  |       Assert.Equal(24, result.Salt.Length); | ||||||
|  |       // For 32 bytes hash, Base64 length is 44 characters | ||||||
|  |       Assert.Equal(44, result.Hash.Length); | ||||||
|  |     } | ||||||
|  |   } | ||||||
|  | } | ||||||
							
								
								
									
										44
									
								
								src/MaksIT.Core/Extensions/DataTableExtensions.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								src/MaksIT.Core/Extensions/DataTableExtensions.cs
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,44 @@ | |||||||
|  | using System.Data; | ||||||
|  | 
 | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Extensions; | ||||||
|  | public static class DataTableExtensions { | ||||||
|  | 
 | ||||||
|  |   public static int DuplicatesCount(this DataTable dt1, DataTable dt2) { | ||||||
|  |     if (dt1 == null) | ||||||
|  |       throw new ArgumentNullException(nameof(dt1)); | ||||||
|  |     if (dt2 == null) | ||||||
|  |       throw new ArgumentNullException(nameof(dt2)); | ||||||
|  | 
 | ||||||
|  |     var duplicates = 0; | ||||||
|  |     foreach (DataRow dtRow1 in dt1.Rows) { | ||||||
|  |       var dt1Items = dtRow1.ItemArray.Select(item => item?.ToString() ?? string.Empty); | ||||||
|  |       var dt1Comp = string.Join("", dt1Items); | ||||||
|  |       foreach (DataRow dtRow2 in dt2.Rows) { | ||||||
|  |         var dt2Items = dtRow2.ItemArray.Select(item => item?.ToString() ?? string.Empty); | ||||||
|  |         var dt2Comp = string.Join("", dt2Items); | ||||||
|  | 
 | ||||||
|  |         if (dt1Comp == dt2Comp) { | ||||||
|  |           duplicates++; | ||||||
|  |         } | ||||||
|  |       } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     return duplicates; | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   /// <summary> | ||||||
|  |   /// Returns distinct records based on specified columns. | ||||||
|  |   /// </summary> | ||||||
|  |   /// <param name="dt"></param> | ||||||
|  |   /// <param name="columns"></param> | ||||||
|  |   /// <returns></returns> | ||||||
|  |   public static DataTable DistinctRecords(this DataTable dt, string[] columns) { | ||||||
|  |     if (dt == null) | ||||||
|  |       throw new ArgumentNullException(nameof(dt)); | ||||||
|  |     if (columns == null) | ||||||
|  |       throw new ArgumentNullException(nameof(columns)); | ||||||
|  | 
 | ||||||
|  |     return dt.DefaultView.ToTable(true, columns); | ||||||
|  |   } | ||||||
|  | } | ||||||
							
								
								
									
										104
									
								
								src/MaksIT.Core/Extensions/DateTimeExtensions.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										104
									
								
								src/MaksIT.Core/Extensions/DateTimeExtensions.cs
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,104 @@ | |||||||
|  | using System; | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Extensions; | ||||||
|  | 
 | ||||||
|  | public static class DateTimeExtensions { | ||||||
|  |   public static DateTime AddWorkdays(this DateTime date, int days, IHolidayCalendar holidayCalendar) { | ||||||
|  |     if (days == 0) | ||||||
|  |       return date; | ||||||
|  | 
 | ||||||
|  |     int direction = days > 0 ? 1 : -1; | ||||||
|  |     int absDays = Math.Abs(days); | ||||||
|  |     DateTime currentDate = date; | ||||||
|  | 
 | ||||||
|  |     while (absDays > 0) { | ||||||
|  |       // If the current date is a workday, decrement absDays | ||||||
|  |       if (currentDate.DayOfWeek != DayOfWeek.Saturday && | ||||||
|  |           currentDate.DayOfWeek != DayOfWeek.Sunday && | ||||||
|  |           !holidayCalendar.Contains(currentDate)) { | ||||||
|  |         absDays--; | ||||||
|  |         if (absDays == 0) | ||||||
|  |           break; | ||||||
|  |       } | ||||||
|  | 
 | ||||||
|  |       // Move to the next date | ||||||
|  |       currentDate = currentDate.AddDays(direction); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     return currentDate; | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   public static DateTime AddWorkdays(this DateTime date, TimeSpan timeSpanWorkDays, IHolidayCalendar holidayCalendar) => | ||||||
|  |       date.AddWorkdays(timeSpanWorkDays.Days, holidayCalendar); | ||||||
|  | 
 | ||||||
|  |   public static DateTime NextWeekday(this DateTime start, DayOfWeek day) { | ||||||
|  |     int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7; | ||||||
|  |     daysToAdd = daysToAdd == 0 ? 7 : daysToAdd; // If today is the target day, move to next week | ||||||
|  |     return start.AddDays(daysToAdd); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   public static TimeSpan ToNextWeekday(this DateTime start, DayOfWeek day) { | ||||||
|  |     int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7; | ||||||
|  |     daysToAdd = daysToAdd == 0 ? 7 : daysToAdd; | ||||||
|  |     return TimeSpan.FromDays(daysToAdd); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   public static DateTime NextEndOfMonth(this DateTime date) { | ||||||
|  |     var nextMonth = date.AddMonths(1); | ||||||
|  |     return new DateTime( | ||||||
|  |         nextMonth.Year, | ||||||
|  |         nextMonth.Month, | ||||||
|  |         DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month), | ||||||
|  |         date.Hour, | ||||||
|  |         date.Minute, | ||||||
|  |         date.Second, | ||||||
|  |         date.Kind); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   public static DateTime EndOfMonth(this DateTime date) => | ||||||
|  |       new DateTime( | ||||||
|  |           date.Year, | ||||||
|  |           date.Month, | ||||||
|  |           DateTime.DaysInMonth(date.Year, date.Month), | ||||||
|  |           date.Hour, | ||||||
|  |           date.Minute, | ||||||
|  |           date.Second, | ||||||
|  |           date.Kind); | ||||||
|  | 
 | ||||||
|  |   public static DateTime BeginOfMonth(this DateTime date) => | ||||||
|  |       new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind); | ||||||
|  | 
 | ||||||
|  |   public static DateTime StartOfYear(this DateTime date) => | ||||||
|  |       new DateTime(date.Year, 1, 1, date.Hour, date.Minute, date.Second, date.Kind); | ||||||
|  | 
 | ||||||
|  |   public static DateTime EndOfYear(this DateTime date) => | ||||||
|  |       new DateTime(date.Year, 12, 31, date.Hour, date.Minute, date.Second, date.Kind); | ||||||
|  | 
 | ||||||
|  |   public static bool IsEndOfMonth(this DateTime date) => | ||||||
|  |       date.Day == DateTime.DaysInMonth(date.Year, date.Month); | ||||||
|  | 
 | ||||||
|  |   public static bool IsBeginOfMonth(this DateTime date) => date.Day == 1; | ||||||
|  | 
 | ||||||
|  |   public static bool IsEndOfYear(this DateTime date) => date.Day == 31 && date.Month == 12; | ||||||
|  | 
 | ||||||
|  |   public static bool IsSameMonth(this DateTime date, DateTime targetDate) => | ||||||
|  |       date.Month == targetDate.Month && date.Year == targetDate.Year; | ||||||
|  | 
 | ||||||
|  |   public static int GetDifferenceInYears(this DateTime startDate, DateTime endDate) { | ||||||
|  |     // Implementation follows the logic used in Excel's DATEDIF function | ||||||
|  |     // "COMPLETE calendar years in between dates" | ||||||
|  | 
 | ||||||
|  |     int years = endDate.Year - startDate.Year; | ||||||
|  | 
 | ||||||
|  |     if (endDate.Month < startDate.Month || | ||||||
|  |         (endDate.Month == startDate.Month && endDate.Day < startDate.Day)) { | ||||||
|  |       years--; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     return years; | ||||||
|  |   } | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | public interface IHolidayCalendar { | ||||||
|  |   bool Contains(DateTime date); | ||||||
|  | } | ||||||
| @ -1,6 +1,7 @@ | |||||||
| using System; | using System; | ||||||
| using System.Collections.Generic; | using System.Collections.Generic; | ||||||
| using System.ComponentModel.DataAnnotations; | using System.ComponentModel.DataAnnotations; | ||||||
|  | using System.Data; | ||||||
| using System.Globalization; | using System.Globalization; | ||||||
| using System.Linq; | using System.Linq; | ||||||
| using System.Security.Cryptography; | using System.Security.Cryptography; | ||||||
| @ -228,5 +229,38 @@ namespace MaksIT.Core.Extensions { | |||||||
| 
 | 
 | ||||||
|       return string.Join("", words); |       return string.Join("", words); | ||||||
|     } |     } | ||||||
|  | 
 | ||||||
|  |     public static DataTable CSVToDataTable(this string filePath) { | ||||||
|  |       if (string.IsNullOrEmpty(filePath)) | ||||||
|  |         throw new ArgumentNullException(nameof(filePath)); | ||||||
|  | 
 | ||||||
|  |       using var sr = new StreamReader(filePath); | ||||||
|  | 
 | ||||||
|  |       var headerLine = sr.ReadLine(); | ||||||
|  |       if (headerLine == null) | ||||||
|  |         throw new InvalidOperationException("File is empty"); | ||||||
|  | 
 | ||||||
|  |       var headers = headerLine.Split(','); | ||||||
|  |       var dt = new DataTable(); | ||||||
|  |       foreach (var header in headers) { | ||||||
|  |         dt.Columns.Add(header); | ||||||
|  |       } | ||||||
|  | 
 | ||||||
|  |       while (!sr.EndOfStream) { | ||||||
|  |         var line = sr.ReadLine(); | ||||||
|  |         if (line == null) | ||||||
|  |           continue; | ||||||
|  | 
 | ||||||
|  |         var rows = Regex.Split(line, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); | ||||||
|  |         var dr = dt.NewRow(); | ||||||
|  | 
 | ||||||
|  |         for (var i = 0; i < headers.Length; i++) { | ||||||
|  |           dr[i] = i < rows.Length ? rows[i] : string.Empty; | ||||||
|  |         } | ||||||
|  |         dt.Rows.Add(dr); | ||||||
|  |       } | ||||||
|  | 
 | ||||||
|  |       return dt; | ||||||
|  |     } | ||||||
|   } |   } | ||||||
| } | } | ||||||
|  | |||||||
| @ -4,11 +4,11 @@ | |||||||
|     <TargetFramework>net8.0</TargetFramework> |     <TargetFramework>net8.0</TargetFramework> | ||||||
|     <ImplicitUsings>enable</ImplicitUsings> |     <ImplicitUsings>enable</ImplicitUsings> | ||||||
|     <Nullable>enable</Nullable> |     <Nullable>enable</Nullable> | ||||||
|     <RootNamespace>MaksIT.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace> |     <RootNamespace>$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace> | ||||||
| 
 | 
 | ||||||
|     <!-- NuGet package metadata --> |     <!-- NuGet package metadata --> | ||||||
|     <PackageId>MaksIT.Core</PackageId> |     <PackageId>MaksIT.Core</PackageId> | ||||||
|     <Version>1.0.0</Version> |     <Version>1.0.2</Version> | ||||||
|     <Authors>Maksym Sadovnychyy</Authors> |     <Authors>Maksym Sadovnychyy</Authors> | ||||||
|     <Company>MAKS-IT</Company> |     <Company>MAKS-IT</Company> | ||||||
|     <Product>MaksIT.Core</Product> |     <Product>MaksIT.Core</Product> | ||||||
| @ -23,4 +23,8 @@ | |||||||
|   <ItemGroup> |   <ItemGroup> | ||||||
|     <None Include="../../README.md" Pack="true" PackagePath="" /> |     <None Include="../../README.md" Pack="true" PackagePath="" /> | ||||||
|   </ItemGroup> |   </ItemGroup> | ||||||
|  | 
 | ||||||
|  |   <ItemGroup> | ||||||
|  |     <PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="8.0.8" /> | ||||||
|  |   </ItemGroup> | ||||||
| </Project> | </Project> | ||||||
|  | |||||||
							
								
								
									
										43
									
								
								src/MaksIT.Core/Security/PasswordHasher.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								src/MaksIT.Core/Security/PasswordHasher.cs
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,43 @@ | |||||||
|  | using System.Security.Cryptography; | ||||||
|  | using Microsoft.AspNetCore.Cryptography.KeyDerivation; | ||||||
|  | 
 | ||||||
|  | namespace MaksIT.Core.Security; | ||||||
|  | 
 | ||||||
|  | public static class PasswordHasher { | ||||||
|  |   private static byte[] CreateSaltBytes() { | ||||||
|  |     byte[] randomBytes = new byte[16]; | ||||||
|  |     using (var generator = RandomNumberGenerator.Create()) { | ||||||
|  |       generator.GetBytes(randomBytes); | ||||||
|  |     } | ||||||
|  |     return randomBytes; | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   private static string CreateHash(string value, byte[] saltBytes) { | ||||||
|  |     var valueBytes = KeyDerivation.Pbkdf2( | ||||||
|  |         password: value, | ||||||
|  |         salt: saltBytes, | ||||||
|  |         prf: KeyDerivationPrf.HMACSHA512, | ||||||
|  |         iterationCount: 100_000, // Increased iteration count | ||||||
|  |         numBytesRequested: 256 / 8); | ||||||
|  | 
 | ||||||
|  |     return Convert.ToBase64String(valueBytes); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   public static (string Salt, string Hash) CreateSaltedHash(string value) { | ||||||
|  |     var saltBytes = CreateSaltBytes(); | ||||||
|  |     var hash = CreateHash(value, saltBytes); | ||||||
|  |     var salt = Convert.ToBase64String(saltBytes); | ||||||
|  | 
 | ||||||
|  |     return (salt, hash); | ||||||
|  |   } | ||||||
|  | 
 | ||||||
|  |   public static bool ValidateHash(string value, string salt, string hash) { | ||||||
|  |     var saltBytes = Convert.FromBase64String(salt); | ||||||
|  |     var hashToCompare = CreateHash(value, saltBytes); | ||||||
|  | 
 | ||||||
|  |     return CryptographicOperations.FixedTimeEquals( | ||||||
|  |         Convert.FromBase64String(hashToCompare), | ||||||
|  |         Convert.FromBase64String(hash) | ||||||
|  |     ); | ||||||
|  |   } | ||||||
|  | } | ||||||
		Loading…
	
		Reference in New Issue
	
	Block a user
	 Maksym Sadovnychyy
						Maksym Sadovnychyy