Helpers
- Introduction
- Complete Example: Slug and Preview
- Available Methods
- Strings
- Arrays
- Numbers
- Nested Data
- Miscellaneous
- Application Paths
Complete Example: Slug and Preview
Create this dependency-free command in a Blog application:
// app/Commands/HelperDemo.cs
using DotBlaze;
using DotBlaze.Support;
namespace Blog.Commands;
public class HelperDemo : Command
{
public override string Signature => "demo:helpers";
public override Task<int> Handle()
{
var slug = Str.Slug("Hello World!");
var preview = Str.Limit("Hello world", 5);
if (slug != "hello-world" || preview != "Hello...")
throw new InvalidOperationException("Unexpected helper result.");
Line($"{slug}: {preview}");
return Task.FromResult(0);
}
}Run dotblaze demo:helpers; expected output: hello-world: Hello.... A slug is formatting, not uniqueness: add a unique database index and an application collision policy when using it as an identifier. Str.Limit returns text, not trusted HTML; render it with escaped Blade braces.
Introduction
DotBlaze includes static helpers modelled on Laravel's Str, Arr, and Number classes. These are plain utilities and work anywhere, including outside a request. The Once and application path functions use the active application's service scope.
The helpers live in the DotBlaze.Support namespace, which the template imports globally. Standalone functions such as Collect, DataGet, Retry, and BasePath come from DotBlaze.Support.Functions, imported with using static, so they can be called like global functions.
Available Methods
Strings: Str.Slug, Str.Limit, Str.Random, Str.Uuid, Str.OrderedUuid, Str.Ulid, Str.Of
More strings: Str.Snake / Camel / Studly / Kebab / Headline, Str.Before / After / Between, Str.Words, Str.Mask, Str.Plural / Singular
Arrays: Arr.Get, Arr.Set, Arr.Only, Arr.Dot, Arr.Undot, Arr.Wrap
More arrays: Arr.Has / HasAny, Arr.Except / Forget / Pull, Arr.Flatten / Pluck
Numbers: Number.Currency / Percentage / FileSize / Abbreviate
Nested data: DataGet / DataSet / DataForget
Miscellaneous: Abort, Collect, Report, Rescue, Url.Route, Request.WantsJson, Request.File
General utilities: Retry, Tap, Once, Blank / Filled
Paths: BasePath / AppPath / StoragePath / PublicPath / ResourcePath
Strings
Str.Slug()
Generates a URL-friendly slug using transliteration, lowercase letters and normalized separators. Punctuation is removed; whitespace becomes the separator. language: null preserves non-ASCII letters. The default dictionary expands @ to at; provide a dictionary to customize substitutions.
Str.Slug("Hello World!"); // "hello-world"
Str.Slug(" Café Crème "); // "cafe-creme"
Str.Slug("C# & .NET 10"); // "c-net-10"
Str.Slug("Hello World", '_'); // "hello_world"Str.Limit()
Truncates a string to the given display width (default 100) and appends an ending (default ...) when it was cut. Surrogate pairs remain intact. Pass preserveWords: true to avoid cutting the final word. Negative limits throw; zero returns only the ending for nonempty input.
Str.Limit("Hello world", 5); // "Hello..."
Str.Limit("Hello", 10); // "Hello"
Str.Limit("Hello world", 5, " >"); // "Hello >"Str.Random()
Generates a cryptographically secure random string of letters and digits. The default length is 16:
var token = Str.Random(32);Str.Uuid()
Generates a random (version 4) UUID string:
var id = Str.Uuid(); // "e3c2b7a0-..."Str.IsUuid(value) checks the format.
Str.OrderedUuid()
Generates a timestamp-first version 4 COMB UUID, matching Laravel's ordered UUID layout. The prefix stores time in 10-microsecond units. IDs within the same timestamp have random ordering; clock rollback can also affect ordering.
var ordered = Str.OrderedUuid();
var version7 = Str.Uuid7();
var dated = Str.Uuid7(DateTimeOffset.UtcNow);
Str.IsUuid(version7, version: 7); // trueMigration: OrderedUuid() previously returned UUID v7. Use Uuid7() to retain that format. Existing stored identifiers are not modified.
Str.Ulid()
Generates a ULID: 26 characters, time-ordered (milliseconds) with 80 random bits, and shorter than a UUID. Ids created in the same millisecond by one process keep increasing. Str.IsUlid(value) checks the format:
var id = Str.Ulid(); // "01JDZ3W6N8Q4XK7Y2R5T9V0BCE"Case Conversion
Case conversion recognises camel-case and acronym boundaries, treats punctuation and whitespace as word separators, and uses invariant casing:
Str.Snake("XMLHttpRequest"); // "xml_http_request"
Str.Camel("hello-world"); // "helloWorld"
Str.Studly("hello_world"); // "HelloWorld"
Str.Kebab("HelloWorld"); // "hello-world"
Str.Headline("hello_world"); // "Hello World"Str.Before(), Str.After(), and Str.Between()
Matching is ordinal and case-sensitive. Before / After use the first delimiter; BeforeLast / AfterLast use the last. Between applies After then BeforeLast; BetweenFirst applies After then Before. Each extraction leaves its input unchanged when its delimiter is missing or empty.
Migration: Between("[a][b]", "[", "]") now returns "a][b" like Laravel, rather than "a"; use BetweenFirst for the first pair. A missing closing delimiter now retains the text after the opening delimiter, e.g. Between("[open", "[", "]") returns "open".
Str.Before("name@example.test", "@"); // "name"
Str.After("a:b:c", ":"); // "b:c"
Str.Between("Hello [Ali]!", "[", "]"); // "Ali"Str.Words()
Limit whitespace-separated words, preserving the original spacing between retained words. The ending is appended only when words were removed. The default limit is 100; zero removes all words, and negative limits throw:
Str.Words("one two three", 2); // "one two..."
Str.Words("one two", 2); // "one two"
Str.Words("one two", 1, " >"); // "one >"Str.Mask()
Repeat the replacement string over a range of Unicode text elements, keeping emoji and combining characters intact. The index is zero-based; a negative index counts from the end. Omitting length masks to the end. Ranges are clipped to the string, and negative lengths throw:
Str.Mask("ali@example.test", "*", 1, 2); // "a**@example.test"
Str.Mask("123456789", "*", -4); // "12345****"Str.Plural() and Str.Singular()
Apply Humanizer's English inflection rules, including irregular and uncountable words, preserving casing. PluralStudly inflects the final word of a StudlyCase name. Counted(value, count) and Plural(value, count, prependCount: true) prefix the count formatted using the current culture. Counts 1 and -1 retain the singular.
Migration: this improves the public string helper only; database table naming rules are unchanged. Inflection and slug output can change for inputs the older simple rules did not handle.
Str.Plural("Category"); // "Categories"
Str.Plural("post", count: 1); // "post"
Str.Singular("posts"); // "post"Fluent Strings
Str.Of wraps a string in a Stringable, so you can chain operations, like Laravel's Str::of():
var slug = Str.Of(" New Title ").Trim().Lower().Replace(" ", "-").ToString(); // "new-title"Stringable is immutable. Transformations return another Stringable; Value, ToString() or implicit conversion to string return the text. Predicates return bool, measurements return numbers, and splitting/matching returns the existing Collection<T> type. A default Stringable behaves like an empty string; an explicitly null input throws.
var words = Str.Of("foo bar baz").Explode(" "); // Collection<string>: foo, bar, baz
var upper = words.Map(word => word.ToUpperInvariant());
var segments = Str.Of("one, two, three").Split(@"[\s,]+");
var formatted = Str.Of("hello").WhenStartsWith("h", s => s.Title()).Append("!");
var count = Str.Of("hello").Tap(s => Console.WriteLine(s.Value)).Pipe(s => s.Length());Explode(delimiter, limit) preserves empty segments. A positive limit retains the remainder in the final segment; a negative limit drops that many trailing segments; zero behaves as one. Empty delimiters throw. Split uses a .NET regular expression. Scan parses a format such as %[^.].%s into a Collection<object?>. It supports numeric conversions, scansets, widths, suppression (%*d), %n, literal %%, and positional fields (%2$s %1$d). Signed integers use long, unsigned integers ulong, and floating-point fields double; overflow throws. Widths and %n count UTF-16 units, not PHP bytes. Unmatched fields are null. Invalid formats, mixed/duplicate/gapped positions and unsupported C length modifiers throw rather than silently guessing.
String method reference
The following operations are available on static Str and fluent strings unless marked otherwise. Static transformation methods generally take the input string first. Regex matching uses Str.Match(pattern, value), Str.MatchAll(pattern, value), Str.IsMatch(pattern, value) and wildcard matching uses Str.Is(pattern, value); fluent versions only need the pattern.
| Group | Methods |
|---|---|
| Casing | Lower, Upper, Lcfirst, Ucfirst, Ucwords, Title, Apa, Initials, Camel, Studly, Snake, Kebab, Headline |
| Transliteration | Ascii, Transliterate, Slug |
| Extraction | Before, BeforeLast, After, AfterLast, Between, BetweenFirst, CharAt, Substr, Take, Excerpt, Limit, Words |
| Whitespace and boundaries | Trim, Ltrim, Rtrim, Squish, Deduplicate, ChopStart, ChopEnd, Start, Finish, Wrap, Unwrap |
| Replacement | Replace, ReplaceArray, ReplaceFirst, ReplaceLast, ReplaceStart, ReplaceEnd, ReplaceMatches, SubstrReplace, Swap, Remove |
| Formatting | PadLeft, PadRight, PadBoth, Repeat, Reverse, Mask, WordWrap |
| Inflection | Plural, PluralStudly, Singular, Counted |
| Search | Contains, ContainsAll, DoesntContain, StartsWith, EndsWith, DoesntStartWith, DoesntEndWith, Is, IsMatch |
| Validation | IsAscii, IsJson, IsUrl, IsUuid, IsUlid |
| Measurement | Length, Position, WordCount; static-only SubstrCount |
| Parsing | Match, MatchAll, Explode, Split, Ucsplit, Scan |
| Paths | Basename, Dirname, ClassBasename |
| Encoding/rendering | ToBase64, FromBase64, Markdown, InlineMarkdown, StripTags, Hash |
| Generators (static only) | Random, Password, Uuid, Uuid7, OrderedUuid, Ulid |
| Fluent only | Append, Prepend, NewLine, Exactly, IsEmpty, IsNotEmpty, IsBlank, IsNotBlank, Test, Pipe, Tap, Encrypt, Decrypt, ToHtmlString, ToUri |
Conditional fluent methods accept a transformation and optional fallback transformation:
When, WhenContains, WhenContainsAll, WhenStartsWith, WhenEndsWith, WhenDoesntStartWith, WhenDoesntEndWith, WhenEmpty, WhenNotEmpty, WhenExactly, WhenNotExactly, WhenIs, WhenIsAscii, WhenIsUlid, WhenIsUuid, WhenTest.
When accepts a boolean or Func<Stringable, bool>. Conditional callbacks return Stringable to keep a statically typed chain; use Tap for side effects. Pipe wraps string results back into Stringable for continued chaining, while Pipe<TResult> can change the result type.
Security and compatibility
- Regex patterns and replacement syntax are .NET, without PHP
/.../delimiters. User-supplied regex execution is time-bounded and can throwRegexMatchTimeoutException. Length, positions, substrings and padding count Unicode code points.Maskretains its existing grapheme-cluster behavior.Limitcounts display columns; Unicode width tables can differ from PHP/ICU versions.CharAt,PositionandExcerptreturnnullwhen not found.Matchreturns an empty string when unmatched.Excerptis terminal, rather than returning another fluent string.- Markdown uses Markdig with raw HTML stripped and unsafe links disabled by default.
htmlInputacceptsstrip,escapeorallow; enable raw HTML/unsafe links only for trusted content.StripTagsis not an HTML sanitizer, especially with allowed tags.ToHtmlStringexplicitly bypasses Blade escaping and must only wrap trusted HTML. - Transliteration uses AnyAscii, with German language substitutions, rather than Laravel's language dictionaries/ICU. Results across languages and Unicode versions are not guaranteed identical. English inflection uses Humanizer; database naming stays unchanged.
IsUrluses .NET absolute URI validation, requires a host and://, and permits custom schemes unlessprotocolsrestricts them. Validation is not SSRF protection.ToUrireturnsSystem.Uriand accepts relative or absolute URIs.FromBase64requires valid Base64 containing UTF-8 text and throws for invalid input.Hashproduces a hex digest (default SHA-256), not a password hash; use the frameworkHash.Makefacade for passwords.Encrypt/Decryptuse DotBlazeCryptand require an active service scope and configured key. Payloads are not interoperable with Laravel encryption.Passworduses cryptographic randomness and includes each selected character category when the requested length permits. Enabling no categories or requesting a negative length throws.- This is the documented Laravel 13 method surface adapted to C#, not binary compatibility or a PHP runtime emulation. Existing compiled consumers should rebuild after upgrading optional-parameter signatures.
string title = Str.Of("user_categories").Headline().Singular(); // "User Category"Arrays
The Arr methods work on nested dictionaries (IDictionary<string, object?>), the closest .NET equivalent of PHP's associative arrays, using dot notation for nested keys.
var data = new Dictionary<string, object?>
{
["user"] = new Dictionary<string, object?>
{
["name"] = "Ali",
["address"] = new Dictionary<string, object?> { ["city"] = "Bandung" },
},
["active"] = true,
};Arr.Get()
Retrieves a value from a nested dictionary using dot notation. It returns the fallback when a key is missing or the value is not of type T:
Arr.Get(data, "user.address.city", "-"); // "Bandung"
Arr.Get(data, "user.address.zip", "-"); // "-"
Arr.Get<string>(data, "user.name"); // "Ali"Arr.Set()
Sets a value using dot notation, creating nested dictionaries as needed:
Arr.Set(data, "user.address.city", "Jakarta");Arr.Only()
Returns a new dictionary with only the given top-level keys. Missing keys are skipped:
var subset = Arr.Only(input, "name", "email");Arr.Dot()
Flattens a nested dictionary into a single level, with dot-notation keys:
var flat = Arr.Dot(data);
// ["user.name"] = "Ali", ["user.address.city"] = "Bandung", ["active"] = trueArr.Undot()
The reverse of Arr.Dot: expands dot-notation keys into nested dictionaries:
var nested = Arr.Undot(flat);
Arr.Get<string>(nested, "user.address.city"); // "Bandung"Arr.Wrap()
Wraps a value in a List<object?>. null becomes an empty list, a sequence becomes a list of its items, and a string or any other value becomes a one-item list:
Arr.Wrap(null); // []
Arr.Wrap("abc"); // ["abc"]
Arr.Wrap(new[] { 1, 2 }); // [1, 2]
Arr.Wrap(5); // [5]Arr.Has() and Arr.HasAny()
Check all or any of the supplied dot-notation keys. A present key with a null value still exists. Both methods return false for an empty key list:
Arr.Has(data, "user.name", "user.address.city"); // true
Arr.HasAny(data, "missing", "active"); // trueArr.Except(), Arr.Forget(), and Arr.Pull()
Except returns a shallow copy excluding top-level keys, matching Only's top-level selection. Forget removes dot-notation keys in place, ignoring missing paths. Pull<T> retrieves a value using Get's type/fallback rules and removes its key:
var publicInput = Arr.Except(input, "password", "token");
Arr.Forget(data, "user.address.city", "active");
var name = Arr.Pull(data, "user.name", "Guest");Arr.Flatten() and Arr.Pluck()
Flatten returns a List<object?> of values, discarding dictionary keys and recursively flattening collections. Strings and nulls stay intact. The optional depth limits how many nested collection levels are expanded; zero leaves the top-level values intact:
Arr.Flatten(new object?[] { new[] { 1, 2 }, new object?[] { 3, new[] { 4 } } });
// [1, 2, 3, 4]Pluck returns a List<object?> by reading a path from each item with DataGet, including objects and dictionaries. Missing values become null:
Arr.Pluck(new[] { new { User = new { Name = "Ali" } } }, "User.Name"); // ["Ali"]Numbers
Currency, Percentage, and Abbreviate use the current culture (normally the application's locale) unless locale is specified. Currency symbols and decimal places come from that locale. Percentage takes percentage points: 12.5 means 12.5%, not 1,250%.
Number.Currency(1234.5m, "en-US"); // "$1,234.50"
Number.Percentage(12.5m, 1, "en-US"); // "12.5%"
Number.FileSize(1536); // "1.5 KB"
Number.Abbreviate(1200, locale: "en-US"); // "1.2K"
Number.Abbreviate(-1200000, locale: "en-US"); // "-1.2M"FileSize accepts nonnegative byte counts and uses powers of 1024 with B through EB, invariant separators, and at most two decimal places by default. Abbreviate uses powers of 1000 with K, M, B, and T, and at most one decimal place by default. Both omit trailing zeroes and carry rounding into the next unit. Percentage defaults to zero decimal places. Their precision argument accepts 0 through 28.
Nested Data
DataGet, DataSet, and DataForget use case-sensitive dot paths through string-keyed dictionaries, public object properties and fields, and zero-based collection indices. * selects every dictionary value or collection item:
var data = new Dictionary<string, object?>
{
["users"] = new List<Dictionary<string, object?>>
{
new() { ["name"] = "Ali" },
new() { ["name"] = "Sari" },
},
};
DataGet(data, "users.0.name"); // "Ali"
DataGet(data, "users.*.name"); // List<object?>: ["Ali", "Sari"]
DataGet<string>(data, "users.9.name", "Guest"); // "Guest"
DataSet(data, "users.*.active", true);
DataSet(data, "settings.theme", "dark"); // creates nested dictionaries
DataSet(data, "settings.theme", "light", overwrite: false); // keeps "dark"
DataForget(data, "users.*.active", "settings.theme");DataGet returns the fallback for missing paths. A present null is returned as null by the untyped overload; the typed overload also falls back when the value is not of type T. A null path returns the whole target. Wildcards return lists; multiple wildcards collapse the intermediate lists, so teams.*.users.*.name returns one list of names. Reads also accept lazy IEnumerable sequences.
DataSet and DataForget mutate the supplied reference object. Missing dictionary branches are created by DataSet; initialise typed object members before traversing a null member. Values must match typed member/collection types. overwrite: false preserves existing values, including null. Mutation wildcards require dictionaries, IList collections, or arrays and visit existing items only; list/array indices must already exist.
DataForget ignores missing paths, removes dictionary entries and list items, and resets array slots and writable object members to their type's default. Removing list items shifts later indices. Read-only writes and invalid assignments throw rather than being silently ignored. Mutations are not transactional: earlier wildcard matches may already have changed if a later match throws.
Miscellaneous
Retry()
Retry a synchronous or asynchronous callback. times is the total number of attempts, including the first. The optional delay is in milliseconds; when limits which exceptions are retried. The final exception is rethrown unchanged. Cancellation exceptions are never retried:
var value = Retry(3, () => ReadValue(), sleepMilliseconds: 100);
var result = await Retry(3, () => FetchValueAsync(),
sleepMilliseconds: 100, when: error => error is IOException,
cancellationToken: token);Callbacks returning no value are supported through Action and Func<Task>. Async retries use Task.Delay and honour cancellation before attempts and during delays; pass the same token to the callback's I/O when it needs cancellation too. Synchronous delays block the calling thread. Attempt counts must be positive and delays nonnegative. HTTP and queue retries retain their own dedicated APIs.
Tap()
Run an action on a value and return the same value. Exceptions propagate:
var names = Tap(new List<string>(), list => list.Add("Ali"));Once()
Evaluate a callback once per explicit key and result type in the current HTTP request, job, or console command service scope:
var settings = Once("settings", () => LoadSettings());
var user = await Once("current-user", () => LoadUserAsync());Repeated calls in that scope reuse the first result, including nulls, tasks, and exceptions. Concurrent calls evaluate the callback only once. A new or nested ServiceScope.Run gets a fresh cache. Keys must be nonempty; use distinct keys for different inputs. Outside framework execution, wrap the work in ServiceScope.Run(services, ...).
Blank() and Filled()
Blank is true for null, whitespace-only strings, and empty collections or sequences. Zero and false are not blank. Filled is the inverse. Checking a lazy sequence advances and disposes one enumerator:
Blank(" \t"); // true
Blank(0); // false
Blank(false); // false
Filled("0"); // trueAbort()
Stops the request with an HTTP error, which is rendered by the exception handler. AbortIf and AbortUnless take a condition first:
Abort(404);
Abort(403, "You may not edit this post.");
AbortIf(!post.Published, 404);
AbortUnless(user.IsAdmin, 403);Collect()
Creates a collection from any sequence, like Laravel's collect() helper:
var names = Collect(users).Where(u => u.Active).Pluck(u => u.Name);Report()
Reports an exception through the exception handler (log, report callbacks) and carries on:
catch (PaymentException e)
{
await Report(e);
}Rescue()
Runs a callback and returns a fallback value if it throws. The exception is reported unless report: false is given:
var rate = await Rescue(() => ExchangeRates.Fetch("EUR"), fallback: 1.0m);Url.Route()
An extension method on MVC's IUrlHelper that generates the URL of a named route, like Laravel's route() helper. It throws if the route does not exist or a parameter is missing:
var url = Url.Route("posts.show", new { post = 1 }); // "/posts/1"In controllers, RedirectRoute("posts.show", new { post = post.Id }) redirects to a named route, and in views @Route("posts.index") prints its URL. See Routing.
Request.WantsJson()
An extension method on HttpRequest that returns true when the client asks for JSON (an Accept: application/json header, or X-Requested-With: XMLHttpRequest):
if (Request.WantsJson()) return Json(post);Request.File()
An extension method on HttpRequest that returns an uploaded file from the form, or null:
var avatar = Request.File("avatar");See File Storage for storing uploads.
Application Paths
Paths resolve from the active host's configured roots, regardless of the process's working directory. Call them inside a request, job, command, provider's Boot, or ServiceScope.Run:
BasePath(); // IHostEnvironment.ContentRootPath
BasePath("config/App.cs"); // <content-root>/config/App.cs
AppPath("Models"); // <content-root>/app/Models
StoragePath("logs"); // <content-root>/storage/logs
ResourcePath("views"); // <content-root>/resources/views
PublicPath("build"); // <web-root>/buildPublicPath uses IWebHostEnvironment.WebRootPath, falling back to <content-root>/wwwroot in a non-web host or when no web root is configured. The other directory helpers follow DotBlaze's app, storage, and resources conventions under the content root. Each accepts an optional relative path and uses System.IO.Path.Combine; it does not create directories.