Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / C#

JHelpers 6 - A Good and Faithful Servant

Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
22 Aug 2022CPOL11 min read 8.4K   13   12
A library of generally useful methods and functionality that can save a developer from writing code to accomplish these mundane tasks. Targeted to .NET 6.
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.

C#
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);

// In your application’s shutdown code, I recommend adding this line so the
// ContextMgr disposes of its resources without waiting on the .NET garbage collector.

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

C#
String GetFullExceptionMessage(this Exception ex2Examine, 
                               Boolean getDataCollection, 
                               Boolean getStackTrace)
Example
C#
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.

C#
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.

C#
Int32 ContainsHowMany(this String source, String toCheck, Boolean ignoreCase = false)
Example
C#
String origString = "Having tea with the Team.";
Int32 result1 = origString.ContainsHowMany("tea", true);  // result1 = 2
Int32 result2 = origString.ContainsHowMany("tea");        // result2 = 1

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.

C#
Boolean ConvertToBoolean(this String valueToExamine, out Boolean isBoolean)
Example
C#
String origString = "trUe";
Boolean isBoolean = false;
Boolean result1 = origString.ConvertToBoolean(out isBoolean);  // result1 = true

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.

C#
Boolean IsBoolean(this String valueToExamine)
Example
C#
String origString = "trUe";
Boolean isBoolean = false;
Boolean result1 = origString.IsBoolean();  // result1 = true

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.

C#
Boolean IsOnlyDigits(this String testString, Boolean includePeriod = false)
Example
C#
String string2Check = "Nine.";
Boolean result = string2Check.IsOnlyDigits(false);  // result = false

string2Check = "999.0";
result = string2Check.IsOnlyDigits(false);  // result = false as the period 
          // is not allowed as a part of digits (looking for whole digits only)

string2Check = "999.0";
result = string2Check.IsOnlyDigits(true);   // result = true, as the period 
          // is allowed as a part of digits (looking for whole or decimal)

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 strings can be handled properly.

C#
String GetOnlyDigits(this String testString, Boolean includePeriod = false)
Example
C#
String value2Check = "Akery3mn.5n7X9.9c0";
String result = value2Check.GetOnlyDigits(false);  // result = "357990"

value2Check = "USD $2,332.45";
result = value2Check.GetOnlyDigits(true);          // result = "2332.45"

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.

C#
String GetOnlyLetters(this String testString, Boolean includeSpace = false)
Example
C#
String value2Check = "Akery 3mn.5n7X9.9c0";
String result = value2Check.GetOnlyLetters(false);       // result = "AkerymnnXc" 
                                                         // (no internal spaces)
String value2Check = "John Smith 999-99-9999";
String result = value2Check.GetOnlyLetters(true).Trim(); // result = "John Smith"  
                                                         // (internal spaces allowed)

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.

C#
String GetOnlyLettersAndDigits(this String testString, 
                               BooleanincludePeriodAndSpace = false)
Example
C#
String value2Check = "##### ... WARNING ... 123 ... #######";
String result = value2Check.GetOnlyLetters(false);             // result = "WARNING123"
String value2Check = "!@#$%^&*()+{}[]John Smith USD211.78";
String result = value2Check.GetOnlyLetters(true).Trim();       // result = "John Smith 
                                                               // USD211.78"

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.

C#
Boolean IsOnlyLetters(this String testString, Boolean includeSpace = false)
Example
C#
String string2Check = "Nine hundred forty two";
Boolean result = string2Check.IsOnlyLetters(false);   // result = false
result = string2Check.IsOnlyLetters(true);            // result = true

This String object extension checks for all characters being letters. If includeSpace is true, then spaces are accepted as if they were letters.

C#
Boolean IsOnlyLettersAndOrDigits(this String testString, 
                                 Boolean includePeriodAndSpace = false)
Example
C#
String string2Check = "Nine hundred forty two 942.00";
Boolean result = string2Check.IsOnlyLettersAndOrDigits(false); // result = false

string2Check = "999.0";
result = string2Check.IsOnlyLettersAndOrDigits(false);         // result = false

string2Check = "999.0";
result = string2Check.IsOnlyLettersAndOrDigits(true);          // result = true

string2Check = "Nine hundred forty two 942.00";
result = string2Check.IsOnlyLettersAndOrDigits(true);          // result = 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.

C#
Boolean IsEmailFormat(this String email)
Example
C#
String test1 = "John.Doe@domain";
Boolean result = test1.IsEmailFormat();  // result = false

test1 = "John.Doe@domain.net";
result = test1.IsEmailFormat();          // result = true

test1 = "Mary Smith@domain.net";
result = test1.IsEmailFormat();          // result = false

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.

C#
DateTime GetDateTime(this String dateString, DateTime dateDefault)
Example
C#
String time2Check = "02/29/2004 13:03:14.234";
DateTime result = time2Check.GetDateTime(DateTime.MinValue);   // result = 2/29/2004 
                                                               //          1:03:14 PM

time2Check = "02/29/2005 13:03:14.234";
result = time2Check.GetDateTime(DateTime.MinValue);            // result = 
         // DateTime.MinValue because "02/29/2005 13:03:14.234" is not a valid datetime.

This String object extension converts string to date, or returns the default value.

C#
Decimal GetDecimal(this String numberString, Decimal decimalDefault)
Example
C#
String number = "3.14159";
Decimal result = number.GetDecimal(0.0m);   // result = 3.14159

number = "1x";
result = number.GetDecimal(0.0m);           // result = 0  since "1x" is not a number.

This String object extension converts string to decimal value, or returns the default value.

C#
Int32 GetInt32(this String numberString, Int32 integerDefault)
Example
C#
String num = "23";
Int32 result = num.GetInt32(Int32.MinValue);   // result = 23

num = "1x";
result = num.GetInt32(Int32.MinValue);         // result = Int32.MinValue 
                                               // since "1x" is not an integer

This String object extension converts string to an Int32 value, or returns the default value.

C#
Int64 GetInt64(this String numberString, Int64 integerDefault)
Example
C#
String num = "23456";
Int64 result = num.GetInt64(Int64.MinValue); // result = 23,456

num = "1x";
result = num.GetInt64(Int64.MinValue); // result = Int64.MinValue since 
                                       //          "1x" is not an integer

This String object extension converts string to an Int64 value, or returns the default value.

C#
Object GetDefaultValue(this Type t)
Example
C#
Type dec = typeof(Decimal);
dec.GetDefaultValue();
Object result = dec.GetDefaultValue();   // result = 0

Type dtm = typeof(DateTime);
result = dtm.GetDefaultValue();          // result = 1/1/0001 12:00:00 AM

Type bmp = typeof(System.Drawing.Bitmap);
result = bmp.GetDefaultValue();          // result = Null

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
C#
AddressGeoData
    Double Latitude1
    Double Longitude1
    Double Altitude1
    Double Latitude2
    Double Longitude2
    Double Altitude2
    Double LinearDistance (value is calculated, read-only)
    DistanceUnitsOfMeasureEnum UnitsOfMeasure
Class Constructor
C#
AddressGeoData(Double pLatitude1,
               Double pLongitude1,
               Double pAltitude1,
               Double pLatitude2,
               Double pLongitude2,
               Double pAltitude2,
               DistanceUnitsOfMeasureEnum pUnitsOfMeasure)
Class Methods
C#
void SetUnitsOfMeasure(DistanceUnitsOfMeasureEnum lngUnitsOfMeasure)

Specify the units of measure to use during this class' instantiation.

C#
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.

C#
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.

C#
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.

C#
String TableDelimiter (Get only)
Example
C#
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.

C#
String FullComputerName (Get only)
Example
C#
String result = CommonHelpers.FullComputerName;

Gets the full computer name that DNS will recognize in any domain.

C#
String GetDNSName(String pComputerName = "")
Example
C#
result = CommonHelpers.GetDNSName("13.249.120.102");  // result = 
                           // "server-13-249-120-102.atl51.r.cloudfront.net"

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.

C#
String CurDir (Get/Set)
Example
C#
String result1 = CommonHelpers.CurDir;  // gets the current working folder
CommonHelpers.CurDir = @"C:\";          // changes the current working folder to C:\
String result2 = CommonHelpers.CurDir;  // gets the value of the folder 
                                        // you just changed to (C:\)
CommonHelpers.CurDir = result1;         // sets the current working folder 
                                        // back to what it originally was

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.

C#
Boolean AmIRunningInTheIDE (Get only)
Example
C#
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.

C#
Boolean IsInDomain()
Example
C#
Boolean result = CommonHelpers.IsInDomain();

Returns true if the computer running the code is in a domain. False if it is not.

C#
String GetComputerDomainName()
Example
C#
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.

C#
String GetFullComputerDomainName()
Example
C#
String result = CommonHelpers.GetFullComputerDomainName();

Returns the full domain name instead of the alias.

C#
Boolean IsDaylightSavingsTime(DateTime dtmToTest)
Example
C#
DateTime date2Check = "12/25/2020".GetDateTime(DateTime.MinValue);

result = CommonHelpers.IsDaylightSavingsTime(date2Check);  // result is false.

True if the datetime supplied falls within the period of Daylight Savings.

C#
Boolean IsDaylightSavingsTime()
Example
C#
Boolean result = CommonHelpers.IsDaylightSavingsTime(); // result is true if in DST

True if it is currently daylight savings time.

C#
String CurrentTimeZoneDaylightName (Get only)
Example
C#
String result1 = CommonHelpers.CurrentTimeZoneDaylightName;  // result1 = 
                                                             // "Eastern Daylight Time"

Name of the current time zone for daylight savings.

C#
String CurrentTimeZoneName (Get only)
Example
C#
String result = CommonHelpers.CurrentTimeZoneDaylightName;  // result = 
                                                            // "Eastern Daylight Time"

Name of the current time zone, regardless of daylight savings.

C#
Int32 Asc(String strChar)
Example
C#
Int32 result = CommonHelpers.Asc("T");  //  result = 84

Same functionality as the VB6 ASC function - give it a character, get back the ASCIII decimal number.

C#
String Hex(Int32 lngValue)
Example
C#
String result = CommonHelpers.Hex(320);  //  result = "140"

Same as the VB6 function. Converts a 32 bit integer to a String hex value.

C#
Int32 GetCurrentCPUUsage()
Example
C#
Int32 result = CommonHelpers.GetCurrentCPUUsage();   // result = 4 (as in 4%)

Gets the current % processor time.

C#
Int32 AvailableRAMinMB()
Example
C#
Int32 result = CommonHelpers.AvailableRAMinMB();   //  result = 13169

Returns available RAM MBs.

C#
PingReply Ping(String strHostName, Int32 lngTimeout)
Example
C#
PingReply result = CommonHelpers.Ping("www.microsoft.com", 1000);   //   Status-Success
                                                               // Roundtrip Time- 14ms
PingReply result = CommonHelpers.Ping("23.55.228.170", 1000);  // Status-Success  
                                                               // Roundtrip Time- 23ms

Pings the specified server synchronously. Returns a PingReply instance indicating whether or not the operation was successful.

C#
void GetLinearDistances(ref List<AddressGeoData> objAddressList)
Example
C#
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.

C#
Double GetLinearDistance(double Latitude1,
                         double Longitude1,
                         double Altitude1,
                         double Latitude2,
                         double Longitude2,
                         double Altitude2,
                         DistanceUnitsOfMeasureEnum lngUnitsOfMeasure)
Example
C#
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.

C#
Double GetLinearDistance(Double Latitude1,
                         Double Longitude1,
                         Double Altitude1,
                         Double Latitude2,
                         Double Longitude2,
                         Double Altitude2,
                         Boolean UseMiles)
Example
C#
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):

C#
Double GetLinearDistance(Double Latitude1,
                         Double Longitude1,
                         Double Latitude2,
                         Double Longitude2,
                         DistanceUnitsOfMeasureEnum UnitsOfMeasure)
Example
C#
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.

C#
Double RadianToDegree(Double Coordinate)
Example
C#
Double result = CommonHelpers.RadianToDegree(1.5d);  // result = 85.94366926962348 degrees

Converts radians to degrees.

C#
Double CelciusToFahrenheit(Double DegC)
Example
C#
Double result = CommonHelpers.CelsiusToFahrenheit(25);   // result = 77  (25°C = 77°F)

Converts Celsius to Fahrenheit.

C#
Double FahrenheitToCelsius(Double DegF)
Example
C#
Double result = CommonHelpers.FahrenheitToCelsius(77);  // result = 25  (77°F = 25°C)

Converts Fahrenheit to Celsius.

C#
String StringToBase64(String String2Convert)
Example
C#
String orig = "I am a string";
String result = CommonHelpers.StringToBase64(orig);   // result = "SSBhbSBhIHN0cmluZw=="

Convert String to Base64.

C#
String Base64ToString(String ByteString64)
Example
C#
String base64 = "SSBhbSBhIHN0cmluZw==";
String result = CommonHelpers.Base64ToString(base64);  // result = "I am a string"

Convert Base64String to String.

C#
List<ManagementObject> GetNetworkPrinters()
Example
C#
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.

C#
void SetIntBitValue(ref Int32 intValue, Int32 bitPlaceValue, Boolean setBitOn)
Example
C#
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.

C#
Boolean GetIntBitValue(Int32 intValue, Int32 bitPlaceValue)
Example
C#
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.

C#
String GetStackInfo()
String GetStackInfo(Exception ex)
Example
C#
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.

C#
String GetFullDateTimeStampForFileName(DateTime dtmDate)
Example
C#
String result = CommonHelpers.GetFullDateTimeStampForFileName(DateTime.Now)  // result = 
                                               // "2022-08-19T22.40.50.0712793-04.00"

This returns a String with a consistent datetime format for a filename.

C#
Boolean IsFileText(out Encoding lngEncoding, String strFileName, 
                   Int32 lngNumCharactersToRead)
Example
C#
Boolean result = CommonHelpers.IsFileText(out encodingType, 
                               @"C:\TestFile.txt", 80);  // result = True
result = CommonHelpers.IsFileText(out encodingType, 
                       @"C:\Windows\regedit.exe", 80);   // result = False

Detect if a file is text and detects the encoding.

C#
Int32 GetTotalHDDFreeSpace(String pDriveName)
Example
C#
Int32 result = CommonHelpers.GetTotalHDDFreeSpace("C");  // result = 58085

Returns MB of free disk space.

C#
Int32 GetTotalHDDSize(String pDriveName)
Example
C#
Int32 result = CommonHelpers.GetTotalHDDSize("C");  // result = 961507

Returns MB of total space.

C#
Int32 GetMinPasswordLength()
Example
C#
Int32 result = CommonHelpers.GetMinPasswordLength();  // result = -1

Returns the minimum password length from a domain, if one exists. If no domain exists, -1 is returned.

C#
Boolean IsIPAddress(String pValue, out IPAddress pIPValue)
Example
C#
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.

C#
String AssemblyTitle (Get only)
Example
C#
String result = CommonHelpers.AssemblyTitle;   // result = "JHelpers_Demo"

Title of the .NET assembly.

C#
String AssemblyVersion (Get only)
Example
C#
String result = CommonHelpers.AssemblyVersion;  // result = "1.0.0.0"

Version of the .NET assembly.

C#
String AssemblyDescription (Get only)
Example
C#
String result = CommonHelpers.AssemblyDescription;   // result = "Demonstrates how to 
                                                     // use the JHelpers library."

Description of the .NET assembly.

C#
String AssemblyProduct (Get only)
Example
C#
String result = CommonHelpers.AssemblyProduct;       // result = "JHelpers_Demo"

Product description of the .NET assembly.

C#
String AssemblyCopyright (Get only)
Example
C#
String result = CommonHelpers.AssemblyCopyright;     // result = "Copyright ©  2020"

Copyright string used by the .NET assembly.

C#
String AssemblyCompany (Get only)
Example
C#
String result = CommonHelpers.AssemblyCompany;  // result = "Jeff Jones"

Company that owns the .NET assembly.

C#
Boolean WriteToLog(String logFileName, String mainMessage, String secondMessage)
Example
C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAdvantage of ContextMgr ? Pin
tbayart31-Aug-22 4:11
professionaltbayart31-Aug-22 4:11 
AnswerRe: Advantage of ContextMgr ? Pin
MSBassSinger31-Aug-22 4:56
professionalMSBassSinger31-Aug-22 4:56 
GeneralRe: Advantage of ContextMgr ? Pin
tbayart1-Sep-22 9:01
professionaltbayart1-Sep-22 9:01 
GeneralRe: Advantage of ContextMgr ? Pin
MSBassSinger1-Sep-22 9:11
professionalMSBassSinger1-Sep-22 9:11 
QuestionNice Pin
_MarkJ_24-Aug-22 14:30
_MarkJ_24-Aug-22 14:30 
QuestionWrong version Pin
MSBassSinger19-Aug-22 6:30
professionalMSBassSinger19-Aug-22 6:30 
QuestionJLogger Pin
gil_tadiad29-Jul-19 16:59
gil_tadiad29-Jul-19 16:59 
AnswerRe: JLogger Pin
MSBassSinger19-Aug-22 6:24
professionalMSBassSinger19-Aug-22 6:24 
GeneralMy vote of 1 Pin
kiquenet.com29-Jul-19 10:42
professionalkiquenet.com29-Jul-19 10:42 
GeneralRe: My vote of 1 Pin
MSBassSinger19-Aug-22 6:26
professionalMSBassSinger19-Aug-22 6:26 
QuestionJLogger ? Pin
kiquenet.com29-Jul-19 10:24
professionalkiquenet.com29-Jul-19 10:24 
AnswerRe: JLogger ? Pin
MSBassSinger19-Aug-22 6:27
professionalMSBassSinger19-Aug-22 6:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.