Skip to content

sankdeveloper/short-sharp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MIT License Nuget Maintained - yes dotnet package Contributions - welcome docs.rs GitHub issues GitHub last commit (branch)

ShortSharp

ShortSharp(Your short code helper) is a day to day used C# Helper utility around the most common wrappers !!!
Let us handle the most common code for your applications supporting, Asp.net, Blazor, Webform, Xamarin and plus in almost all type of C# applications that are targeted to >=net6.

Installation

  Install-Package ShortSharp
  dotnet add package ShortSharp --version 1.x.x
  <PackageReference Include="ShortSharp" Version="1.x.x" />

API Reference

☞ Advance Looping

foreach (var i in 5..10)
{
  // var index = 5; index < result.Count; index++
}
foreach (var i in ..10)
{
  // iterate 0 to x
}
foreach (var i in 10)
{
  // iterate 0 to x
}

☞ Utilities

Simple In-memory job scheduler
BackgroundCronJobScheduler.Instance.ScheduleNew(
		jobFunction: () => System.WriteLine("Task exeecuted"),
		crownIntervalInMinutes: 1);
In-Memory File
// Create, Read, Write in memory file without creating on physical Disk based on UTF8-Encoding.
InMemoryFile inMemoryFile = new();

// Write fresh content to file.
inMemoryFile.WriteContent("old");
await inMemoryFile.WriteContentAsync("new");

// Append string content to file.(output: "new-appended")
await inMemoryFile.AppendContentAsync("-appended");

// Read all content of file.
string content = inMemoryFile.ReadContent();
string contentAsync = await inMemoryFile.ReadContentAsync();

// Save content to physical file
inMemoryFile.SaveAsFile("D:\\test.txt");
await inMemoryFile.SaveAsFileAsync("D:\\test.txt");

// Clear content of the file.
inMemoryFile.ClearFile();

☞ Helpers

Reflections
Parameter Type Description
Reflection.GetPublicPropertyNames<TClass>() IEnumerable<string> Read all properties of TClass
Reflection.GetPublicPropertyValues<TClass>(object) IReadOnlyDictionary<string, object?> Read all properties and values of TClass reference

☞ Json

Json Reader/Writer $\textcolor{green}{(1.3.0)}$
On Type Returns Description
object .ToJson(bool indented = true) string Converts a Type to a JSON string.
object .ToJson(JsonSerializerOptions options) string Converts a Type to a JSON string.
object .ToJsonFileAsync(string fileName) void Writes a Type to a JSON File.
FileInfo .ReadJsonFileAsync<T>() T Read a JSON File to strongly typed T.
FileInfo .WriteJsonDataAsync() void Writes a JSON File.
fileName as string .ReadJsonFileAsync<T>() T Read a JSON File to strongly typed T type.
string .IsValidJson() $\textcolor{green}{(1.5.1)}$ bool Returns true if json string is valid else false.
string validJson = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
validJson.IsValidJson(); // returns true
Json Converters
Parameter Description
DateTimeStringConverter datetime-in-string converter
IntConverter int-in-string converter
DynamicNestedObjectConverter dynamic object to Dictionary converter
// String format: "2022-10-21" (YYYY-mm-dd)
[JsonPropertyName("date")]
[JsonConverter(typeof(DateTimeStringConverter))]
public DateTime Date { get; set; }

// String format: "123654789"
[JsonPropertyName("id")]
[JsonConverter(typeof(IntConverter))]
public int IntegerId { get; set; }

// String format: {'prop1': {'one': 1}', 'prop2': {'two': 2}'.......}
[JsonPropertyName("object")]
[JsonConverter(typeof(DynamicNestedObjectConverter))]
public IReadOnlyDictionary<string, dynamic>> DynamicObject { get; set; }

☞ Extensions

IEnumerable
// Also applies to all implemented collections
// e.g. List, ICollection, IQuerable etc.
private readonly List<string> _list = new() { "One", "Two", "Three", "Four", "Five" };
private IEnumerable<Task<T>> asyncTasks = new List() { Task1, Task2.............. Task_n};
Parameter Description
_list.ForEach() Like List.ForEach() but slightly better in terms of iterations using IEnumerator.
_list.ForEachWithReturn() Like List.ForEach() but with returning back an new IEnumerable collection.
_list.PickRandom() Gets any one random item.
_list.PickRandom(n) Gets random 'n' number of items.
_list.Shuffle() Shuffle the list items.
_list.Shuffle(nTimes) Shuffle the list items n-times.
_list.Join(saperator: ",") Gets back a string with coma saperated words.
_list.ToCsv() $\textcolor{green}{(1.5.0)}$ Converts an IEnumerable to CSV formated string.
asyncTasks.WhenAllAsync() Wait till all task finishes.
asyncTasks.WhenAllSequentialAsync() Wait till all task finishes 'sequencially'.
asyncTasks.WhenAllByChunkAsync(chunkSize: 2) Process tasks by chunk(just like Pagination, e.g process 2 tasks at a time).
ICollection
// Also applies to all implemented collections
// e.g. List, ICollection, IQuerable etc.
private readonly ICollection<string> _list = new List<string> { "One", "Two", "Three", "Four", "Five" };
Parameter Type Description
_list.AddIf(predicate, value) / _list.RemoveIf(predicate, value) bool Adds/removes only if the value satisfies the predicate.
_list.AddIfNotContains(value) bool Add value if the ICollection doesn't contains it already.
_list.AddRange(v1, v2...) / _list.RemoveRange(v1, v2...) void Adds/removes a range to 'values'.
_list.AddRangeIf(predicate, v1, v2...) / _list.RemoveRangeIf(predicate, v1, v2...) void Adds/ removes a collection of objects to the end of this collection only for value who satisfies the predicate.
_list.RemoveWhere(predicate) void Removes value that satisfies the predicate.
IDictionary
private Dictionary<string, string> _dictionary = new();
Parameter Type Description
_dictionary.AddIfNotContainsKey(key, value) bool Adds if not contains key.
_dictionary.RemoveIfContainsKey(key) bool Removes if contains key.
_dictionary.UpsertByKey(key, value) value Add if the key does not already exist, or to update a key/value pair in the IDictionary<TKey, TValue>> if the key already exists.
_dictionary.GetOrAdd(predicate, value) value Adds a key/value pair if the key does not already exist.
_dictionary.RemoveIfContainsKey(predicate, value) void Removes if contains key.
Boolean Extensions
bool str = true;
Parameter Type Description
str.AsYOrN() string Returns Char 'Y' for true, 'N' for false.
str.AsYesOrNo() string Returns string 'Yes' for true, 'No' for false.
str.As0Or1() string Returns int '1' for true, '0' for false.
str.AsZeroOrOne() string Returns Char 'Zero' for true, 'One' for false.
DateTime Extensions
DateTime dt = new DateTime();
Parameter Type Description
dt.IsValid() bool Is falling in valid date time range
dt.AssumeUniversalTime() DateTime Assumes to DateTimeKind.Utc for current date-time
dt.ToJavaScriptTicks() long Gets javascript date-time.
Enum Extensions
enum Level 
{
  [Description("Low Level description")] 
  Low,
  
  [Description("Medium Level description")] 
  Medium,
  
  [Description("High Level description")] 
  High
}

Level @enum = Level.Medium;
Parameter Type Description
@enum.GetDescription() string Get description attribute value
@enum.GetDescriptions() IEnumerable<string> Get multiple description attribute value
EnumExtensions.ToDictionary(Level) Dictionary<string, string> Converts to dictionary
QueryString Extensions
var urlLink = "http://www.my-url/users?type=xyz";
Uri uri = new Uri(urlLink);
Parameter Type Description
uri.QueryString() NameValueCollection get entire querystring name/value collection
urlLink.QueryString() NameValueCollection get entire querystring name/value collection
uri.TryGetQueryStringParam(paramKey) string? get single querystring value with specified key
urlLink.TryGetQueryStringParam() string? get single querystring value with specified key
OI Extensions $\textcolor{green}{(1.2.1)}$
On Type Returns Description
string ToDirectoryInfo() DirectoryInfo Converts to directory
DirectoryInfo Clear() void A DirectoryInfo extension method that clears all files and directories in this directory.
DirectoryInfo DeleteDirectoriesWhere(predicate) void A DirectoryInfo extension method that deletes the directories where.
DirectoryInfo DeleteDirectoriesWhere(predicate, searchOption, searchPattern = "*.*") void A DirectoryInfo extension method that deletes the directories where.
DirectoryInfo DeleteFilesWhere(predicate) void A DirectoryInfo extension method that deletes the files where.
DirectoryInfo DeleteFilesWhere(predicate, searchOption, searchPattern = "*.*") void A DirectoryInfo extension method that deletes the files where.
DirectoryInfo DeleteOlderThan(DateTime minDate, searchOption, searchPattern = "*.*") void A DirectoryInfo extension method that deletes the older than.
DirectoryInfo EnsureDirectoryExists() DirectoryInfo Creates all directories and subdirectories in the specified @this if the directory doesn't already exists. This methods is the same as FileInfo.CreateDirectory however it's less ambigues about what happen if the directory already exists.
DirectoryInfo EnumerateDirectories(string searchPattern = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly) IEnumerable<DirectoryInfo> Enumerate directories
DirectoryInfo GetDirectories(string searchPatterns, SearchOption searchOption) DirectoryInfo[] Get all directories
DirectoryInfo GetDirectories(string[] searchPatterns, SearchOption searchOption) DirectoryInfo[] Get all directories
DirectoryInfo GetFiles(string searchPatterns = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly) FileInfo[] Get all files
DirectoryInfo GetFiles(string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly) FileInfo[] Get all files
DirectoryInfo GetFilesWhere(Func<FileInfo, bool> predicate, string searchPattern = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly) FileInfo[] Get all files with Where predicate having true/false.
DirectoryInfo PathCombine(params string[] paths) string Combines multiples string into a path.
DirectoryInfo PathCombineFile(params string[] paths) FileInfo Combines multiples string into a 'File' path.
DirectoryInfo EnumerateFiles(string searchPattern = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly) IEnumerable<FileInfo> Enumerate Files.
FileInfo EnsureExists() FileInfo Create file if not exists else dose nothing.
fileName as string ToFileInfo() FileInfo Converts string file path to FileInfo.
String Extensions
var str = "Hello, Blah blah blah...";
Parameter Type Description
str.EqualsCaseSensitive(string compareTo) bool Case Sensitive comparison
str.EqualsCaseIgnore(string compareTo) bool Case In-sensitive comparison
str.GetMD5Hash(bool toBase64 = false, bool unicode = false) string? Get MD hash
str.UrlEncode() string Encodes a URL string.
str.UrlEncode(Encoding encoding) string Encodes a URL string to specific encoding.
str.UrlDecode() string Converts a string that has been encoded for transmission in a URL into a decoded string.
str.UrlDecode(Encoding encoding) string Converts a string that has been encoded for transmission in a URL into a decoded string.
str.HtmlEncode() string Converts a string to an HTML-encoded string.
str.HtmlDecode() string Converts a string that has been HTML-encoded for HTTP transmission into a decoded string.
str.ToMemoryStream(Encoding encoding) string Convert value to a MemoryStream, using a default Unicode encoding.
str.IsInteger() bool Check if string is an Integer number.
str.IsDouble() bool Check if string is an Double number.

License

MIT

Authors

Feedback

If you have any feedback, please reach out to us at sankdeveloper@gmail.com

Roadmap

  • CI/CD pipeline for Nuget.org push.
  • More features will be still in progress to add.
  • Test cases and code coverage.

About

ShortSharp(Your short code helper) is a day to day used C# Helper utility around the most common wrappers.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages