DX.Utils 26.1.3.42

dotnet add package DX.Utils --version 26.1.3.42
                    
NuGet\Install-Package DX.Utils -Version 26.1.3.42
                    
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="DX.Utils" Version="26.1.3.42" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DX.Utils" Version="26.1.3.42" />
                    
Directory.Packages.props
<PackageReference Include="DX.Utils" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DX.Utils --version 26.1.3.42
                    
#r "nuget: DX.Utils, 26.1.3.42"
                    
#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.
#:package DX.Utils@26.1.3.42
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DX.Utils&version=26.1.3.42
                    
Install as a Cake Addin
#tool nuget:?package=DX.Utils&version=26.1.3.42
                    
Install as a Cake Tool

DX.Utils

General-purpose C# helper classes and extension methods used throughout the DXWeb package family. No DevExpress dependency — this package is plain .NET and can be used standalone in any project.

Target frameworks: net462, net8.0, net9.0, net10.0

Behaviour changes in 26.1.3.41

  • PropertyExtensions works on public properties only (private ones are ignored), skips indexers, and Assign skips destination properties that cannot be written.
  • AsQueryParameters URL-encodes values once (they were encoded twice); AppendQueryParameters keeps the existing query string.
  • StripHTMLTags keeps escaped markup (&lt;b&gt;) and plain & text as text, removes multi-line <head> sections and turns &nbsp; into a space.
  • DetermineMimeType / GetMimeType fall back to the file extension (lookup by name, extension and Uri did not work before).
  • GetConfigOption / ToDictionary with duplicate keys return the last value instead of throwing.
  • Attributes.GetTypesWith caches its results per attribute type and scans only assemblies loaded since the previous call, so plugins and lazy-loaded assemblies are still found.
  • RequiredIf's default message reads "The X field is required." and the result carries the member name; DateMin/DateMax keep DateTimeKind; Log timestamps use a 24-hour clock.
  • Fixed crashes: Collection.Clear() and the IList indexer setter (StackOverflow), Bits.Clear (always returned 0), EnumExtensions.GetDisplay for [Display(Name)] without a resource type, undefined values and flag combinations.

Install

dotnet add package DX.Utils

What's in the box

Attributes.cs — reflection over attributes

public static class Attributes
{
    public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit = false) where TAttribute : Attribute;
    public static TResult? GetAttributeData<TAttribute, TResult>(MemberInfo member, Func<TAttribute, TResult> selector) where TAttribute : Attribute;
}

GetTypesWith<TAttribute>() scans loaded assemblies for every type decorated with TAttribute. GetAttributeData pulls a single value off a member's attribute without you having to null-check GetCustomAttribute yourself.

Also included: RequiredIfAttribute, a ValidationAttribute that makes a property required only when another named property equals a given value (compiled only for non-.NET-Framework TFMs).

Bits.cs — bit-flag helpers

public static class Bits
{
    public static int BitSet(int value, int bit);
    public static int BitClear(int value, int bit);
    public static int BitToggle(int value, int bit);
    public static bool BitHas(int value, int bit);
}

Plus the same four operations as extension methods on int (BitsExtensions), so myFlags.BitHas(4) reads naturally at call sites. Used internally by DX.Data.Xpo.Identity for its legacy loading-flags scheme.

Collection.cs — typed collection base classes

CollectionItem, BaseCollection, and generic Collection<TItemClass> — an old-style strongly-typed collection base (pre-List<T>/ObservableCollection<T> era) kept for backward compatibility with consumers that still derive from it.

Conversion.cs — safe parsing & config helpers

public static class Utils
{
    public static T Iif<T>(bool condition, T trueValue, T falseValue);
}
public static class ListExtensions
{
    public static void RemoveAll<T>(this IList<T> list, Action<T> beforeRemove);
}
public static class Conversion
{
    public static int ParseInt(object value, int defaultValue = 0);
    public static double ParseDouble(object value, double defaultValue = 0);
    public static decimal ParseDecimal(object value, decimal defaultValue = 0);
    public static bool ParseBool(object value, bool defaultValue = false);
    public static TEnum ParseEnum<TEnum>(object value, TEnum defaultValue) where TEnum : struct;
    public static TEnum ParseEnum<TEnum>(object value, TEnum defaultValue, bool definedOnly, bool ignoreCase = false) where TEnum : struct;
    public static bool IsDefinedEnumValue<TEnum>(TEnum value) where TEnum : struct;
    public static string GetConfigOption(string key, string defaultValue = "");
    public static T MinValue<T>(T a, T b);
    public static T MaxValue<T>(T a, T b);
}

All the Parse* methods swallow format/overflow exceptions and fall back to defaultValue — handy for reading loosely-typed data (query strings, DataRow cells, config values) without wrapping every call in a try/catch.

ParseEnum(value, defaultValue) follows Enum.TryParse: it is case-sensitive and accepts any number, so "99" gives (TEnum)99 even if the enum has no such member. Pass definedOnly: true to get defaultValue for undefined values instead; a [Flags] enum accepts any combination of its flags ("Read, Write", "3"). ignoreCase: true matches member names case-insensitively.

CronJobs — a self-contained cron scheduler

public class CronExpression // 5-field: minutes hours days months daysOfWeek
{
    public CronExpression();                                                            // "* * * * *"
    public CronExpression(string minutes, string hours, string days, string months, string daysOfWeek);
}

public static class CronBuilder // fluent-ish factories for common CronExpressions
{
    public static CronExpression CreateMinutelyTrigger();
    public static CronExpression CreateHourlyTrigger(int triggerMinute = 0);
    public static CronExpression CreateDailyTrigger(int triggerHour = 0);
    public static CronExpression CreateDailyOnlyWeekDayTrigger(int triggerHour = 0);
    public static CronExpression CreateDailyOnlyWeekEndTrigger(int triggerHour = 0);
    public static CronExpression CreateMonthlyTrigger(int triggerDay = 0);
    public static CronExpression CreateYearlyTrigger(int triggerMonth = 0);
    // ... plus range/interval/multi-value overloads of each
}

public class CronSchedule // computes occurrences for one parsed CronExpression
{
    public static CronSchedule Parse(string cronExpression);           // "0 12 * * *"
    public static CronSchedule Parse(string minutes, string hours, string days, string months, string daysOfWeek);
    public static CronSchedule Create(CronExpression cronExpression);

    public bool GetNext(DateTime start, out DateTime next);
    public bool GetNext(DateTime start, DateTime end, out DateTime next);
    public List<DateTime> GetAll(DateTime start, DateTime end);
}

public class CronObject // runs one job's own wait/fire loop against one or more CronSchedules
{
    public CronObject(CronObjectDataContext cronObjectDataContext);

    public bool Start();
    public bool Stop();

    public bool IsStarted { get; }
    public bool IsExecuting { get; }
    public bool TriggerOnApplicationStart { get; set; } // fire once immediately on Start(), in addition to the schedule

    public event CronEvent OnCronTrigger; // the job fired - do the work here
    public event CronEvent OnStarted;
    public event CronEvent OnStopped;
    public event CronEvent OnThreadAbort;      // Stop() gave up waiting for a still-running handler
    public event CronErrorEvent OnError;       // an OnCronTrigger handler threw; the loop keeps running
}

CronExpression is a 5-field expression (no seconds, no year) - minutes hours days months daysOfWeek - supporting *, single values, a-b ranges, a,b,c lists, and /n intervals (eg. "*/15 8-18 * * 1-5" = every 15 minutes, 8am-6pm, Monday-Friday). CronSchedule parses one expression and answers "what's the next matching DateTime after X" - minute resolution, no seconds. CronObject wraps one or more CronSchedules plus an OnCronTrigger handler into a self-driving background loop (Task-based, cancellation-token cooperative - no Thread.Abort): Start() begins waiting for the next occurrence and firing on it, Stop() cancels the wait and waits up to 5s for an in-flight handler to finish. A handler that throws is caught, logged via Log.Exception, and raised on OnError - it does not kill the job's loop, so one bad firing only skips that firing.

For a single long-lived job you can use CronObject directly:

var schedule = CronSchedule.Create(CronBuilder.CreateDailyOnlyWeekDayTrigger(9)); // 9am, Mon-Fri
var context = new CronObjectDataContext("daily-report", dataContext: null, schedule);
var job = new CronObject(context);
job.OnCronTrigger += _ => SendDailyReport();
job.Start();
// ... later: job.Stop();
CronJobService — a runtime job registry
public sealed class CronJobService : IDisposable
{
    public static CronJobService Default { get; } // process-wide singleton, no DI required

    public CronObject AddJob(string jobId, string cronExpression, Action<CronObject> onTrigger, bool startImmediately = true, bool triggerOnRegister = false);
    public CronObject AddJob(string jobId, CronExpression cronExpression, Action<CronObject> onTrigger, bool startImmediately = true, bool triggerOnRegister = false);
    public CronObject AddJob(string jobId, Action<CronObject> onTrigger, bool startImmediately, bool triggerOnRegister, params CronSchedule[] schedules);

    public bool RemoveJob(string jobId);
    public bool TryGetJob(string jobId, out CronObject job);
    public bool StartJob(string jobId);
    public bool StopJob(string jobId);
    public void StartAll();
    public void StopAll();

    public IReadOnlyCollection<string> JobIds { get; }
    public int Count { get; }
    public event CronJobErrorEvent OnJobError; // fan-in of every registered job's OnError
}

CronJobService is a thread-safe registry over CronObject for adding and removing jobs by id at runtime, instead of wiring each CronObject up by hand and keeping track of the instances yourself. Job ids are case-insensitive and unique - registering a duplicate id throws InvalidOperationException.

Without DI, use the process-wide singleton:

CronJobService.Default.AddJob("cleanup-temp-files", "0 3 * * *", _ => CleanupTempFiles());
CronJobService.Default.AddJob("send-reminders", CronBuilder.CreateHourlyTrigger(), _ => SendReminders());
...
CronJobService.Default.RemoveJob("send-reminders");

With DI (ASP.NET Core / generic host, non-.NET-Framework targets only), register it as a singleton and inject it:

services.AddCronJobService(); // Microsoft.Extensions.DependencyInjection

// elsewhere, injected as CronJobService:
cronJobService.AddJob("cleanup-temp-files", "0 3 * * *", _ => CleanupTempFiles());

Dispose() (or process shutdown, if you call it from your host's shutdown hook) stops and forgets every registered job.

DateTimeExtensions.cs

public static DateTime DateMin(this DateTime a, DateTime b);
public static DateTime DateMax(this DateTime a, DateTime b);

EnumExtensions.cs — DisplayAttribute-aware enum labels

public static string GetDisplay(this Enum value);
public static IEnumerable<(TEnumType Value, string Display)> GetDisplayValues<TEnumType>() where TEnumType : struct, Enum;

Reads [Display(Name = "...", ResourceType = ...)] off enum members (falling back to the raw member name), so you can bind enums to dropdowns/grids with human-readable, localizable labels in one call.

ExceptionExtensions.cs

public static Exception GetInnerException(this Exception ex);

Walks InnerException all the way down and returns the innermost exception — useful when surfacing the real error message from a wrapped AggregateException/TargetInvocationException.

GeoHaversine.cs — great-circle distance

public enum GeoScale { KM, Mtr, Mile }
public static double Haversine(double lat1, double lon1, double lat2, double lon2, GeoScale scale = GeoScale.KM);
public static double Distance(double lat1, double lon1, double lat2, double lon2);
public static double DistanceKM(double lat1, double lon1, double lat2, double lon2);
public static double DistanceMtr(double lat1, double lon1, double lat2, double lon2);
public static double DistanceMile(double lat1, double lon1, double lat2, double lon2);

Log.cs — minimal thread-static logger

public static class Log
{
    public static void Exception(Exception ex);
    public static void Write(string message);
    public static string GetLog();
    public static void ClearLog();
}

Backed by UtilsConfig.LoggerType (read from the DXWeb/Utils config section) so the logging target can be swapped without code changes.

MimeDetection — content-based MIME type detection

public static class MimeTypes
{
    public const string DEFAULT = "application/octet-stream";

    public static string DetermineMimeType(string fileName, byte[] fileBytes);
    public static MimeType GetMimeTypeFromBytes(string fileName, byte[] fileBytes);
}

public sealed class MimeType
{
    public string Name { get; }         // e.g. "image/png"
    public string PrimaryType { get; }  // e.g. "image"
    public string SubType { get; }      // e.g. "png"
}

Determines a file's real MIME type by sniffing its content (magic bytes) rather than trusting its extension or a browser-supplied Content-Type — useful when validating uploads that could be mislabeled or renamed to spoof a type.

byte[] bytes = File.ReadAllBytes(path);
string mime = MimeTypes.DetermineMimeType(fileName, bytes); // "" if undetermined

DetermineMimeType first checks the byte content against a table of known magic-byte signatures; if nothing matches it falls back to the file's extension. The signature table (mime-types.xml, embedded as a resource) and detection approach are ported from the Winista.Mime project (itself derived from Apache Tika's mime-info). sbyte[]-based overloads (GetMimeTypeFromSBytes, etc.) are also available for callers already working with signed bytes.

PropertyExtensions.cs — reflection-based object utilities

public static bool HasProperty(this object obj, string name);
public static T GetPropertyValue<T>(this object obj, string name);
public static void SetPropertyValue(this object obj, string name, object value);
public static bool IsCollectionProperty(this PropertyInfo property);
public static TDestination Assign<TSource, TDestination>(this TDestination destination, TSource source);
public static IDictionary<string, object> AsDictionary(this object source);
public static string AppendQueryParameters(this string url, object parameters);
public static string AsQueryParameters(this object source);

AppendQueryParameters/AsQueryParameters build a query string from an object's public properties via reflection — decorate a property with [AppendQueryIgnoreAttribute] to skip it, or [AppendQueryFormatAttribute("...")] to control how it's rendered. Assign is a shallow reflection-based property copier between two (possibly unrelated) types, used internally by several XPDataStore/EFDataStore implementations to refresh a model after a commit.

RegExLibrary.cs — precompiled regexes

Static, precompiled Regex fields: EmailParser, QueryStringParser, UrlParser, SEOSafe, SEOReplaceSpaces, and a handful of legacy ASP.NET URL-rewrite parsers.

Strings.cs — string helpers

public static class Strings
{
    public static string StripHTMLTags(string html);
    public static string Join(string separator, params string[] values); // skips null/empty entries
    public static string CopyMaxLength(string value, int maxLength);
    public static string InsureHtmlParagraph(string html);
    public static string HtmlColor(Color color);
    public static string FormatFileSize(long bytes);
    public static string RemoveDiacritics(string value);
    public static string MakeSEOSafe(string value);
    public static string MakeFileNameSEOSafe(string value);
}

UtilsConfig.cs

public sealed class UtilsConfig
{
    public static UtilsConfig Current { get; }
    public string LoggerType { get; }
}

Singleton that reads the DXWeb/Utils custom config section (app/web.config on Framework, or the matching config provider on .NET) to configure Log's backing logger type.

Notes

  • Urls.cs is compiled only under #if INC_URLS and is not part of the default build (legacy ASP.NET WebForms-era helpers).
  • This package has no DevExpress dependency and is version-bumped alongside the rest of the DXWeb release wave purely for consistency — you can safely pin it independently.

See the root README for the full package list and DevExpress version alignment notes.

Product Compatible and additional computed target framework versions.
.NET 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.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Framework net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on DX.Utils:

Package Downloads
DX.Data.Xpo

Several XPO Related Helper classes and abstract DX.Data.IDataStore implementation for use with XPO with FluentValidation and no Mapping logic

DX.Data.Xpo.Identity

XPO Based abstract storage provider for ASP.NET Identity

DX.Data.Xpo.Mvc

Several extension classes and methods on DevExpress MVC Controls, XPO and XPDataStore implementations. This package needs an active DevExpress ASP.NET license

DX.Data.EF

Abstract DX.Data.IDataStore implementation for use with EF with FluentValidation and no Mapping logic

DX.Data.Xpo.Interfaces

Package with Interface for DX.Data.XPO.Identity ASP.NET Identity

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.1.3.42 181 11/5/2026
26.1.3.41 254 11/4/2026
26.1.3.40 594 8/5/2026
26.1.3.39 163 8/3/2026
26.1.3.38 370 7/31/2026
26.1.3.37 378 7/14/2026
25.2.3.35 371 4/7/2026
24.2.3.34 1,116 12/13/2024
23.2.3.33 985 9/17/2024
23.2.3.32 400 9/17/2024
23.2.3.31 1,821 1/11/2024
20.1.8.26 535 12/19/2023
20.1.8.25 474 12/14/2023
20.1.8.24 3,139 1/4/2023
20.1.8.22 1,236 11/1/2022
20.1.8.20 1,510 8/3/2022
20.1.8.19 1,623 6/16/2022
20.1.7.19 2,462 12/20/2021
20.1.7.18 3,092 3/12/2021
20.1.7.17 632 3/12/2021
Loading failed

26.1.3.42: New Conversion.ParseEnum(value, defaultValue, definedOnly, ignoreCase = false) overload: with definedOnly, values the enum does not define return the default ([Flags] enums accept combinations of their flags). New Conversion.IsDefinedEnumValue(value). The existing ParseEnum overloads are unchanged.
26.1.3.41: Bug fixes found by a new unit test suite (DX.Utils.Tests). Fixed: Collection.Clear() and the IList indexer setter recursed into a StackOverflow, Dispose threw on a non-empty collection; Bits.Clear always returned 0 and Has(ref, flag, clear: false) wiped the value; MimeTypes.GetMimeTypes always returned null, so lookup by name/extension/Uri never worked; MimeType rejected '(' and validates the primary type; EnumExtensions.GetDisplay no longer throws for [Display(Name)] without ResourceType, undefined values or flag combinations; Attributes.GetAttributeData honours TAttribute and GetTypesWith is thread safe; RequiredIf has the right default message, sets MemberNames and its '_' fallback is no longer inverted; StripHTMLTags removes multi-line heads, turns &nbsp; into a space and keeps plain '&' text; CopyMaxLength, InsureHtmlParagraph, FormatFileSize (unit boundaries, long.MinValue) and MakeFileNameSEOSafe (names without an extension) fixed; GetConfigOption/ToDictionary no longer throw on duplicate keys; DateMin/DateMax keep DateTimeKind; GetRegExGroupValue returns the default for missing groups; Log uses a 24-hour clock and logs the exception type and message. Performance: StripHTMLTags is linear (100 KB: 1.2 s to 3 ms), MIME definitions are parsed once (about 400x faster), PropertyExtensions caches properties per type without a Task.Run per lookup, GetTypesWith caches its results and scans only assemblies loaded since the last call. Behaviour changes: PropertyExtensions ignores private properties, skips indexers and read-only destination properties; AsQueryParameters encodes values once; AppendQueryParameters keeps the existing query; StripHTMLTags keeps escaped markup (&lt;b&gt;) as text; DetermineMimeType/GetMimeType fall back to the file extension; GetConfigOption with duplicate keys returns the last value.
26.1.3.40: Ported CronJobs (CronExpression/CronBuilder/CronSchedule/CronObject) from .NET Framework to
net462/net8.0/net9.0/net10.0 (dropped the System.Web dependency, replaced Thread.Abort() with cooperative
cancellation). Added CronJobService, a thread-safe runtime job registry (CronJobService.Default singleton,
or services.AddCronJobService() for DI on non-Framework targets). CronObject.OnCronTrigger handlers that
throw are now caught, logged, and raised via the new OnError event instead of silently killing the job's
loop.
26.1.3.39: Added MimeDetection by content.
26.1.3.38: Added a README.md with technical documentation, now embedded in the package via PackageReadmeFile.
26.1.3.37: Fixed IDE1005, IDE0059 and CA1304/CA1307/CA1310/CA1805-class analyzer warnings in Conversion.cs
(simplified conditional delegate invocation, removed dead re-assignments in catch blocks, and made
ParseBool's string comparison culture- and comparison-explicit). No behavior change.
23.2.3.34: .NETv9 support
23.2.3.31: Data.DataStore plus Validator and Mapper have been moved and simplified into package DX.Data
BREAKING CHANGES:
Data classes moved to DX.Data package
DX.Data package refactored to use FluentValidation with simplyfied validation logic
20.1.8.25: Upgrade to .NET 8
20.1.8.24: static class renamed in Strings.cs
20.1.8.22: IsCollectionProperty extension method added to fix bug in DX.Data.Xpo
20.1.8.21: Upgrade from .NET Framework to 4.6.1 to 4.6.2
20.1.8.20: Fix
20.1.8.19: Small fix
20.1.7.19: .NET 6.0 upgrade
20.1.7.17: IDataStoreModel<TKey> not needed anymore on Models and DBModels. No ID property needed.
20.1.7.16: Validation results include eventType (inserting, Inserted etc), Exception helper class for results, smaller fixes
20.1.3.15: Upgrade to DX v20.1.3
20.1.2.14-pre-20064: Upgrade to DX v20.1.2-pre-20064 and .NET preview 5
1.0.0.14: BREAKING CHANGE: Signature-change on IDataValidator<..>.Deleting(..):
       Was: Deleting(TKey id, object arg, IDataValidationResults<TKey> validationResults);
   Is:  Deleting(TKey id, IDataValidationResults<TKey> validationResults, params object[] args);
1.0.0.13: ListExtensions added
1.0.0.12: dotnet standard 2.1 for dotnet core v3.1 support
1.0.0.10: Small fixes and implementation of DataMapper and DataValidator
1.0.0.8: Small refactorings to improve speed and support for Pageable (XP)DataStore
1.0.0.7: Abstract Generic DTO DataStore and Validator classes added
1.0.0.6: Changed .NET Framework to v4.6.1
1.0.0.5: Initial dual mode package for .NET Framework and .NET Standard 2.0
Some features don't work yet on .NET Standard 2.0