You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

332 lines
11 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DevExpress.Data.Browsing.Design;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
namespace ZJ_BYD.Untils
{
public static class ExtendMethod
{
/// <summary>
/// DataTable转成List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToDataList<T>(this DataTable dt)
{
var list = new List<T>();
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
foreach (DataRow item in dt.Rows)
{
T s = Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(item[i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(item[i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
}
}
}
list.Add(s);
}
return list;
}
/// <summary>
/// List转换成DataTable
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ListToDataTable(IList list)
{
System.Data.DataTable result = new System.Data.DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
//获取类型
Type colType = pi.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
result.Columns.Add(pi.Name, colType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
/// <summary>
/// 表拆分
/// </summary>
/// <param name="dt"></param>
/// <param name="modcounts"></param>
/// <returns></returns>
public static List<DataTable> DataTableSplite(DataTable dt, int modcounts)
{
int counts = dt.Rows.Count / modcounts; /// 取整数个数
List<DataTable> list = new List<DataTable>();
int index = 0;
for (int i = 0; i < counts + 1; i++)
{
list.Add(dt.AsEnumerable().Skip(index * modcounts).Take(modcounts).CopyToDataTable());
index++;
}
return list;
}
/// <summary>
/// Ping测试
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool BoolPing(string ip)
{
var pingbool = true;
try
{
var ping = new Ping();
var replay = ping.Send(ip, 1000);
if (replay.Status != IPStatus.Success)
{
pingbool = false;
}
return pingbool;
}
catch (Exception ex)
{
LogHelper.WriteErrorLog("Ping操作异常", ex);
return false;
}
}
/// <summary>
/// 生成条码
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public static string NumFormat(int a)
{
string num = "";
if (a <= 9)
{
num = "000" + a.ToString();
}
if (a > 9 && a <= 99)
{
num = "00" + a.ToString();
}
if (a > 99 && a <= 999)
{
num = "0" + a.ToString();
}
if (a > 999)
{
num = a.ToString();
}
return num;
}
/// <summary>
/// 字节数组转16进制字符串数组
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string[] ByteArrayToHexStrArray(byte[] bytes)
{
string[] sHexStrArray = null;
if (bytes?.Length > 0)
{
sHexStrArray = new string[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
sHexStrArray[i] = bytes[i].ToString("X2");
}
}
return sHexStrArray;
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static (bool isok, string msg) ByteArrayToHexStr(byte[] bytes, string separator = "")
{
try
{
string returnStr = "";
if (bytes?.Length > 0)
{
foreach (byte byteItem in bytes)
{
returnStr += byteItem.ToString("X2") + separator;
}
}
return (true, returnStr.Trim());
}
catch (Exception ex)
{
var msg = ex == null ? "操作异常" : ex.Message;
return (false, "");
}
}
/// <summary>
/// 字符串转16进制字符
/// </summary>
/// <param name="_str">字符串</param>
/// <param name="encode">编码格式</param>
/// <returns></returns>
public static string StringToHexString(string _str, Encoding encode)
{
//去掉空格
_str = _str.Replace(" ", "");
//将字符串转换成字节数组。
byte[] buffer = encode.GetBytes(_str);
//定义一个string类型的变量用于存储转换后的值。
string result = string.Empty;
for (int i = 0; i < buffer.Length; i++)
{
//将每一个字节数组转换成16进制的字符串以空格相隔开。
result += Convert.ToString(buffer[i], 16) + " ";
}
return result;
}
/// <summary>
/// 16进制字符转字符串
/// </summary>
/// <param name="hex">16进制字符</param>
/// <param name="encode">编码格式</param>
/// <returns></returns>
public static string HexStringToString(string hex, Encoding encode)
{
byte[] buffer = new byte[hex.Length / 2];
string result = string.Empty;
for (int i = 0; i < hex.Length / 2; i++)
{
result = hex.Substring(i * 2, 2);
buffer[i] = Convert.ToByte(result, 16);
}
//返回指定编码格式的字符串
return encode.GetString(buffer);
}
/// <summary>
/// 获取通讯协议的CRC校验和
/// </summary>
/// <param name="strHex"></param>
/// <returns></returns>
public static string ProtocolCRC(string strHex)
{
string[] hexArr = strHex.Split(' ');
int totalNum = 0;
for (int i = 0; i < hexArr.Length; i++)
{
totalNum += Convert.ToInt32(hexArr[i], 16);
}
int low = totalNum & 0xff;//低8位
//int high = (value >> 8) & 0xff;//高8位
var CRCVal = NumberToHexByteArray(low, "X2");
return $"{strHex} {CRCVal}";
}
/// <summary>
/// 十进制转十六进制字符串
/// </summary>
/// <param name="data"></param>
/// <param name="strHEx"></param>
/// <returns></returns>
public static string NumberToHexByteArray(int data, string strHEx = "X4")
{
var str = string.Empty;
int count = 2;//每两个字符进行分割
var hexStr = data.ToString(strHEx);
int length = (int)Math.Ceiling((double)hexStr.Length / count);
for (int i = 0; i < length; i++)
{
int start = count * i;
if (hexStr.Length <= start)
{
break;
}
if (hexStr.Length < start + count)
{
str += hexStr.Substring(start) + " ";
}
else
{
str += hexStr.Substring(start, count) + " ";
}
}
return str;
}
/// <summary>
/// 根据key设置AppConfig值
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
public static (bool isSuccess, string msg) WriteValueByKey(string key, string val)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return (false, $"AppConfigHelper.WriteValueByKey()入参key={key}不存在!");
}
config.AppSettings.Settings[key].Value = val;
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return (true, "操作成功");
}
catch (Exception ex)
{
return (false, $"AppConfigHelper.WriteValueByKey()操作失败{ex.StackTrace}Key={key},Val={val}");
}
}
}
}