DpUtilities 2.1.1

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

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

DP Utilities Library

Contents

<h2 id="UtilIntro">Introduction</h3>

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;

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

<h2 id="StringUtils">String Extension Utilities</h3>

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

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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?

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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 '_').

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

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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?

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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?

Namespace: DpUtilities Package: DpUtilities Module: StringExts

public static bool DpIsValidEmail (this string name)

Returns true if the string is a valid email address.

DpJumble - Jumble a string

Namespace: DpUtilities Package: DpUtilities Module: StringExts

public static string DpJumble (this string name)

Returns the string, jumbled in random order.

DpStringToBool - Does the string represent a boolean value?

Namespace: DpUtilities Package: DpUtilities Module: StringExts

public static bool DpStringToBool (this string name)

Returns true if the string is a single character 'T', 't', 'Y' or 'y'.

DpToChar - Returns the first char of a string

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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

Namespace: DpUtilities Package: DpUtilities Module: StringExts

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

public enum QuoteType { 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.

DpToSS - Convert a character to its superscript equivalent

Namespace: DpUtilities Package: DpUtilities 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: DpUtilities Module: Superscript

public static string DpToSS (this string c)

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>

<h2 id="EnvironUtils">Environment Variables</h2>

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

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

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.

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

<h2 id="GenUtils">General Utilities</h2>

DpRunSync - Runs an asynchronous task synchronously (no return)

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)

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> ());

DpGetPropertyValue<T> - Return the specified property of an object

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

Namespace: DpUtilities Package: DpUtilities Module: Utilities

public static string DpGetStringProperty (object obj, string propName)

Returns the string property named propName from the object obj

DpGetRandomString - Returns a random string of given length

Namespace: DpUtilities Package: DpUtilities 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 !$%^&*+-=@#~<>?|.

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

Namespace: DpUtilities Package: DpUtilities 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

Namespace: DpUtilities Package: DpUtilities 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.

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

<h2 id="OrdUtils">Ordinals (Including Date)</h3>

DpOrdinalDate - Format a date, including ordinal days

Namespace: DpUtilities Package: DpUtilities Module: StringUtils

public static string DpOrdinalDate (DateTime date, string Format)

Formats a date in the standard way but adding new formatting placeholders. If a '~' symbol is placed immediately after the "d" or "dd" (but not "ddd" or "dddd") for the day, this will be replaced by the appropriate ordinal.

eg 31/12/2023 with a format of "d^ MMM yy" would produce "31st December 2023". If the date were 9/12/2023, it would produce "9th December 2023". In the second example, if the format were "dd^ MMM yy", the result would be "09th December 2023".

Similarly, if a '^' character were placed after the "d" or "dd", the ordinal would be superscripted. However beware that not all fonts will render superscripts correctly.

DpOrdinalForInt - Format a date, including ordinal days

Namespace: DpUtilities Package: DpUtilities Module: StringUtils

public static string DpOrdinalForInt (int num)

Returns the appropriate ordinal suffix corresponding to num (without num itself), where num is an integer between 1 and 99.

eg a num of 1 would yield "st", 12 would yield "th", 22 would yield "nd", 33 would yield "rd" and 44 or 99 "th".

If num is outside the range of 1 - 99, an empty string results.

DpSsOrdinalForInt - Format a date, including ordinal days

Namespace: DpUtilities Package: DpUtilities Module: StringUtils

public static string DpSsOrdinalForInt (int num)

Identical to DpOrdinalForInt above, except that the string would be returned in superscript. Beware that not all fonts will render superscript correctly.

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

<h2 id="ColourUtils">Colour Serialisation Class</h3>

Class ColourUtils - Provides serialisation and deserialisation of colours

Namespace: DpUtilities Package: DpUtilities Module: ColourUtils

A static class to facilitate the serialisation and deserialisation of colours. If the colour is a known standard colour, its name is used. Otherwise it is serialised in the format "A:xx R:xx G:xx B:xx".

Property DpDefaultColour

public bool DpDefaultColour { get; }

The default colour, representing a failure to interpret a string by method DpColourFromString.

DpStringFromColour - Create a string representing the colour

Namespace: DpUtilities Package: DpUtilities Module: ColourUtils

public static string DpStringFromColour (Color colour)

Returns a string containing either the colour name, if standard, or a representation of the colour in the format "A:xx R:xx G:xx B:xx" if not standard.

DpColourFromString - Convert a string representation to a colour

Namespace: DpUtilities Package: DpUtilities Module: ColourUtils

public static Color DpColourFromString (string cStr)

Returns the colour if the cStr contains either the standard colour name or a valid colour representation, otherwise returns the default colour. The calling routine should check whether the returned colour equals property DpDefaultColour as an indication that the string was invalid.

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

<h2 id="ConsoleUtils">Configuration for Console Applications</h3>

DpGetConfig - Get configuration in a console app

Namespace: DpUtilities Package: DpUtilities Module: StringUtils

public static IConfigurationRoot DpGetConfig (string settingsPath = "appSettings.json")

Provides access to environmental variables and (by default) an appsettings.json configuration file.

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

<h2 id="ClassUtils">Utility Classes and Structures</h3>

Structure DpStringKvp - Used to convey simple string/string pairs

Namespace: DpUtilities Package: DpUtilities Module: StringKvp

Property Key

public string Key { get; }

Represents the first (key) element of the pair.

Property Value

public string Key { get; }

Represents the second (value) element of the pair.

Default Constructor - Creates an empty structure

public DpStringKvp ()

Creates an empty structure.

Key/Value Constructor - Creates a structure with key and value

public DpStringKvp (string key, string value)

Creates an instance of the structure containing the given key and value.

Classes Pair<T1, T2>, StringPair and StringIntPair - Used to convey generic, string/string and string/int pairs

Namespace: DpUtilities Package: DpUtilities Module: Pair

Introduction

These three classes each hold a pair of values, respectively two values of any type, two strings and a string and an integer. The first value is named both A and Key - the names are interchangeable and refer to the same value in memory. Similarly the second property is named both B and Value - one being the alias for the other. The constructors and standard methods are identical except for types, so are not repeated. Dp_Pair is used to represent either DpPair, DpStringPair or DpStringIntPair.

Property Key / A

public T1 / string Key { get; }

Represents the first (key) element of the pair.

Property B / Value

public string Key { get; }

Represents the second (value) element of the pair.

Default Constructor - Creates an empty instance

public Dp__Pair ()

Creates an empty structure.

Key/Value Constructor - Creates an instance with key and value

public Dp__Pair (string a, string b)

Creates an instance of the class containing the given key and value.

Copy Constructor - Creates an instance copied from an existing instance

public Dp__Pair (Dp__Pair fromPr)

Creates an instance of the class with the key and value copied from an existing instance fromPr.

Copy Method

public Dp_Pair Copy (Dp__Pair fromPr)

Copies the key and value from fromPr into the current instance.

ToString Method - Returns a string representation of the method

public override string ToString ()

Returns a string in the format Dp_Pair: (A, B), where A and B are the values of the two properties, themselves as strings.

GetHashCode Method - Returns a hash code created from the ToString() value

public override string ToString ()

Returns an integer value resulting from hashing the ToString() value.

Equals Method - Returns true if both A and B match the comparator

public override bool Equals (object)

Returns true if object is of the appropriate Dp_Pair type and both A and B match the corresponding values in object as Dp_Pair.

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

<h2 id="AppArgUtils">Application Arguments Class</h3>

Class DpAppArgs - Processes application command-line arguments

Namespace: DpUtilities Package: DpUtilities Module: AppArgs

A class to process command line arguments into a list, together with convenience methods to find keys and values within the list.

The argument list is assumed to take the form: zero or more strings without a leading hyphen and not containing any '=' characters ("self-standing strings") Followed by: either [string]=[string] pairs ("key/value pairs") or -[string] elements ("hyphenated arguments"). Self-standing strings must come before any key/value pairs or hyphenated arguments. Thereafter, key/value pairs and hyphenated arguments may be mixed in any order.

The constructor processes these elements into a key/value list (type List<DpStringKvp>), retaining the input sequence. DpStringKvp simply has two string properties, Key and Value. The self-standing strings are formatted as Value with an empty Key. A hyphenated argument is entered as a Key with an empty Value. For key/value pairs, the characters preceding the sign are entered as the Key and those following, as the Value.

Keys may not contain spaces, as the spaces will be considered separators. Where values contain spaces, they must be enclosed in double-quotes (which will be removed). Keys are case-insensitive. Thus, for instance, -i and -I are not acceptable together on the command line.

If errors are found, the argument will be placed in a string array property ErrorList and the property HaveErrors set to true.

Constructor - Processes the arguments into a list

public DpAppArgs (string [] args)

args is the list of command line arguments, as passed to the main program.

Constructs the argument list and, if appropriate, the error list. The calling program should check property HaveErrors immediately after the instance has been constructed.

Property HaveErrors

public bool HaveErrors { get; }

Should be read immediately following construction to deal with any errors.

Property ErrorList

public string [] ErrorList { get; }

Returns a string array containing any arguments for which errors were detected. If none, null is returned.

Property ArgList

public List<DpStringKvp> ArgList { get; }

Returns a list of DpStringKvp instances (public string properties Key and Value) representing the individual arguments. Where errors were found, the Key is set to a ">" character and the problem argument is placed in the Value, where available.

Property LastValue

public string LastValue { get; }

Following a call to the HaveKey method, where the key is found, the value is placed in LastValue and may be read before any subsequent call to HaveKey. Where the Key was not found, LastKey is set to null.

HaveKey - Check whether the given key exists

public bool HaveKey (string key)

Returns true if the given key exists in the list of arguments. Keys are case-insensitive.

If found, property LastValue is set to the corresponding value and is available until HaveKey is called again. If not found, LastValue is set to null.

GetValue - Retieve the value for a key

public string GetValue (string key)

Returns the Value corresponding to the given Key, if found, otherwise returns null.

Product Compatible and additional computed target framework versions.
.NET net8.0-windows8.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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