ToolsPack.String 3.1.1

dotnet add package ToolsPack.String --version 3.1.1
NuGet\Install-Package ToolsPack.String -Version 3.1.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ToolsPack.String" Version="3.1.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add ToolsPack.String --version 3.1.1
#r "nuget: ToolsPack.String, 3.1.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install ToolsPack.String as a Cake Addin
#addin nuget:?package=ToolsPack.String&version=3.1.1

// Install ToolsPack.String as a Cake Tool
#tool nuget:?package=ToolsPack.String&version=3.1.1

ToolsPack.String

ArrayDisplayer

  • Know to convert a IEnummerable to string in order do display in a log message
var arr = new string[1000] {"item1".."item1000"};
arr.Display().SeparatedBy("; ").MaxItems(4)

gives

{ item1; item2; item3; item4; ..and 996 (of 1000) more }
  • If some items in the array are very long. We should limit the length of individual item with MaxItemLength() so that long items will be displayed with ... ellipsis
var arr = new string[1000] {"Lorem ipsum kidda foom", "item2".."item1000"};
arr.Display().MaxItems(4).MaxItemLength(10)

gives

{ [[Lorem...]], item2, item3, item4, ..and 996 (of 1000) more }
  • Fast performance it only iterate neccessary items once (complexity O(N))
  • see more functionalities in code and test

StopwatchDisplayer

convert Stopwatch to string

Stopwatch sw;
Console.WriteLine(sw.DisplayMili()); //get the display string in mili seconds "103 ms"
Console.WriteLine(sw.DisplayMicro()); //get the display string in micro seconds "103,000 mcs"
Console.WriteLine(sw.Display()); //automaticly choose a time unit (day, hour, minute, seconde..) to display

Tips

For some serializable object which don't implement ToString(). Newtonsoft.Json can convert them to json. DO NOT use this technique on production. The reflection is bad for Perf..

Newtonsoft.Json.JsonConvert.SerializeObject(someObject);

Ellipsis

ArrayDisplayer.DefaultEllipsis("1234567890", 4, "..."); //gives "1234..."
ArrayDisplayer.WordEllipsis("123 567 90", 5, "..."); //gives "123 567..."

Utf8SealCalculator

string signature = Utf8SealCalculator.HMACSHA256("payload", "secret", Utf8SealCalculator.ToHex);
  • Convert the payload string and the secret string to byte[] tables with a Utf-8 encoder
    • If the secret or the payload represents a "hexString" (for eg.: "1a94f6c5a9") then you will have to declare secretIsHexString = true or payloadIsHexString = true so that they will be treated as HexString or else they will be treated as normal text string by default.
  • Use the secret byte[] table to hash the payload byte[] table with the HMACSHA256 algorithm
  • the third parameter convert the hash result back to string. You can use for example:
    • Utf8SealCalculator.ToHex: format the hash result from byte[] to hexa value string
    • Convert.ToBase64String: format the hash result from byte[] to a base64 string

The result string is usually used as a seal or a signature to authenticate the payload content.

Other supported hashing algorithms are:

  • HMACSHA1 (not secure)
  • HMACSHA256
  • HMACSHA384
  • HMACSHA512
  • SHA1 (not secure)
  • SHA256
  • SHA384
  • SHA512

Asymmetric Encryption RSA

The symmetric encryption is straightforward in the .NET SDK. But the asymmetric encryption is a little more complex.

If you got lost in the Microsoft Docs RSA class, then the sample codes in RsaEncryptionTest.cs should cover most of your needs:

  • How to generate a Private Key and Public Key (using C# or OpenSsl).
  • How to use the public key to encrypt, and the Private key to decrypt a string payload.

DiacriticsRemover

string message = DiacriticsRemover.RemoveDiacritics("où déjà aperçu la phénomène"); //returns "ou deja apercu la phenomene"

CreateRandomString

string randomString = StringGenerator.CreateRandomString(5, 0, "abcdefghijklmnpqrstuvwxyz0123456789");
  • Generate a random string of length 5 using random characters in "abcdefghijklmnpqrstuvwxyz0123456789"
  • 0 is the length variable, 0-variable means that the length result is fix to 5.
  • CreateRandomString(5, 3) will result a string with length variable between (5 and 8)

Remark:

  1. A random string is not suppose to replace the GUID because it got higher chance of colission. If you want a shorter Guid then check out the ShortGuid class
  2. If you want to generate nice fake data such as Person name, Email, Product... then Checkout the the Bogus project. Example:
// Generate random object (which looks "real")
var walletGenerator = new Faker<Wallet>()
    .RuleFor(o => o.Gender, f => (int)f.PickRandom<Gender>())
    .RuleFor(o => o.FirstName, (f, o) => f.Name.FirstName((Gender)o.Gender))
    .RuleFor(o => o.LastName, (f, o) => f.Name.LastName())
    .RuleFor(o => o.Situation, f => f.Random.Int(0, 6))
    .RuleFor(o => o.IsBlocked, f => f.PickRandomParam(true, false))
    .RuleFor(o => o.Email, (f, o) => f.Internet.Email(o.FirstName, o.LastName))
    .RuleFor(o => o.Balance, f => f.Random.Decimal(0, 10000))
    .RuleFor(o => o.Name, (f, o) => o.FirstName.ToLower() + "." + o.LastName.ToLower() + "." + f.Random.String2(5))
    .RuleFor(o => o.CreationDate, f => f.Date.Past(3))
;
var w = walletGenerator.Generate();

// Generate random string (same as what the ToolsPack)

var faker = new Faker();
var randomString = faker.Random.String2(minLength: 3, maxLength: 10, chars "abcdefghijklmnopqrstuvwxyz"); 

ShortGuid

A normal GUID (or UUID) is a random 128-bit, the standard Microsoft Guid class format it in base-16 so a length-32 string. Why not format it in base-64 for a shorter (length-22) string? Here how to do it:

var g = Guid.NewGuid();

var shortGuid = g.ToShortGuid();
Assert.Equal(g, ShortGuid.Parse(shortGuid));

var shortGuidUrlFriendly = g.ToShortGuid(true);
Assert.Equal(g, ShortGuid.Parse(shortGuidUrlFriendly, true));

Note:

  1. if the ShortGuid (length-22) is still too long, you can create a even shorter unique id with Sqids. Youtube is using this popular technique to create short + unique id for their videos. Checkout this video

  2. Consider to use the a ULID (Universally Unique Lexicographically Sortable Identifier) instead of UUID library if you want to generate a sequential (sortable) GUID.

SqlServerConnectionStringBuilder

string connectionString = SqlServerConnectionStringBuilder.Build("localhost", "mydb", "root", "secretpassword");

UriCombine

Assert.Equal("http://www.my.domain/relative/path", UriCombine.Join("http://www.my.domain/", "relative/path").ToString());
Assert.Equal("http://www.my.domain/absolute/path", UriCombine.Join("http://www.my.domain/something/other", "/absolute/path").ToString());

For more complex Uri manipulation, checkout the Furl project.

JoinNonEmpty

Assert.Equal("a, c , b", StringExt.JoinNonEmpty(", ", "a", null, "c ", string.Empty, "b"));
Assert.Equal("a,c ,b", StringExt.JoinNonEmpty(',', new[] { "a", null, string.Empty, "c ", "b" }));

Working with XmlDocument and XDocument

  • XDocument is recommended over the old XmlDocument

Serialize a object to a XDocument

XDocument doc = XDocumentFactory.CreateDocFromXmlSerializer(o);
Console.WriteLine(xmlDoc.ToString());

Serialize a object to a XmlDocument

XmlDocument doc = XmlDocumentFactory.Create(o);
Console.WriteLine(doc.OuterXml);

Convert XDocumentXmlDocument

var xmlDoc = XmlDocumentFactory.Create(o);
var xDoc = XDocumentFactory.CreateDocFromXmlSerializer(o);
Console.WriteLine(xmlDoc.ToXDocument().ToString());
Console.WriteLine(xDoc.ToXmlDocument().OuterXml);

Useful regex

  • latin characters with accent ^([a-zA-Z0-9]|[À-Ö]|[Ø-ö]|[ø-ǿ]|[Ȁ-ʯ]|[-ͯ ]|[Ḁ-ỿ])+$
  • latin characters with accent + cyrillique: ^([a-zA-Z0-9]|[À-Ö]|[Ø-ö]|[ø-ǿ]|[Ȁ-ʯ]|[-ͯ ]|[Ḁ-ỿ]|[\u0430-\u044f])+$

Tips: checkout also

  1. Bogus: If you want to generate nice fake data such as Person name, Email, Product...

  2. Humanizer: If you want to generate nice human readable string from strings, enums, dates, times, timespans, numbers and quantities...

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.
  • .NETStandard 2.1

    • No dependencies.
  • net5.0

    • No dependencies.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on ToolsPack.String:

Package Downloads
ToolsPack.Log4net

Config log4net with one line of code, and other useful helper to log codes benchmark (elapsed time of operations)

ToolsPack.Webservice

Various helper for SOAP Webservices. See test codes for more information

ToolsPack.Samba

Wrapping native Windows call to connect to a Samba 1.0 (CIFS) server

ToolsPack.Logging

Micro-benchmark logger: add elapsed time of operations to the log messages, MockLogger

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.1.1 136 4/3/2024
3.1.0 777 2/8/2024
3.0.3 145 2/8/2024
3.0.2 1,593 11/27/2022
3.0.1 1,413 7/31/2022
3.0.0 969 7/5/2022
2.1.1 806 1/16/2022
2.1.0 10,308 5/14/2020
2.0.12 393 5/8/2020
2.0.11 431 4/30/2020
2.0.10 510 4/28/2020
2.0.9 404 4/19/2020
2.0.8 850 4/13/2020
2.0.7 526 4/12/2020
2.0.6 628 4/10/2020
2.0.4 427 4/9/2020
2.0.3 549 4/5/2020
2.0.2 688 4/4/2020
2.0.0 454 12/20/2019