📄 StringUtility.cs Documentation
Welcome to the comprehensive guide for IrbyImaging.Utility/StringUtility.cs! This static class provides a rich set of extension methods and helpers for handling strings, parsing dates/numbers, formatting phone numbers, exception‐flattening, and more. Whether you need safe trimming, numeric parsing, Base64 encoding, or advanced string slicing, StringUtility has you covered.
📑 Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Key Functional Areas
- Methods Overview
- Usage Examples
- Error Handling & Return Values
- UML Diagram
- Conclusion
🌟 1. Overview & Purpose
StringUtility is a static helper class in the IrbyImaging.Utility namespace that centralizes common string‑ and exception‑related operations:
- Safe operations (null‑checks, whitespace handling, trimming)
- Parsing (dates, numbers, decimals)
- Formatting (phone numbers, Base64, custom “Irby” decimal format)
- Utilities (exception flattening, ParallelOptions generation, splitting, padding)
🎯 Use Cases
- Sanitizing user inputs
- Flattening exception messages for logging
- Converting string payloads to typed data
- Formatting phone numbers and identifiers
🔗 2. Dependencies & Technologies
| Component |
Notes |
| .NET Standard / .NET Core |
Built‑in BCL: System, System.Text, System.Text.RegularExpressions, System.Threading.Tasks |
| Regular Expressions (Regex) |
Punctuation removal, GUID replacement, digit extraction |
| Tasks & Parallelism |
ParallelOptions helper to optimize CPU‑bound operations |
🔑 3. Key Functional Areas
🔥 Exception Handling Utilities
| Method |
Signature |
Description |
| ToFullMessage |
string ToFullMessage(this Exception) |
Flattens Exception and all InnerExceptions into one detailed message (stack traces, sources, target sites). |
🛠 String Conversion & Parsing
| Method |
Signature |
Description |
| ToBytes |
byte[] ToBytes(this string) |
Converts a string into a byte array (Unicode). |
| ToBase64string |
string ToBase64string(this string) |
Encodes a UTF‑8 string into Base64. |
| SplitInParts |
IEnumerable<string> SplitInParts(this string, int partLength) |
Splits a string into fixed‑length chunks. |
| ToUpperList |
List<string> ToUpperList(this List<string>) |
Converts all list entries to uppercase. |
| Method |
Signature |
Description |
| SafeTrim |
string SafeTrim(this string) |
Null‑safe Trim(). |
| SafeTrimAndStripPunctuation |
string SafeTrimAndStripPunctuation(this string) |
Removes punctuation via regex and trims. |
| SafeToUpper |
string SafeToUpper(this string) |
Trims, then converts to uppercase. |
| SafeTrimStart / SafeTrimEnd |
string SafeTrimStart(this string) |
Null‑safe TrimStart(). / TrimEnd(). |
| SafeSubstring |
string SafeSubstring(this string, int length) |
Safe truncation without exceptions. |
| SafeReplace |
string SafeReplace(this string, string find, string replace, bool treatFindAsCharArray) |
Null‑safe Replace(). |
| ReplaceGuid / ReplaceString |
string ReplaceGuid(string) / ReplaceString(string, find, replace) |
Regex heavy GUID replacement / basic replace. |
📊 Numeric & Date Parsing
| Method |
Signature |
Description |
| ToNullableInt |
int? ToNullableInt(this string) |
Parses integer or null if invalid. |
| ToNullableLong |
long? ToNullableLong(this string) |
Parses long or null if invalid. |
| ToNullableDec |
decimal? ToNullableDec(this string) |
Parses decimal or null if invalid. |
| ToImpliedNullableDec |
decimal? ToImpliedNullableDec(this string) |
Parses decimal, divides by 100 (implied cents). |
| FromDecToIrbyString |
string FromDecToIrbyString(this decimal, int sz) |
Converts decimal to zero‑padded integer string (×100). |
| ToNullableYear |
int? ToNullableYear(this string) |
Two‑ or four‑digit year mapping (threshold at current year). |
| ToDob50 |
DateTime? ToDob50(this string) |
Parses yyyyMMdd date or null on failure. |
| GetParallelOptions |
ParallelOptions GetParallelOptions() |
Suggests MaxDegreeOfParallelism = max(Environment.ProcessorCount/2,1). |
🎯 Padding & Substring Helpers
| Method |
Signature |
Description |
| PadLeft |
this int? / long? / string |
Left‑pad to a given width with a char. |
| AddIfNotExists |
string AddIfNotExists(this string, string add) |
Appends add if not already present. |
| Method |
Signature |
Description |
| FormatPhone |
string FormatPhone(this string) |
(123) 456-7890 styled if 10 digits. |
| ToPhoneFormatDashed |
string ToPhoneFormatDashed(this string) |
123-456-7890 dashed if 10 digits. |
| ToNumericOnly |
string ToNumericOnly(this string) |
Strips all non‑digit chars. |
| DigitsOnly |
string DigitsOnly(this string) |
Regex‑based digit extraction. |
| IsNumeric |
bool IsNumeric(this string) |
long.TryParse check on trimmed string. |
| IsAllZeros |
bool IsAllZeros(this string) |
True if only '0' characters present. |
✨ Miscellaneous Utilities
- IsValidString: Null/empty/whitespace check.
- ToUpperIgnoreNull: Uppercases only if not null.
📋 4. Methods Overview
| Method Name |
Category |
Return Type |
Throws? |
| ToFullMessage |
Exception Utilities |
string |
No |
| ToBytes |
Conversion |
byte[] |
No |
| SafeTrim |
Sanitization |
string |
No |
| … |
… |
… |
… |
| SplitInParts |
Miscellaneous |
IEnumerable<string> |
ArgEx / ArgNullEx |
Full table omitted for brevity – see in‑code XML documentation for every member.
💻 5. Usage Examples
using IrbyImaging.Utility;
// 1. Flatten an exception chain:
try {
// ... some code ...
} catch (Exception ex) {
string full = ex.ToFullMessage();
Console.WriteLine(full);
}
// 2. Safe trimming & uppercase:
string input = null;
string clean = input.SafeTrim().SafeToUpper(); // ""
// 3. Numeric parsing:
int? year = "22".ToNullableYear(); // 2022 (assuming threshold logic)
DateTime? dob = "19850715".ToDob50(); // 1985-07-15
// 4. Phone formatting:
string rawPhone = "(123)4567890";
string dashed = rawPhone.ToPhoneFormatDashed(); // "123-456-7890"
string styled = rawPhone.FormatPhone(); // "(123) 456-7890"
// 5. Base64 encode:
string token = "Hello!";
string b64 = token.ToBase64string(); // "SGVsbG8h"
// 6. Split into chunks:
foreach(var part in "ABCDEFG".SplitInParts(3))
Console.WriteLine(part); // "ABC","DEF","G"
⚠️ 6. Error Handling & Return Values
- Null Safety: Most methods guard against
null or empty strings and return string.Empty or null accordingly.
- Parse Failures: Numeric/date parse helpers return
null rather than throwing.
- Exceptions: Only
SplitInParts throws if arguments are invalid (ArgumentNullException / ArgumentException).
📈 7. UML Diagram
+--------------------------------------+
| <<static>> StringUtility |
+--------------------------------------+
| - digitsOnly: Regex |
+--------------------------------------+
| + ToFullMessage(e: Exception): string|
| + SafeTrim(s: string): string |
| + SafeToUpper(s: string): string |
| + ToNullableInt(s: string): int? |
| + ToDob50(s: string): DateTime? |
| + FormatPhone(s: string): string |
| + ToBase64string(s: string): string |
| + SplitInParts(s: string, len: int): IEnumerable<string> |
| ... |
+--------------------------------------+
🎉 8. Conclusion
StringUtility.cs is your go‑to library for robust, null‑safe string manipulation and parsing in the IrbyImaging ecosystem. It consolidates:
- Safe trimming, casing, and replacements
- Parsing logic for dates, numbers, decimals
- Formatting for phone numbers, Base64, and custom “Irby” formats
- Exception flattening for rich diagnostics
By leveraging these extension methods, you reduce boilerplate, avoid common pitfalls, and write cleaner, more maintainable code. Happy coding! 🚀