DpUtilities 3.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package DpUtilities --version 3.0.0                
NuGet\Install-Package DpUtilities -Version 3.0.0                
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="DpUtilities" Version="3.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DpUtilities --version 3.0.0                
#r "nuget: DpUtilities, 3.0.0"                
#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 DpUtilities as a Cake Addin
#addin nuget:?package=DpUtilities&version=3.0.0

// Install DpUtilities as a Cake Tool
#tool nuget:?package=DpUtilities&version=3.0.0                

DpUtilities Package

Contents

Introduction {#UtilIntro}

The DpUtilities library provides an eclectic selection of routines which I personally find useful. They are generally small or very small pieces of code. It seemed more convenient to keep them together in one library, rather than split into several.

The majority of the functionality is provided by methods of the static class DpUtilities. All of its public method names are prefixed with "Dp", to help to avoid name clashes. This should enable a static using statement to avoid the necessity of always providing the class name (and the "Dp" will give an indication of where the method originates):

    [global] using static DpUtilities.DpUtilities;

The exceptions to being contained within the DpUtilities static class are the structure DpStringKvp, providing a simple string Key/Value pair and DpAppArgs, a class to analyse command line arguments. To use these without prepending the namespace, you would use:

    [global] using DpUtilities;

String Extensions {#StringUtils}

String Extensions

Ordinal & Superscript Functions

DpIsAlphaNumeric - Determines whether the string contains only a/n characters {#DpIsAlphaNumeric}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpIsAlphaNumeric (this string name)

Returns true if the string only contains a/n characters a-z, A-Z, 0-9.

DpIsANStartingWithCapital - All chars a/n and starting with a capital?{#DpIsANStartingWithCapital}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpIsAlphaNumeric (this string name)

Returns true if the string starts with a capital alpha, followed by just a-z, A-Z, 0-9 (no spaces or '_').

DpIsAllDigits - True if the trimmed string contains only digits 0-9{#DpIsAllDigits}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpIsAllDigits (this string s)

Returns true if the string (ignoring leading and trailing white space) is not empty and contains only the digit characters '0' to '9'.

DpIsProperName - All chars a/n or '_' and starting with a capital?{#DpIsProperName}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpIsProperName (this string name)

Returns true if the string starts with a capital alpha, followed by just a-z, A-Z, 0-9 or '_' (no spaces).

DpIsProperNameWithSp - All chars a/n, '_' or space and starting with a capital?{#DpIsProperNameWithSp}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpIsProperNameWithSp (this string name)

Returns true if the string starts with a capital alpha, followed by a-z, A-Z, 0-9, space or '_'.

DpIsValidEmail - Is the string a valid email address?{#DpIsValidEmail}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpIsValidEmail (this string name)

Returns true if the string is a valid email address.

DpJumble - Jumble a string{#DpJumble}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static string DpJumble (this string name)

Returns the string, jumbled in random order.

DpStringToBool or DpToBool - Does the string represent a boolean value?{#DpToBool}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static bool DpStringToBool (this string name) public static bool DpToBool (this string name)

Returns true if the first character of the string is a 'T', 't', 'Y' or 'y'. Otherwise, returns false.

DpToChar - Returns the first char of a string{#DpToChar}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static char DpToChar (this string name)

Returns the first character of a trimmed string as a char. If the string is empty, returns a space character.

DpToUpperChar - Returns the first char of a string as upper case{#DpToUpperChar}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static char DpToUpperChar (this string name)

Returns the first character of a trimmed string as a char, converted to upper case. If the string is empty, returns a space character.

DpRemoveQuotes - Remove quotes from a string{#DpRemoveQuotes}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static string DpRemoveQuotes (this string value, QuoteType quoteType = QuoteType.Either)

public enum DpQuoteType { Single, Double, Either }

If the first and last characters of a string are the same quote type, returns the string without quotes. Otherwise, returns the string as received.

By default, either single or double quotes are removed. However, the second parameter of type QuoteType can specify one or the other.

Ordinal and Superscript Functions, Including Date

DpOrdinalForInt - Returns the ordinal suffix for an integer{#DpOrdinalForInt}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static string DpOrdinalForInt (int i)

Returns the appropriate ordinal suffix ('st', 'nd', 'rd', 'th') for an integer between 1 and 99.

DpOrdinalDate - Formats a date with ordinal days{#DpOrdinalDate}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static string DpOrdinalDate (DateTime date, string format)

Given a date and a format string containing either 'd~' or 'dd~', formats the day portion of the date as an ordinal. For example, `DpOrdinalDate (new DateTime (2024,4,1), "d~ MMM yy") would return '1st Apr 24'. Replacing 'd~' with 'dd~' would yield '01st Apr 24'.

DpSsOrdinalForInt - Returns a superscript ordinal suffix for an integer{#DpSsOrdinalForInt}

Namespace: DpUtilities Package: DpUtils Module: StringUtils

public static string DpSsOrdinalForInt (int i)

Returns the appropriate ordinal suffix ('st', 'nd', 'rd', 'th') for an integer between 1 and 99, as a superscripted unicode string.

DpToSS - Convert a character to its superscript equivalent{#DpToSS}

Namespace: DpUtilities Package: DpUtils Module: Superscript

public static char DpToSS (char c)

Converts an alphanumeric character to the equivalent unicode superscript character. Where a superscripted equivalent does not exist (eg 'q'), a space is returned. However, not all fonts will have all superscripted characters and odd-looking glyphs may appear.

DpToSS - Convert a string to its superscript equivalent

Namespace: DpUtilities Package: DpUtils Module: Superscript

public static string DpToSS (this string str)

Converts an alphanumeric string to the equivalent unicode superscript characters. Where a superscripted equivalent does not exist (eg 'q'), a space is returned. However, not all fonts will have all superscripted characters and odd-looking glyphs may appear.

<div style="page-break-after: always"> </div>

General Utilities {#GenUtils}

String Utilities

Environment Utilities

Async Utilities

Property Utilities

DpGetRandomString - Returns a random string of given length{#DpGetRandomString}

Namespace: DpUtilities Package: GenUtils Module: Utilities

public static string DpGetRandomString (int len, bool includeSymbols = false)

Returns a random string. If includeSymbols is false, the characters will all be a/n (A-Z, a-z, 0-9). Otherwise, if true, they may also include any of the characters !$%^&*+-=@#~<>?|.

DpJumble - Jumbles a string{#DpJumble}

Namespace: DpUtilities Package: GenUtils Module: Utilities

public static string DpJumble (string str)

Given a string str, returns a new string containing the same characters as in str but in a random order.

DpListToString - Converts a list of strings to a single comma-separated string{#DpListToString}

Namespace: DpUtilities Package: GenUtils Module: Utilities

public static string DpListToString (List<string> list, bool spaceAfterComma = true)

Converts a list of strings to a single string containing the values in the list. If spaceAfterComma is true (default), the items will be separated by a comma followed by a space. If false, the separator will just be a comma.

DpIsInArray - Searches for a match with an array item{#DpIsInArray}

Namespace: DpUtilities Package: GenUtils Module: Utilities

public static int DpIsInArray<T> (T[] array, Predicate<T> match)

Searches an array for the first item for which the predicate is true. Returns the index into the array of that item.

Environment Utilities

Introduction

Environment variables may hail from any of 3 sources: System, User and Process. The Process contains a combination of the System and User variables, plus any of its own. Paths are combined but otherwise, if a variable is specified in both System and User, User takes precedence.

The first DpGetEnvVariable overload below retrieves a variable from the Process set. The second provides the option of selecting from any of System, User or Process.

DpGetEnvVariable - Return the specified process environment variable{#DpGetEnvVariable}

Namespace: DpUtilities, Package: DpUtilities, Module: DpEnvironment

public static string DpGetEnvVariable (string name, string defValue="")

Returns the environment value corresponding to name from the project, or defValue if not found

DpGetEnvVariable - Return the specified environment variable of the given type

Namespace: DpUtilities, Package: DpUtilities, Module: DpEnvironment

public static string DpGetEnvVariable (string name, DpEnvVarType type, string defValue="")

public enum DpEnvVarTypes { Process = 0, User = 1, System = 2 }

Returns the environment value corresponding to name from the given environment variable store. If not found, defValue (an empty string, by default) is returned.

DpListEnvVars - Writes a list of Environment Variables{#DpListEnvVars}

Namespace: DpUtilities, Package: DpUtilities, Module: DpEnvironment

public static string DpGetEnvVars (string path=null)

Writes a list of environment variables of each type to a text file. If the path is null, it is written to c:\Temp\EnvVarListyyMMdd.txt, where yyMMdd represent the current date. If a path is provided but no file name (no extension) the file name as above is used.

Async Utilities

DpRunSync - Runs an asynchronous task synchronously (no return){#DpRunSync}

Namespace: DpUtilities, Package: DpUtilities, Module: Utilities

public static void DpRunSync (Func<Task> task)

Synchronously executes an asynchronous Task method which has a void return type. eg DpUtilities.RunSync (() => AsyncMethod ());

DpRunSync<T> - Runs an asynchronous task synchronously (return of type T){#DpRunSyncT}

Namespace: DpUtilities, Package: DpUtilities, Module: Utilities

public static T DpRunSync<T> (Func<Task<TResult>> task)

Synchronously executes an asynchronous Task<T> method which has a return type of T. eg T result = DpUtilities.RunSync (() ⇒ AsyncMethod<T> ());

Property Utilities

DpGetPropertyValue<T> - Return the specified property of an object{#DpGetPropertyValueT}

Namespace: DpUtilities Package: DpUtilities Module: Utilities

public static T DpGetPropertyValue<T> (object obj, string propName)

Returns the property named propName, of type T, from the object obj

DpGetStringProperty - Return the specified string property of an object{#DpGetStringProperty}

Namespace: DpUtilities Package: DpUtilities Module: Utilities

public static string DpGetStringProperty (object obj, string propName)

Returns the string property named propName from the object obj

<div style="page-break-after: always"> </div>

Colour Serialisation Functions {ColourUtils}

DpStringFromColour - Returns a string representation of the Color

Namespace: DpUtilities Package: DpUtils Module: ColourUtils

public static string DpStringFromColour (Color colour)

Returns a string containing the colour name, if a known named colour. Otherwise returns the ARGB representation in the format 'A:XX R:XX G:XX b:XX', where 'XX' is the hex value of each component.

DpColourFromString - Returns a Color value from the string representation

Namespace: DpUtilities Package: DpUtils Module: ColourUtils

public static string DpColourFromString (string colourStr)

Returns a colour equivalent to the string representation colourStr, created by DpStringFromColour. colourStr may be either the name of a known colour or the ARGB string representation created by DpStringFromColour.

<div style="page-break-after: always"> </div>

Utility Classes & Structures {#ClassUtils}

Time Class (DpTime) {#TimeClass}

Introduction

Namespace: DpUtilities Package: GenUtils Module: DpTime

DpTime is a class that mirrors the standard class TimeOnly but with less precision (hours, minutes & seconds only) and a slightly smaller footprint. For database storage, the value can be reduced to a 32-bit integer, whereas TimeOnly is, at best, a 64-bit 'ticks' value.

In memory, the values of hours (0 - 23), minutes (0 to 59) and seconds (0 to 59) are stored as three byte values. The encoded time, obtained from the integer property AsCode is simply obtained from the formula:

hours * 3600 + minutes * 60 + seconds.

Constructors

public DpTime ()

Default constructor that sets the instance to 00:00:00

public DpTime (int hr, int min, int sec)

public DpTime (int hr, int min)

Constructors which set the time explicitly to the given hours minutes and seconds (if seconds are not specified, they default to zero).

public DpTime (int code)

Constructor from an encoded time.

public DpTime (DateTime dt)

Constructor from an existing DateTime instance.

public DpTime (TimeOnly tOnly)

Constructor from an existing TimeOnly instance

public DpTime (DpTime dt)

Copy constructor from an existing DpTime instance.

Properties

public int Hour {get, set}

Gets or sets the hour element of the time.

public int Minute {get, set}

Gets or sets the minute element of the time.

public int Second {get, set}

Gets or sets the second element of the time.

public bool IsValid {get}

Returns true if the time value is valid.

public string HMS {get}

Returns the time value formatted as 'HH:MM:SS'.

public string HM {get}

Returns the time value formatted as 'HH:MM', ignoring any seconds.

public int AsCode {get}

Returns the time value as an encoded integer.

public DateTime AsDateTime {get}

Returns the time value as a DateTime instance, with date set to zeros.

public TimeOnly AsTimeOnly {get}

Returns the time value as a TimeOnly instance.

public int MinValue {get}

Returns the minimum value of the encoded time (zero = 00:00:00).

public int MaxValue {get}

Returns the maximum value of the encoded time (= 23:59:59).

Instance Methods

public DpTime Add (int hrs, int mins, int secs, out int surplusDays)

public DpTime Add (int hrs, int mins = 0, int secs = 0)

Returns a new DpTime containing the sum of the current instance plus the number of hours/minutes/seconds specified. The hours may be any value >= 0, whereas minutes and seconds must be in the range 0 to 59. If the addition causes the new value to tip over into one or more new days, the number of additional days is returned in surplusDays. The result of both overloads would be identical, except that any spans of midnight would not be reported in the second case.

public DpTime AddHours (int hrs, out int surplusDays)

public DpTime AddHours (int hrs)

The number of hours specified is added to the time value of the current instance and returned as a new DpTime. hrs may be positive or negative and any valid integer value. If the addition causes the value to span one or more days, the number of days (+ or -) is returned in surplusDays - if used.

public DpTime AddMinutes (int mins, out int surplusDays)

public DpTime AddMinutes (int mins)

The number of minutes specified is added to the time value of the current instance and returned as a new DpTime. mins may be positive or negative and any valid integer value. If the addition causes the value to span one or more days, the number of days (+ or -) is returned in surplusDays - if used.

public DpTime AddSeconds (int secs, out int surplusDays)

public DpTime AddSeconds (int secs)

The number of seconds specified is added to the time value of the current instance and returned as a new DpTime. secs may be positive or negative and any valid integer value. If the addition causes the value to span one or more days, the number of days (+ or -) is returned in surplusDays - if used.

public void FromDpTime (DpTime dt)

Sets the current instance to a copy of the given DpTime.

public void Deconstruct (out int hr, out int min, out int sec)

public void Deconstruct (out int hr, out int min)

Returns the elements of the time value, in the second case, ignoring seconds.

public bool IsBetween (DpTime start, DpTime end)

Returns true if the current instance is between, or equal to one of, the start and end times. If the start time is greater than the end time, it assumes that the range spans midnight and correctly places the current instance. If the start and end time are equal, returns false.

public string ToString ()

Override returns the value formatted as 'HH:MM:SS'.

public int GetHashCode ()

Returns the encoded value as a hash code.

Static Methods

public static bool TryParse (string str, out DpTime dt)

If str contains a valid formatted time value, returns true and the parsed value is available in dt. If parsing fails, false is returned and dt is set to the equivalent of '00:00:00'.

'public static DpTime Parse (string str)`

If str contains a valid formatted time value, returns its equivalent as a DpTime instance. If parsing fails, throws a FormatException.

public static DpTime FromCode (int code)

Returns a DpTime instance from the given encoded time.

public static DpTime FromDateTime (DateTime dt)

Returns a DpTime instance from the given DateTime.

public static DpTime FromTimeOnly (TimeOnly tOnly)

Returns a DpTime instance from the given TimeOnly.

public static int Encode (int hrs, int mins, int secs)

Returns the encoded value of the time represented by hrs/mins/secs.

public static DpTime Decode (int code)

Returns a DpTime instance equivalent to the given encoded value.

Operators

public override bool Equals (object? obj)

Returns true if obj is a DpTime and is exactly equal to the current instance.

public static operator == (DpTime left, DpTime right)

public static operator != (DpTime left, DpTime right)

Returns true if left and right represent the same time - otherwise false.

public static operator > (DpTime left, DpTime right)

public static operator < (DpTime left, DpTime right)

Returns true if the time represented by left is greater than/less than that represented by right - otherwise false.

public static operator >= (DpTime left, DpTime right)

public static operator <= (DpTime left, DpTime right)

Returns true if the time represented by left is greater than or equal to/less than or equal to that represented by right - otherwise false.

public static operator - (DpTime left, DpTime right)

Returns a TimeSpan instance representing the difference between left and right.

<div style="page-break-after: always"> </div>

Generic Multi-Property Classes {#DpPairEtc}

Classes Pair, StringPair, StringIntPair, Trio and Quartet

Introduction

Namespace: DpUtilities, Package: DpUtils, Module: PairEtc

DpPair, DpTrio and DpQuartet are classes to simply contain 1, 2 or 3 generic objects respectively. They simply act as convenient containers for transmission of a number of objects together. DpStringPair and DpStringIntPair provide shortcuts for common cases.

Classes

public class DpPair <T1, T2> public class DpStringPair () public class DpStringIntPair <> public class DpTrio <T1, T2, T3> public class DpQuartet <T1, T2, T3, T4>

Properties

public T1/string A {get; set;} public T1/string/int B {get; set;} public T1 C {get; set;} (Trio & Quartet only) public T1 D {get; set;} (Quartet only)

Public properties that can be set or retrieved.

Constructors

Default Constructors

public DpPair<T1, T2> () public DpStringPair () public DpStringIntPair () public DpTrio<T1, T2, T3> () public DpQuartet<T1, T2, T3, T4> ()

Sets the values of A, B, [C] & [D] to their defaults

Value Constructors

public DpPair<T1, T2> (T1 a, T2 b) public DpStringPair (string a, string b) public DpStringIntPair (string a, int b) public DpTrio<T1, T2, T3> (T1 a, T2 b, T3 c) public DpQuartet<T1, T2, T3, T4> (T1 a, T2 b, T3 c, T4 d)

The values of properties A, B, [C] & [D] are set to a, b, [c] & [d] respectively.

Copy Constructors

public DpPair<T1, T2> (Pair<T1, T2> sourcePair) public DpStringPair (StringPair sourceSPair) public DpStringIntPair (StringIntPair sourceSiPair) public DpTrio<T1, T2, T3> (Pair<T1, T2, T3> sourceTrio) public DpQuartet<T1, T2, T3, T4> (Pair<T1, T2, T3, T4> sourceQuartet)

The values from the source are (shallow) copied int the new instance.

Overrides

public override string ToString ()

A string is returned in the format: '[className]: ()'A.ToString()', 'B.ToString()' [, 'C.ToString()' [, 'D.ToString()']]) e.g. new DpTrio<int, int, int> (1, 2, 3).ToString() would yield "DpTrio: ('1', '2', '3')".

public override int GetHashCode ()

Returns the hash code of the object's ToString() value.

<div style="page-break-after: always"> </div>

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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on DpUtilities:

Package Downloads
DpChangeTracker

Enables the developer to track which controls are 'dirty'. Also provides the facilities to return all controls to their initial state (cancel changes) and to make the current state of controls the 'clean' state (eg after file save).

DpAppArgs

Organises windows program arguments into accesible key/value pairs.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.0.3 137 4/5/2024
3.0.2 95 4/5/2024
3.0.1 98 4/4/2024
3.0.0 99 4/2/2024
2.1.1.3 239 11/28/2023
2.1.1.2 136 11/27/2023
2.1.1.1 126 11/27/2023
2.1.1 124 11/27/2023
2.1.0 143 11/26/2023
2.0.0 134 11/20/2023
1.3.1 211 4/4/2023
1.3.0 201 4/4/2023
1.2.2 348 11/13/2022
1.2.1 332 11/12/2022
1.2.0 331 11/12/2022
1.1.0 333 11/11/2022
1.0.0 344 10/29/2022

V2.1
Further functions added
All public classes/method names prefixed with the letters "Dp" to help avoid clashes.
Comprehensive user documentation added.
V2.1.1
Updated to .Net 8
v2.1.1.x
Problems with .Net 8
2.1.2
Reset to .Net 7
2.1.3 Removed configuration, which was inconsistent with Blazor Wasm
Restored to .Net 8
3.0 Reduced to pure utilities with WinForms controls and Console specifics transferred to separate libraries.