目录
介绍
JHelpers6是一个.NET 6库组件,可与任何受支持的操作系统上的任何.NET 6兼容项目一起使用。它是一个通常有用的方法和功能的库,可以使开发人员免于编写代码来完成这些平凡的任务——或者更糟糕的是,在多个地方编写相同操作的方法的多个版本。 正是出于这个原因,在我的JDAC6和JLogger6 NuGet包中使用JHelpers6。
- 源代码可在 GitHub - MSBassSinger/JHelpers6: .NET helper functions, targeted to .NET 6
- 演示代码可在 GitHub - MSBassSinger/JHelpers_Demo6: Example code and demo for JHelpers6
有关如何使用该JHelpers6库的最佳示例,请参阅上面引用的演示代码。对于最初的读者,我包含了该演示项目中的代码片段,以便简要了解如何以及为什么使用库的各种属性。
通过搜索NuGet Jeff.Jones.JHelpers6或直接转到 NuGet Gallery | Jeff.Jones.JHelpers6 6.0.1 来找到该组件。
背景
随着时间的推移,我发现,就像许多开发人员一样,我在多个项目中使用了某些辅助函数和简单功能。因此,我将它们(从头开始重写,以免使用为他人编写并由他人拥有的代码)合并到库中。然后,我通过在另外两个NuGet项目中使用此库“吃了我自己的狗粮”(可以这么说)。
CommonHelpers是一个具有static方法和扩展的static类。
ContextMgr是一个线程安全的单一实例,可用于将数据存储在可从应用程序中任何位置和任何线程访问的单个位置。一个典型的用途是存储设置和其他运行时值,以便它们的源(文件、数据库等)只需读取一次。任何可以定义为唯一String名称以及任何类型的值或引用类型的内容都可以保留在那里。值将添加为String键名称(必须是唯一的)和任何值或引用类型,并装箱为动态类型。
ContextMgr没有初始化,并且作为单例,不使用“new”进行创建。实际实例是在代码中的第一个引用上动态创建的。
使用代码
ContextMgr代码示例
在此示例中,一些名称/值对将添加到ContextMgr单一实例。可以从项目中的任何其他代码访问它们。这为您提供了一个位置来存储、编辑和检索代码中一个位置指定的值(例如启动时读取的值)。
请注意,该TryGetValue方法允许以优雅的方式获取值并确定该值是否存在。
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
这是一个具有许多有用static方法的static类。引用命名空间后,扩展方法将显示在智能感知中。
扩展方法
String GetFullExceptionMessage(this Exception ex2Examine,
Boolean getDataCollection,
Boolean getStackTrace)
例
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;
此Exception对象扩展从父异常和堆栈中的任何异常以及可选的数据收集中返回错误消息。该Exception.Data集合用于存储通常记录运行时值或其他重要数据以进行调试的名称-值对。
Boolean Contains(this String source, String toCheck, StringComparison strComp)
例
//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
此String对象扩展允许在string上比较string类型以进行检查。如果toCheck string在string源中,则扩展方法返回true,如果不是则扩展方法返回false。
Int32 ContainsHowMany(this String source, String toCheck, Boolean ignoreCase = false)
例
String origString = "Having tea with the Team.";
Int32 result1 = origString.ContainsHowMany("tea", true); // result1 = 2
Int32 result2 = origString.ContainsHowMany("tea"); // result2 = 1
此String对象扩展获取给定string在另一个string中出现的次数。扩展方法返回0到n次的Count。
Boolean ConvertToBoolean(this String valueToExamine, out Boolean isBoolean)
例
String origString = "trUe";
Boolean isBoolean = false;
Boolean result1 = origString.ConvertToBoolean(out isBoolean); // result1 = true
此String对象扩展名用于将string(假定采用可转换的格式)转换为布尔值。识别true为(不区分大小写)true, on, yes, up, ok, good, 1, -1。识别false为(不区分大小写):false, off, no, down, not ok, bad, 0。如果转换失败,则返回false。检查isBoolean out值以查看转换是否检测到布尔值。如果是false,则未转换该值。
Boolean IsBoolean(this String valueToExamine)
例
String origString = "trUe";
Boolean isBoolean = false;
Boolean result1 = origString.IsBoolean(); // result1 = true
此String对象扩展测试string,假定采用可转换为布尔值的格式。识别true为(不区分大小写)true, on, yes, up, ok, good, start, 1, -1。识别false为(不区分大小写):false, off, no, down, not ok, bad, stop, 0。如果转换失败,则返回false。否则,返回。true
Boolean IsOnlyDigits(this String testString, Boolean includePeriod = false)
例
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)
此String对象扩展检查所有字符是否为数字。测试数字的转换函数可以将字母转换为十六进制值。includePeriod设置为true如果将唯一句点视为数字,以便可以正确处理十进制数string。
String GetOnlyDigits(this String testString, Boolean includePeriod = false)
例
String value2Check = "Akery3mn.5n7X9.9c0";
String result = value2Check.GetOnlyDigits(false); // result = "357990"
value2Check = "USD $2,332.45";
result = value2Check.GetOnlyDigits(true); // result = "2332.45"
此String对象扩展获取string中的所有数字,并忽略任何非数字。如果includePeriod是true,则string中的第一个句点将包含在结果中。
String GetOnlyLetters(this String testString, Boolean includeSpace = false)
例
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)
此String对象扩展获取string中的所有字母,并忽略任何非字母。但是,如果includeSpace是true,则找到的任何空格都包含在返回值中。
String GetOnlyLettersAndDigits(this String testString,
BooleanincludePeriodAndSpace = false)
例
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"
此String对象扩展名获取string中的所有字母和数字,并忽略所有其他内容,当includePeriodAndSpace是true时,句点和空格除外。
Boolean IsOnlyLetters(this String testString, Boolean includeSpace = false)
例
String string2Check = "Nine hundred forty two";
Boolean result = string2Check.IsOnlyLetters(false); // result = false
result = string2Check.IsOnlyLetters(true); // result = true
此String对象扩展名检查所有字符是否为字母。如果includeSpace是true,则空格被接受为字母。
Boolean IsOnlyLettersAndOrDigits(this String testString,
Boolean includePeriodAndSpace = false)
例
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
此String对象扩展检查所有字符是否仅为字母和数字。如果includePeriodAndSpace为true,则所有句点和空格都被视为字母。
Boolean IsEmailFormat(this String email)
例
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
此String对象扩展名检查string以查看它是否是有效的电子邮件格式。它不会检查它是否是有效的工作电子邮件。
DateTime GetDateTime(this String dateString, DateTime dateDefault)
例
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.
此String对象扩展转换string为date或返回默认值。
Decimal GetDecimal(this String numberString, Decimal decimalDefault)
例
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.
此String对象扩展转换string为十进制值,或返回默认值。
Int32 GetInt32(this String numberString, Int32 integerDefault)
例
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
此String对象扩展转换string为Int32值,或返回默认值。
Int64 GetInt64(this String numberString, Int64 integerDefault)
例
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
此String对象扩展转换string为Int64值,或返回默认值。
Object GetDefaultValue(this Type t)
例
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
返回类型默认值(如果存在)的泛型扩展方法。这在default<T>可能不起作用的通用实例中很有用。
帮助程序函数和属性
枚举
DistanceUnitsOfMeasureEnum
Unassigned
Miles
Kilometers
Feet
Meters
这与地理位置一起使用,以指定距离的测量单位。
类
AddressGeoData
Double Latitude1
Double Longitude1
Double Altitude1
Double Latitude2
Double Longitude2
Double Altitude2
Double LinearDistance (value is calculated, read-only)
DistanceUnitsOfMeasureEnum UnitsOfMeasure
类构造函数
AddressGeoData(Double pLatitude1,
Double pLongitude1,
Double pAltitude1,
Double pLatitude2,
Double pLongitude2,
Double pAltitude2,
DistanceUnitsOfMeasureEnum pUnitsOfMeasure)
类方法
void SetUnitsOfMeasure(DistanceUnitsOfMeasureEnum lngUnitsOfMeasure)
指定在此类实例化期间要使用的度量单位。
void SetLinearDistance(Double dDistance)
此类用于存储指定纬度、经度和高度的两个地理位置。度量单位确定与LinearDistance值对应的单位。如果不知道或不需要,则可能是高度为0。
String RowDelimiter (Get only)
此值可以应用于常量的值。RowDelimiter与电传打字机和其他设备中用于指示新行的不可打印ASCII字符相同,并且不太可能在string数据中看到。
String ColumnDelimiter (Get only)
此值可以应用于常量的值。ColumnDelimiter与电传打字机和其他设备中用于指示新列的不可打印ASCII字符相同,不太可能在string数据中看到。
此代码显示自行打印机开始以来,如何使用不可打印的分隔符使用标准分隔符构建行和列表。
可用于构建可接受具有任何可打印字符的字段值的表,尤其是那些通常用作分隔符的表。
String TableDelimiter (Get only)
例
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();
此值可以应用于常量的值。TableDelimiter与电传打字机和其他设备中使用的不可打印ASCII字符相同,用于指示新的数据表,并且不太可能在string数据中看到。
String FullComputerName (Get only)
例
String result = CommonHelpers.FullComputerName;
获取DNS将在任何域中识别的完整计算机名称。
String GetDNSName(String pComputerName = "")
例
result = CommonHelpers.GetDNSName("13.249.120.102"); // result =
// "server-13-249-120-102.atl51.r.cloudfront.net"
获取给定计算机名称的DNS主机条目表名称。传入任何计算机名称。如果留空或null,将使用当前计算机名称。
String CurDir (Get/Set)
例
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
获取或设置当前工作目录的完全限定路径。对于服务,当前目录通过正常方式显示Windows System32 目录,因为服务在位于那里的EXE下运行。此属性通过使用一个方法调用在IDE中运行,另一个方法调用来运行已编译,从而说明了这一点。
Boolean AmIRunningInTheIDE (Get only)
例
Boolean result = CommonHelpers.AmIRunningInTheIDE;
if (result)
{
txtResults.Text += "Running in the IDE";
}
else
{
txtResults.Text += "Running compiled";
}
如果此项目或将此组件作为编译代码调用的任何项目在IDE下运行,则此方法将返回true。如果未使用IDE,则此方法返回false。
Boolean IsInDomain()
例
Boolean result = CommonHelpers.IsInDomain();
如果运行代码的计算机位于域中,则返回true。如果不是则返回False。
String GetComputerDomainName()
例
String result = CommonHelpers.GetComputerDomainName();
返回计算机加入到的域。注意:如果用户以本地帐户登录,则仍返回计算机域。如果已加入,则返回带有域名的String,如果未加入,则返回空String。
String GetFullComputerDomainName()
例
String result = CommonHelpers.GetFullComputerDomainName();
返回完整的域名而不是别名。
Boolean IsDaylightSavingsTime(DateTime dtmToTest)
例
DateTime date2Check = "12/25/2020".GetDateTime(DateTime.MinValue);
result = CommonHelpers.IsDaylightSavingsTime(date2Check); // result is false.
True如果datetime供应的属于夏令时。
Boolean IsDaylightSavingsTime()
例
Boolean result = CommonHelpers.IsDaylightSavingsTime(); // result is true if in DST
True如果当前是夏令时。
String CurrentTimeZoneDaylightName (Get only)
例
String result1 = CommonHelpers.CurrentTimeZoneDaylightName; // result1 =
// "Eastern Daylight Time"
夏令时的当前时区的名称。
String CurrentTimeZoneName (Get only)
例
String result = CommonHelpers.CurrentTimeZoneDaylightName; // result =
// "Eastern Daylight Time"
当前时区的名称,与夏令时无关。
Int32 Asc(String strChar)
例
Int32 result = CommonHelpers.Asc("T"); // result = 84
与VB6 ASC函数的功能相同——给它一个字符,取回ASCIII十进制数。
String Hex(Int32 lngValue)
例
String result = CommonHelpers.Hex(320); // result = "140"
与VB6函数相同。将32位整数转换为String hex值。
Int32 GetCurrentCPUUsage()
例
Int32 result = CommonHelpers.GetCurrentCPUUsage(); // result = 4 (as in 4%)
获取当前处理器时间百分比。
Int32 AvailableRAMinMB()
例
Int32 result = CommonHelpers.AvailableRAMinMB(); // result = 13169
返回可用的内存MB。
PingReply Ping(String strHostName, Int32 lngTimeout)
例
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
同步ping指定的服务器。返回一个PingReply实例,该实例指示操作是否成功。
void GetLinearDistances(ref List<AddressGeoData> objAddressList)
例
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);
结果
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.
此函数使用Haversine公式计算两组纬度和经度之间的线性距离,并根据纬度调整地球半径。使用Haversine代替Vincenty公式,以保持计算更简单,处理器密集度更低。此函数获取地址地理数据实例的列表并对其进行处理,更新List中线性距离属性中的各个类实例。
Double GetLinearDistance(double Latitude1,
double Longitude1,
double Altitude1,
double Latitude2,
double Longitude2,
double Altitude2,
DistanceUnitsOfMeasureEnum lngUnitsOfMeasure)
例
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);
结果
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.
此函数使用Haversine公式计算两组纬度和经度之间的线性距离,并根据纬度调整地球半径。使用Haversine代替Vincenty公式,以保持计算更简单,处理器密集度更低。此重载允许调用方指定返回值所需的度量单位。
Double GetLinearDistance(Double Latitude1,
Double Longitude1,
Double Altitude1,
Double Latitude2,
Double Longitude2,
Double Altitude2,
Boolean UseMiles)
例
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);
结果
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.
此函数使用Haversine公式计算两组纬度和经度之间的线性距离,并根据纬度调整地球半径。使用Haversine代替Vincenty公式,以保持计算更简单,处理器密集度更低。此重载允许用户在英里和公里(UseMiles参数)之间进行选择:
Double GetLinearDistance(Double Latitude1,
Double Longitude1,
Double Latitude2,
Double Longitude2,
DistanceUnitsOfMeasureEnum UnitsOfMeasure)
例
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);
结果
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.
此函数使用Haversine公式计算两组纬度和经度之间的线性距离,但不提供高度(所有计算都假定地球在海平面曲线上呈线性),并根据纬度调整地球半径。使用Haversine代替Vincenty公式,以保持计算更简单,处理器密集度更低。此重载允许用户选择度量单位。
Double RadianToDegree(Double Coordinate)
例
Double result = CommonHelpers.RadianToDegree(1.5d); // result = 85.94366926962348 degrees
将弧度转换为度。
Double CelciusToFahrenheit(Double DegC)
例
Double result = CommonHelpers.CelsiusToFahrenheit(25); // result = 77 (25°C = 77°F)
将摄氏度转换为华氏度。
Double FahrenheitToCelsius(Double DegF)
例
Double result = CommonHelpers.FahrenheitToCelsius(77); // result = 25 (77°F = 25°C)
将华氏度转换为摄氏度。
String StringToBase64(String String2Convert)
例
String orig = "I am a string";
String result = CommonHelpers.StringToBase64(orig); // result = "SSBhbSBhIHN0cmluZw=="
String转换为Base64。
String Base64ToString(String ByteString64)
例
String base64 = "SSBhbSBhIHN0cmluZw==";
String result = CommonHelpers.Base64ToString(base64); // result = "I am a string"
Base64String转换为String。
List<ManagementObject> GetNetworkPrinters()
例
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;
}
获取使用List对象中每台打印机一个ManagementObject实例的网络打印机的列表。
void SetIntBitValue(ref Int32 intValue, Int32 bitPlaceValue, Boolean setBitOn)
例
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;
用于设置Int开/关位值的帮助程序方法。
Boolean GetIntBitValue(Int32 intValue, Int32 bitPlaceValue)
例
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.";
帮助程序方法,用于获取Int类型的位值的状态。
String GetStackInfo()
String GetStackInfo(Exception ex)
例
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]";
}
这将在String中获取模块、函数、行号和列号信息。这在记录和创建异常以准确定义发生某些事情的位置时非常有用。
第二个重载根据异常获取String中的模块、函数、行号和列号信息。这在记录和创建异常以准确定义发生某些事情的位置时非常有用。
String GetFullDateTimeStampForFileName(DateTime dtmDate)
例
String result = CommonHelpers.GetFullDateTimeStampForFileName(DateTime.Now) // result =
// "2022-08-19T22.40.50.0712793-04.00"
这将返回具有一致datetime格式的String文件名。
Boolean IsFileText(out Encoding lngEncoding, String strFileName,
Int32 lngNumCharactersToRead)
例
Boolean result = CommonHelpers.IsFileText(out encodingType,
@"C:\TestFile.txt", 80); // result = True
result = CommonHelpers.IsFileText(out encodingType,
@"C:\Windows\regedit.exe", 80); // result = False
检测文件是否为文本并检测编码。
Int32 GetTotalHDDFreeSpace(String pDriveName)
例
Int32 result = CommonHelpers.GetTotalHDDFreeSpace("C"); // result = 58085
返回MB的可用磁盘空间。
Int32 GetTotalHDDSize(String pDriveName)
例
Int32 result = CommonHelpers.GetTotalHDDSize("C"); // result = 961507
返回总空间的MB。
Int32 GetMinPasswordLength()
例
Int32 result = CommonHelpers.GetMinPasswordLength(); // result = -1
返回域的最小密码长度(如果存在)。如果不存在域,则返回-1。
Boolean IsIPAddress(String pValue, out IPAddress pIPValue)
例
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;
}
结果
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
检查string是IPv4地址还是IPv6地址,并将IPAddress对象作为out参数返回。
String AssemblyTitle (Get only)
例
String result = CommonHelpers.AssemblyTitle; // result = "JHelpers_Demo"
.NET程序集的标题。
String AssemblyVersion (Get only)
例
String result = CommonHelpers.AssemblyVersion; // result = "1.0.0.0"
.NET程序集的版本。
String AssemblyDescription (Get only)
例
String result = CommonHelpers.AssemblyDescription; // result = "Demonstrates how to
// use the JHelpers library."
.NET程序集的说明。
String AssemblyProduct (Get only)
例
String result = CommonHelpers.AssemblyProduct; // result = "JHelpers_Demo"
.NET程序集的产品说明。
String AssemblyCopyright (Get only)
例
String result = CommonHelpers.AssemblyCopyright; // result = "Copyright © 2020"
.NET程序集使用的版权string。
String AssemblyCompany (Get only)
例
String result = CommonHelpers.AssemblyCompany; // result = "Jeff Jones"
拥有.NET程序集的公司。
Boolean WriteToLog(String logFileName, String mainMessage, String secondMessage)
例
Boolean result = CommonHelpers.WriteToLog(@"C:\Temp\TestFile.log",
"Main message to log", "Optional second message to log");
结果
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
执行简单的基于文件的日志写入的方法,其中文件以制表符分隔并具有列标题行。
兴趣点
我为此创建了一个签名的NuGet包,并将其集成到我的JLogger6 NuGet包中。
https://www.codeproject.com/Articles/5163230/JHelpers-6-A-Good-and-Faithful-Servant