This article gives a collection of simple and useful methods that you could write yourself, but now they are written for you to save time.
Introduction
JHelpers6
is a .NET 6 library component that can be used with any .NET 6 compatible project on any supported OS. It is a library of generally useful methods and functionality that can save a developer from writing code to accomplish these mundane tasks – or worse, have several versions of a method that do the same thing written in multiple places. JHelpers6
is used in my JDAC6 and JLogger6
NuGet packages for that very reason.
For the best examples of how to use the JHelpers6
library, please see the demo code referenced above. For the initial reader, I have included snippets of code from that demo project to give a small glimpse into how and why to use the various attributes of the library.
The component is found by searching NuGet for Jeff.Jones.JHelpers6
, or by going directly to https://www.nuget.org/packages/Jeff.Jones.JHelpers6/.
Background
I found, over time, as many developers do, there are certain helper functions and simple functionality that I used in multiple projects. Thus I incorporated them (rewritten from scratch so as not to use code written for, and owned by, others) into a library. I then "ate my own dog food" (so to speak) by using this library in two other NuGet projects.
CommonHelpers
is a static
class with static
methods and extensions.
ContextMgr
is a thread-safe singleton that can be used to store data in a single place accessible from anywhere, and any thread, in the application. One typical use is to store settings and other runtime values so their sources (file, database, etc.) only have to be read once. Anything that can be defined as a unique String
name and a value or reference type of any kind can be kept there. Values are added as a String
key name (which must be unique) and any value or reference type, boxed as a dynamic type.
ContextMgr
has no initialization, and as a singleton, does not use “new
” to be created. The actual instance is dynamically created on the first reference in the code.
Using the Code
ContextMgr Code Example
In this example, some name-value pairs are added to the ContextMgr
singleton. They can be accessed from any other code in the project. This gives you a place to store, edit, and retrieve values specified in one place in code (such as values read at startup).
Note the TryGetValue
method allows a graceful way to get a value and determine if the value existed.
Boolean retVal = false;
ContextMgr.Instance.ContextValues.Add("Computer Name", Environment.MachineName);
ContextMgr.Instance.ContextValues.Add("Startup Time", DateTime.Now);
IPAddress[] ips = Dns.GetHostAddresses("BubbaComputer");
ContextMgr.Instance.ContextValues.Add("IP Addresses", ips);
dynamic machineName = "";
retVal = ContextMgr.Instance.ContextValues.TryGetValue("Computer Name", out machineName);
dynamic startupTime = "";
retVal = ContextMgr.Instance.ContextValues.TryGetValue("Startup Time", out startupTime);
dynamic hostAddresses = null;
retVal = ContextMgr.Instance.ContextValues.TryGetValue("IP Addresses", out hostAddresses);
ContextMgr.Instance.Dispose();
CommonHelpers API
This is a static
class with a number of useful static
methods. Once the namespace is referenced, the extension methods will show in Intellisense.
Extension Methods
String GetFullExceptionMessage(this Exception ex2Examine,
Boolean getDataCollection,
Boolean getStackTrace)
Example
String result = exUnhandled.GetFullExceptionMessage(true, true);
txtResults.Text += $"Exception Message with data collection and stack trace:
{Environment.NewLine}{result}{Environment.NewLine}" + Environment.NewLine;
result = exUnhandled.GetFullExceptionMessage(true, false);
txtResults.Text += $"Exception Message with data collection and no stack trace:
{Environment.NewLine}{result}{Environment.NewLine}" + Environment.NewLine;
result = exUnhandled.GetFullExceptionMessage(false, true);
txtResults.Text += $"Exception Message with no data collection and with stack trace:
{Environment.NewLine}{result}{Environment.NewLine}" + Environment.NewLine;
result = exUnhandled.GetFullExceptionMessage(false, false);
txtResults.Text += $"Exception Message with no data collection and no stack trace:
{Environment.NewLine}{result}{Environment.NewLine}" + Environment.NewLine;
This Exception
object extension returns error messages from the parent exception and any exceptions down the stack, and optionally, the data collection. The Exception.Data
collection is used to store name-value pairs that typically record runtime values or other significant data for debugging.
Boolean Contains(this String source, String toCheck, StringComparison strComp)
Example
Gives the Contains method a way to do ignore or use case
String origString = "This is the original string.";
Boolean result1 = origString.Contains
("Original", StringComparison.CurrentCulture); // result1 = false
Boolean result2 = origString.Contains("Original",
StringComparison.CurrentCultureIgnoreCase); // result2 = true
This String
object extension allows string
comparison type on the string
to check. The extension method returns true
if the toCheck string
is in the source string
, false
if not.
Int32 ContainsHowMany(this String source, String toCheck, Boolean ignoreCase = false)
Example
String origString = "Having tea with the Team.";
Int32 result1 = origString.ContainsHowMany("tea", true);
Int32 result2 = origString.ContainsHowMany("tea");
This String
object extension gets the count of how many times a given string
occurs within another string
. The extension method returns a Count
of 0
to n
occurrences.
Boolean ConvertToBoolean(this String valueToExamine, out Boolean isBoolean)
Example
String origString = "trUe";
Boolean isBoolean = false;
Boolean result1 = origString.ConvertToBoolean(out isBoolean);
This String
object extension to convert a string
, assumed to be in a format that can be converted, to a Boolean value. Recognizes as true
(case insensitive) true, on, yes, up, ok, good, 1, -1
. Recognizes as false
(case insensitive): false, off, no, down, not ok, bad, 0
. If the conversion fails, false
is returned. Check the isBoolean
out value to see if the conversion detected a Boolean value. If it is false
, the value was not converted.
Boolean IsBoolean(this String valueToExamine)
Example
String origString = "trUe";
Boolean isBoolean = false;
Boolean result1 = origString.IsBoolean();
This String
object extension tests a string
, assumed to be in a format that can be converted, to a Boolean value. Recognizes as true
(case insensitive) true, on, yes, up, ok, good, start, 1, -1
. Recognizes as false
(case insensitive): false, off, no, down, not ok, bad, stop, 0
. If the conversion fails, false
is returned. Otherwise, true
is returned.
Boolean IsOnlyDigits(this String testString, Boolean includePeriod = false)
Example
String string2Check = "Nine.";
Boolean result = string2Check.IsOnlyDigits(false);
string2Check = "999.0";
result = string2Check.IsOnlyDigits(false);
string2Check = "999.0";
result = string2Check.IsOnlyDigits(true);
This String
object extension checks for all characters being digits. Conversion functions to test numbers may translate letters as Hex values. includePeriod
is set to true
if the one and only period is to be treated as being a number, so that decimal number string
s can be handled properly.
String GetOnlyDigits(this String testString, Boolean includePeriod = false)
Example
String value2Check = "Akery3mn.5n7X9.9c0";
String result = value2Check.GetOnlyDigits(false);
value2Check = "USD $2,332.45";
result = value2Check.GetOnlyDigits(true);
This String
object extension gets all digits in a string
and ignores any non-digits. If includePeriod
is true
, then the first period in the string
will be included in the results.
String GetOnlyLetters(this String testString, Boolean includeSpace = false)
Example
String value2Check = "Akery 3mn.5n7X9.9c0";
String result = value2Check.GetOnlyLetters(false);
String value2Check = "John Smith 999-99-9999";
String result = value2Check.GetOnlyLetters(true).Trim();
This String
object extension gets all letters in a string
and ignores any non-letters. However, if includeSpace
is true
, then any spaces found are included in the return value.
String GetOnlyLettersAndDigits(this String testString,
BooleanincludePeriodAndSpace = false)
Example
String value2Check = "##### ... WARNING ... 123 ... #######";
String result = value2Check.GetOnlyLetters(false);
String value2Check = "!@#$%^&*()+{}[]John Smith USD211.78";
String result = value2Check.GetOnlyLetters(true).Trim();
This String
object extension gets all letters and digits in a string
, and ignores all else, with the exception of periods and spaces when includePeriodAndSpace
is true
.
Boolean IsOnlyLetters(this String testString, Boolean includeSpace = false)
Example
String string2Check = "Nine hundred forty two";
Boolean result = string2Check.IsOnlyLetters(false);
result = string2Check.IsOnlyLetters(true);
This String
object extension checks for all characters being letters. If includeSpace
is true
, then spaces are accepted as if they were letters.
Boolean IsOnlyLettersAndOrDigits(this String testString,
Boolean includePeriodAndSpace = false)
Example
String string2Check = "Nine hundred forty two 942.00";
Boolean result = string2Check.IsOnlyLettersAndOrDigits(false);
string2Check = "999.0";
result = string2Check.IsOnlyLettersAndOrDigits(false);
string2Check = "999.0";
result = string2Check.IsOnlyLettersAndOrDigits(true);
string2Check = "Nine hundred forty two 942.00";
result = string2Check.IsOnlyLettersAndOrDigits(true);
This String
object extension checks for all characters being only letters and numbers. If includePeriodAndSpace
is true
, then all periods and spaces are treated as if they are letters.
Boolean IsEmailFormat(this String email)
Example
String test1 = "John.Doe@domain";
Boolean result = test1.IsEmailFormat();
test1 = "John.Doe@domain.net";
result = test1.IsEmailFormat();
test1 = "Mary Smith@domain.net";
result = test1.IsEmailFormat();
This String
object extension checks the string
to see if it is a valid email format. It does not check whether it is a valid, working email.
DateTime GetDateTime(this String dateString, DateTime dateDefault)
Example
String time2Check = "02/29/2004 13:03:14.234";
DateTime result = time2Check.GetDateTime(DateTime.MinValue);
time2Check = "02/29/2005 13:03:14.234";
result = time2Check.GetDateTime(DateTime.MinValue);
This String
object extension converts string
to date
, or returns the default value.
Decimal GetDecimal(this String numberString, Decimal decimalDefault)
Example
String number = "3.14159";
Decimal result = number.GetDecimal(0.0m);
number = "1x";
result = number.GetDecimal(0.0m);
This String
object extension converts string
to decimal value, or returns the default value.
Int32 GetInt32(this String numberString, Int32 integerDefault)
Example
String num = "23";
Int32 result = num.GetInt32(Int32.MinValue);
num = "1x";
result = num.GetInt32(Int32.MinValue);
This String
object extension converts string
to an Int32
value, or returns the default value.
Int64 GetInt64(this String numberString, Int64 integerDefault)
Example
String num = "23456";
Int64 result = num.GetInt64(Int64.MinValue);
num = "1x";
result = num.GetInt64(Int64.MinValue);
This String
object extension converts string
to an Int64
value, or returns the default value.
Object GetDefaultValue(this Type t)
Example
Type dec = typeof(Decimal);
dec.GetDefaultValue();
Object result = dec.GetDefaultValue();
Type dtm = typeof(DateTime);
result = dtm.GetDefaultValue();
Type bmp = typeof(System.Drawing.Bitmap);
result = bmp.GetDefaultValue();
Generic extension method that returns a default value for the type, if one exists. This is useful in generic instances where default<T>
may not work.
Helper Functions and Properties
Enum
DistanceUnitsOfMeasureEnum
Unassigned
Miles
Kilometers
Feet
Meters
This is used with geolocation to specify the units of measure for distance.
Class
AddressGeoData
Double Latitude1
Double Longitude1
Double Altitude1
Double Latitude2
Double Longitude2
Double Altitude2
Double LinearDistance (value is calculated, read-only)
DistanceUnitsOfMeasureEnum UnitsOfMeasure
Class Constructor
AddressGeoData(Double pLatitude1,
Double pLongitude1,
Double pAltitude1,
Double pLatitude2,
Double pLongitude2,
Double pAltitude2,
DistanceUnitsOfMeasureEnum pUnitsOfMeasure)
Class Methods
void SetUnitsOfMeasure(DistanceUnitsOfMeasureEnum lngUnitsOfMeasure)
Specify the units of measure to use during this class' instantiation.
void SetLinearDistance(Double dDistance)
This class is used to store two geolocations specifying the latitude, longitude, and altitude. The units of measure determine the units corresponding to the LinearDistance
value. Altitude may be 0
if not known or not wanted.
String RowDelimiter (Get only)
This value can be applied to the value for a constant. RowDelimiter
is the same non-printable ASCII character used in teletypes and other devices to indicate a new row, and not likely to be seen in string
data.
String ColumnDelimiter (Get only)
This value can be applied to the value for a constant. ColumnDelimiter
is the same non-printable ASCII character used in teletypes and other devices to indicate a new column, and not likely to be seen in string
data.
This code shows how a table of rows and columns can be built with unprintable delimiters using standard delimiters around since the beginning of line printers.
Useful for building tables that can accept field values with any printable character, especially those normally used as delimiters.
String TableDelimiter (Get only)
Example
String rowDelim = CommonHelpers.RowDelimiter;
String columnDelim = CommonHelpers.ColumnDelimiter;
String tblDelim = CommonHelpers.TableDelimiter;
StringBuilder sb = new StringBuilder();
sb.Append($"Winter{columnDelim}December{columnDelim}January
{columnDelim}February{rowDelim}");
sb.Append($"Spring{columnDelim}March{columnDelim}April{columnDelim}May{rowDelim}");
sb.Append($"Summer{columnDelim}June{columnDelim}July{columnDelim}August{rowDelim}");
sb.Append($"Fall{columnDelim}September{columnDelim}October
{columnDelim}November{rowDelim}{tblDelim}");
sb.Append($"FirstYears{columnDelim}2001{columnDelim}2002{columnDelim}2003{rowDelim}");
sb.Append($"SecondYears{columnDelim}2004{columnDelim}2005{columnDelim}2006{rowDelim}");
String twoTables = sb.ToString();
This value can be applied to the value for a constant. TableDelimiter
is the same non-printable ASCII character used in teletypes and other devices to indicate a new table of data, and not likely to be seen in string
data.
String FullComputerName (Get only)
Example
String result = CommonHelpers.FullComputerName;
Gets the full computer name that DNS will recognize in any domain.
String GetDNSName(String pComputerName = "")
Example
result = CommonHelpers.GetDNSName("13.249.120.102");
Gets the DNS host entry table name for a given computer name. Pass in any computer name. If left blank or null
, the current computer name will be used.
String CurDir (Get/Set)
Example
String result1 = CommonHelpers.CurDir;
CommonHelpers.CurDir = @"C:\";
String result2 = CommonHelpers.CurDir;
CommonHelpers.CurDir = result1;
Gets or sets the fully qualified path of the current working directory. For services, the current directory via normal means shows the Windows System32 directory because the service runs under an EXE located there. This property accounts for that by using one method call for running in the IDE, and another for running compiled.
Boolean AmIRunningInTheIDE (Get only)
Example
Boolean result = CommonHelpers.AmIRunningInTheIDE;
if (result)
{
txtResults.Text += "Running in the IDE";
}
else
{
txtResults.Text += "Running compiled";
}
This method will return true
if this project, or any project that calls this component as compiled code, is running under the IDE. This method returns false
if no IDE is being used.
Boolean IsInDomain()
Example
Boolean result = CommonHelpers.IsInDomain();
Returns true
if the computer running the code is in a domain. False
if it is not.
String GetComputerDomainName()
Example
String result = CommonHelpers.GetComputerDomainName();
Returns the Domain which the computer is joined to. Note: If user is logged in as local account, the domain of computer is still returned. Returns a String
with the domain name if it's joined, or an empty String
if it isn't.
String GetFullComputerDomainName()
Example
String result = CommonHelpers.GetFullComputerDomainName();
Returns the full domain name instead of the alias.
Boolean IsDaylightSavingsTime(DateTime dtmToTest)
Example
DateTime date2Check = "12/25/2020".GetDateTime(DateTime.MinValue);
result = CommonHelpers.IsDaylightSavingsTime(date2Check);
True
if the datetime
supplied falls within the period of Daylight Savings.
Boolean IsDaylightSavingsTime()
Example
Boolean result = CommonHelpers.IsDaylightSavingsTime();
True
if it is currently daylight savings time.
String CurrentTimeZoneDaylightName (Get only)
Example
String result1 = CommonHelpers.CurrentTimeZoneDaylightName;
Name of the current time zone for daylight savings.
String CurrentTimeZoneName (Get only)
Example
String result = CommonHelpers.CurrentTimeZoneDaylightName;
Name of the current time zone, regardless of daylight savings.
Int32 Asc(String strChar)
Example
Int32 result = CommonHelpers.Asc("T");
Same functionality as the VB6 ASC function - give it a character, get back the ASCIII decimal number.
String Hex(Int32 lngValue)
Example
String result = CommonHelpers.Hex(320);
Same as the VB6 function. Converts a 32 bit integer to a String hex
value.
Int32 GetCurrentCPUUsage()
Example
Int32 result = CommonHelpers.GetCurrentCPUUsage();
Gets the current % processor time.
Int32 AvailableRAMinMB()
Example
Int32 result = CommonHelpers.AvailableRAMinMB();
Returns available RAM MBs.
PingReply Ping(String strHostName, Int32 lngTimeout)
Example
PingReply result = CommonHelpers.Ping("www.microsoft.com", 1000);
PingReply result = CommonHelpers.Ping("23.55.228.170", 1000);
Pings the specified server synchronously. Returns a PingReply
instance indicating whether or not the operation was successful.
void GetLinearDistances(ref List<AddressGeoData> objAddressList)
Example
Double lat1 = 34.078717;
Double long1 = -84.2796787;
Double alt1 = (Double)CommonHelpers.ConvertMetersToFeet(1314);
Double lat2 = 30.8705832;
Double long2 = -84.2130001;
Double alt2 = (Double)CommonHelpers.ConvertMetersToFeet(350);
Double lat3 = 33.5867639;
Double long3 = -86.2874068;
Double alt3 = (Double)CommonHelpers.ConvertMetersToFeet(1322);
List<AddressGeoData> geoData = new List<AddressGeoData>()
{
new AddressGeoData(lat1, long1, alt1, lat2, long2, alt2,
DistanceUnitsOfMeasureEnum.Miles),
new AddressGeoData(lat3, long3, alt3, lat2, long2, alt2,
DistanceUnitsOfMeasureEnum.Miles)
}
CommonHelpers.GetLinearDistances(ref geoData);
List<AddressGeoData> geoData = new List<AddressGeoData>()
{
new AddressGeoData(lat1, long1, alt1, lat2, long2, alt2,
DistanceUnitsOfMeasureEnum.Kilometers),
new AddressGeoData(lat3, long3, alt3, lat2, long2, alt2,
DistanceUnitsOfMeasureEnum.Kilometers)
}
CommonHelpers.GetLinearDistances(ref geoData);
Results
The distance between 34.078717, -84.2796787, 4311.0236286 ft and 30.8705832,
-84.2130001, 1148.293965 ft is [333.26110261857286] miles.
The distance between 33.5867639, -86.2874068, 4337.2703478 ft and 30.8705832,
-84.2130001, 1148.293965 ft is [342.667119569297] miles.
The distance between 34.078717, -84.2796787, 1314 m and 30.8705832,
-84.2130001, 350 m is [212.70882559297874] kilometers.
The distance between 33.5867639, -86.2874068, 1322 m and 30.8705832,
-84.2130001, 350 m is [216.99218873575253] kilometers.
This function uses the Haversine formula to calculate linear distance between two sets of latitude and longitude, with an adjustment for the earth's radius based on the latitude. Haversine is used instead of Vincenty’s formula to keep the computation simpler and less processor intensive. This function takes a List of address geo data instances and processes them, updating the individual class instances in the List
for the linear distance property.
Double GetLinearDistance(double Latitude1,
double Longitude1,
double Altitude1,
double Latitude2,
double Longitude2,
double Altitude2,
DistanceUnitsOfMeasureEnum lngUnitsOfMeasure)
Example
Double lat1 = 34.078717;
Double long1 = -84.2796787;
Double alt1 = (Double)CommonHelpers.ConvertMetersToFeet(1314);
Double lat2 = 30.8705832;
Double long2 = -84.2130001;
Double alt2 = (Double)CommonHelpers.ConvertMetersToFeet(350);
Double result = CommonHelpers.GetLinearDistance(lat1, long1, alt1, lat2, long2,
alt2, DistanceUnitsOfMeasureEnum.Miles);
Double result = CommonHelpers.GetLinearDistance(lat1, long1, alt1, lat2, long2,
alt2, DistanceUnitsOfMeasureEnum.Kilometers);
Results
The distance between 34.078717, -84.2796787, 4311.0236286 ft and 30.8705832,
-84.2130001, 1148.293965 ft is [333.26110261857286] miles.
The distance between 34.078717, -84.2796787, 1314 m and 30.8705832, -84.2130001,
350 m is [212.70882559297874] kilometers.
This function uses the Haversine formula to calculate linear distance between two sets of latitude and longitude, with an adjustment for the earth's radius based on the latitude. Haversine is used instead of Vincenty’s formula to keep the computation simpler and less processor intensive. This overload allows the caller to specify what units of measure is desired for the return value.
Double GetLinearDistance(Double Latitude1,
Double Longitude1,
Double Altitude1,
Double Latitude2,
Double Longitude2,
Double Altitude2,
Boolean UseMiles)
Example
Double lat1 = 34.078717;
Double long1 = -84.2796787;
Double alt1 = (Double)CommonHelpers.ConvertMetersToFeet(1314);
Double lat2 = 30.8705832;
Double long2 = -84.2130001;
Double alt2 = (Double)CommonHelpers.ConvertMetersToFeet(350);
Double result = CommonHelpers.GetLinearDistance
(lat1, long1, alt1, lat2, long2, alt2, true);
Double result = CommonHelpers.GetLinearDistance
(lat1, long1, alt1, lat2, long2, alt2, false);
Results
The distance between 34.078717, -84.2796787, 4311.0236286 ft and 30.8705832,
-84.2130001, 1148.293965 ft is [333.26110261857286] miles.
The distance between 34.078717, -84.2796787, 1314 m and 30.8705832,
-84.2130001, 350 m is [212.70882559297874] kilometers.
This function uses the Haversine formula to calculate linear distance between two sets of latitude and longitude, with an adjustment for the earth's radius based on the latitude. Haversine is used instead of Vincenty’s formula to keep the computation simpler and less processor intensive. This overload allows the user to choose between miles and kilometers (UseMiles
param):
Double GetLinearDistance(Double Latitude1,
Double Longitude1,
Double Latitude2,
Double Longitude2,
DistanceUnitsOfMeasureEnum UnitsOfMeasure)
Example
Double lat1 = 34.078717;
Double long1 = -84.2796787;
Double lat2 = 30.8705832;
Double long2 = -84.2130001;
Double result = CommonHelpers.GetLinearDistance
(lat1, long1, lat2, long2, DistanceUnitsOfMeasureEnum.Miles);
Double result = CommonHelpers.GetLinearDistance
(lat1, long1, lat2, long2, DistanceUnitsOfMeasureEnum.Kilometers);
Results
The distance between 34.078717, -84.2796787, and 30.8705832,
-84.2130001 is [333.26110261857286] miles.
The distance between 34.078717, -84.2796787, and 30.8705832,
-84.2130001 is [212.70882559297874] kilometers.
This function uses the Haversine formula to calculate linear distance between two sets of latitude and longitude, but without providing altitude (all calculations assume linear over the curve of the earth at sea level) with an adjustment for the earth's radius based on the latitude. Haversine is used instead of Vincenty’s formula to keep the computation simpler and less processor intensive. This overload allows the user to choose what unit of measure.
Double RadianToDegree(Double Coordinate)
Example
Double result = CommonHelpers.RadianToDegree(1.5d);
Converts radians to degrees.
Double CelciusToFahrenheit(Double DegC)
Example
Double result = CommonHelpers.CelsiusToFahrenheit(25);
Converts Celsius to Fahrenheit.
Double FahrenheitToCelsius(Double DegF)
Example
Double result = CommonHelpers.FahrenheitToCelsius(77);
Converts Fahrenheit to Celsius.
String StringToBase64(String String2Convert)
Example
String orig = "I am a string";
String result = CommonHelpers.StringToBase64(orig);
Convert String
to Base64
.
String Base64ToString(String ByteString64)
Example
String base64 = "SSBhbSBhIHN0cmluZw==";
String result = CommonHelpers.Base64ToString(base64);
Convert Base64String
to String
.
List<ManagementObject> GetNetworkPrinters()
Example
List<System.Management.ManagementObject> result = CommonHelpers.GetNetworkPrinters();
foreach (System.Management.ManagementObject printer in result)
{
String printerName = printer.Properties["Name"].Value.ToString();
String printerStatus = printer.Properties["Status"].Value.ToString();
String printerDefault = printer.Properties["Default"].Value.ToString();
txtResults.Text += $"{printerName} status: [{printerStatus}]
Default? [{printerDefault}]" + Environment.NewLine;
}
Gets a list of network printers using one ManagementObject
instance per printer in a List
object.
void SetIntBitValue(ref Int32 intValue, Int32 bitPlaceValue, Boolean setBitOn)
Example
Int32 bitmask = 0;
Int32 previousBitmask = bitmask;
CommonHelpers.SetIntBitValue(ref bitmask, 1, true);
txtResults.Text += $"The number [0] bit 1 is set on, resulting in 1." +
Environment.NewLine;
previousBitmask = bitmask;
CommonHelpers.SetIntBitValue(ref bitmask, 2, true);
txtResults.Text += $"The number [1] bit 2 is set on, resulting in 3." +
Environment.NewLine;
previousBitmask = bitmask;
CommonHelpers.SetIntBitValue(ref bitmask, 1, false);
txtResults.Text += $"The number [3] bit 1 is set off,
resulting in 2." + Environment.NewLine;
Helper method to set bit value of an Int
on/off.
Boolean GetIntBitValue(Int32 intValue, Int32 bitPlaceValue)
Example
Int32 bitmask = 3;
Boolean result = CommonHelpers.GetIntBitValue(bitmask, 1);
txtResults.Text += $"The number [3] bit 1 is True." + Environment.NewLine;
result = CommonHelpers.GetIntBitValue(bitmask, 2);
txtResults.Text += $"The number [3] bit 2 is True." + Environment.NewLine;
result = CommonHelpers.GetIntBitValue(bitmask, 3);
txtResults.Text += $"The number [3] bit 3 is True." + Environment.NewLine;
result = CommonHelpers.GetIntBitValue(bitmask, 4);
txtResults.Text += $"The number [3] bit 4 is False.";
Helper method to get the state of a bit value of an Int
.
String GetStackInfo()
String GetStackInfo(Exception ex)
Example
String result = CommonHelpers.GetStackInfo();
txtResults.Text += $"The stack info from the current state is:
JHelpers_Demo.frmMain::GetStackInfo() @ Line [1587], Column [4]";
try
{
ArgumentException ex = new ArgumentException
("Parameter 1 (name) was null. It must be a string with length > 1.");
throw ex;
}
catch (Exception exUnhandled)
{
result = CommonHelpers.GetStackInfo(exUnhandled);
txtResults.Text += $"The stack info from the exception is:
JHelpers_Demo.frmMain::GetStackInfo() @ Line [1595], Column [5]";
}
This gets the module, function, line number, and column number info in a String
. This is useful when logging and creating exceptions to define exactly where something occurred.
The second overload gets the module, function, line number, and column number info in a String
based on an exception. This is useful when logging and creating exceptions to define exactly where something occurred.
String GetFullDateTimeStampForFileName(DateTime dtmDate)
Example
String result = CommonHelpers.GetFullDateTimeStampForFileName(DateTime.Now)
This returns a String
with a consistent datetime
format for a filename.
Boolean IsFileText(out Encoding lngEncoding, String strFileName,
Int32 lngNumCharactersToRead)
Example
Boolean result = CommonHelpers.IsFileText(out encodingType,
@"C:\TestFile.txt", 80);
result = CommonHelpers.IsFileText(out encodingType,
@"C:\Windows\regedit.exe", 80);
Detect if a file is text and detects the encoding.
Int32 GetTotalHDDFreeSpace(String pDriveName)
Example
Int32 result = CommonHelpers.GetTotalHDDFreeSpace("C");
Returns MB of free disk space.
Int32 GetTotalHDDSize(String pDriveName)
Example
Int32 result = CommonHelpers.GetTotalHDDSize("C");
Returns MB of total space.
Int32 GetMinPasswordLength()
Example
Int32 result = CommonHelpers.GetMinPasswordLength();
Returns the minimum password length from a domain, if one exists. If no domain exists, -1
is returned.
Boolean IsIPAddress(String pValue, out IPAddress pIPValue)
Example
String ipAddr4 = "23.55.228.170";
IPAddress ipAddr4IP = null;
String ipAddr6 = "2600:140b:12:4ba::356e";
IPAddress ipAddr6IP = null;
Boolean result = CommonHelpers.IsIPAddress(ipAddr4, out ipAddr4IP);
txtResults.Text += $"Is \"{ipAddr4}\" an IPv4 address? {result}" + Environment.NewLine;
if (ipAddr4IP != null)
{
txtResults.Text += $"\"{ipAddr4}\" resolved as {ipAddr4IP.ToString()},
address family {ipAddr4IP.AddressFamily.ToString()}" + Environment.NewLine +
Environment.NewLine;
}
result = CommonHelpers.IsIPAddress(ipAddr6, out ipAddr6IP);
txtResults.Text += $"Is \"{ipAddr6}\" an IPv6 address? {result}" + Environment.NewLine;
if (ipAddr6IP != null)
{
txtResults.Text += $"\"{ipAddr6}\" resolved as {ipAddr6IP.ToString()},
address family {ipAddr6IP.AddressFamily.ToString()}" +
Environment.NewLine + Environment.NewLine;
}
ipAddr4 = "390.400.987.0";
result = CommonHelpers.IsIPAddress(ipAddr4, out ipAddr4IP);
txtResults.Text += $"Is \"{ipAddr4}\" an IPv4 address? {result}" + Environment.NewLine;
if (ipAddr4IP != null)
{
txtResults.Text += $"\"{ipAddr4}\" resolved as {ipAddr4IP.ToString()},
address family {ipAddr4IP.AddressFamily.ToString()}" +
Environment.NewLine + Environment.NewLine;
}
ipAddr6 = "abc:def";
result = CommonHelpers.IsIPAddress(ipAddr6, out ipAddr6IP);
txtResults.Text += $"Is \"{ipAddr6}\" an IPv6 address? {result}" + Environment.NewLine;
if (ipAddr6IP != null)
{
txtResults.Text += $"\"{ipAddr6}\" resolved as {ipAddr6IP.ToString()},
address family {ipAddr6IP.AddressFamily.ToString()}" + Environment.NewLine;
}
Results
Is "23.55.228.170" an IPv4 address? True
"23.55.228.170" resolved as 23.55.228.170, address family InterNetwork
Is "2600:140b:12:4ba::356e" an IPv6 address? True
"2600:140b:12:4ba::356e" resolved as 2600:140b:12:4ba::356e, address family InterNetworkV6
Is "390.400.987.0" an IPv4 address? False
Is "abc:def" an IPv6 address? False
Checks to see if a string
is an IPv4 or IPv6 address, and returns an IPAddress
object as an out
parameter.
String AssemblyTitle (Get only)
Example
String result = CommonHelpers.AssemblyTitle;
Title of the .NET assembly.
String AssemblyVersion (Get only)
Example
String result = CommonHelpers.AssemblyVersion;
Version of the .NET assembly.
String AssemblyDescription (Get only)
Example
String result = CommonHelpers.AssemblyDescription;
Description of the .NET assembly.
String AssemblyProduct (Get only)
Example
String result = CommonHelpers.AssemblyProduct;
Product description of the .NET assembly.
String AssemblyCopyright (Get only)
Example
String result = CommonHelpers.AssemblyCopyright;
Copyright string
used by the .NET assembly.
String AssemblyCompany (Get only)
Example
String result = CommonHelpers.AssemblyCompany;
Company that owns the .NET assembly.
Boolean WriteToLog(String logFileName, String mainMessage, String secondMessage)
Example
Boolean result = CommonHelpers.WriteToLog(@"C:\Temp\TestFile.log",
"Main message to log", "Optional second message to log");
Results
The file [C:\Temp\TestFile.log] has these contents:
Date Time Message Addtl Info Module Method Line No.
2022-08-19T23:17:59.3811654-04:00 Main message to log Optional second message to log frmMain.cs Void WriteToLog() 2081
2022-08-19T23:18:00.3955869-04:00 Main message to log, entry 2 Optional second message to log frmMain.cs Void WriteToLog() 2083
2022-08-19T23:18:01.4112633-04:00 Main message to log, entry 3 Optional second message to log frmMain.cs Void WriteToLog() 2085
Method that performs a simple file-based log write where the file is tab delimited and has a column header line.
Points of Interest
I created a signed NuGet package for this and integrated it into my JLogger6
NuGet package,.
History
When | Who | What |
25th July, 2019 | JDJ | Genesis |
19th August, 2022 | JDJ | .NET 6 Update |