BaseUtil.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. using DevExpress.XtraEditors;
  2. using DevExpress.XtraEditors.Repository;
  3. using System;
  4. using System.Data;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using UAS_PLCDataReader.DataOperate;
  9. using DevExpress.Utils;
  10. using UAS_PLCDataReader.CustomerControl.ValueLabel;
  11. using System.Collections.Generic;
  12. using System.Xml;
  13. using UAS_PLCDataReader.Entity;
  14. using System.Text.RegularExpressions;
  15. namespace UAS_PLCDataReader.PublicMethod
  16. {
  17. class BaseUtil
  18. {
  19. [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
  20. public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
  21. public static void FillComBoxEditWidthDataTable(RepositoryItemComboBox combo, string TextField, string ValueField, DataTable dt)
  22. {
  23. combo.Items.Clear();
  24. for (int i = 0; i < dt.Rows.Count; i++)
  25. {
  26. ComboBoxData item = new ComboBoxData();
  27. item.Value = dt.Rows[i][ValueField].ToString();
  28. item.Text = dt.Rows[i][TextField].ToString();
  29. combo.Items.Add(item);
  30. }
  31. }
  32. public static void FillComBoxEditWidthDataTable(ComboBoxEdit combo, string TextField, string ValueField, DataTable dt)
  33. {
  34. combo.Properties.Items.Clear();
  35. for (int i = 0; i < dt.Rows.Count; i++)
  36. {
  37. ComboBoxData item = new ComboBoxData();
  38. item.Value = dt.Rows[i][ValueField].ToString();
  39. item.Text = dt.Rows[i][TextField].ToString();
  40. combo.Properties.Items.Add(item);
  41. }
  42. combo.SelectedIndex = 0;
  43. }
  44. public static void FillComBoxEditWidthDataTable(ComboBoxEdit combo, string TextField, string ValueField, DataTable dt, bool AddAll)
  45. {
  46. combo.Properties.Items.Clear();
  47. if (AddAll)
  48. {
  49. ComboBoxData item = new ComboBoxData();
  50. item.Value = "全部";
  51. item.Text = "全部";
  52. combo.Properties.Items.Add(item);
  53. }
  54. for (int i = 0; i < dt.Rows.Count; i++)
  55. {
  56. ComboBoxData item = new ComboBoxData();
  57. item.Value = dt.Rows[i][ValueField].ToString();
  58. item.Text = dt.Rows[i][TextField].ToString();
  59. combo.Properties.Items.Add(item);
  60. }
  61. combo.SelectedIndex = 0;
  62. }
  63. public static DataTable ToDataTable(DataRow[] rows)
  64. {
  65. if (rows == null || rows.Length == 0) return new DataTable();
  66. DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
  67. foreach (DataRow row in rows)
  68. tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
  69. return tmp;
  70. }
  71. public static string GetComboxEditValue(ComboBoxEdit ComBox)
  72. {
  73. if (ComBox.SelectedItem == null)
  74. return ComBox.Text;
  75. else
  76. return (ComBox.SelectedItem as ComboBoxData).Value;
  77. }
  78. public static Dictionary<string, object> ToDictionary(string JsonData)
  79. {
  80. object Data = null;
  81. Dictionary<string, object> Dic = new Dictionary<string, object>();
  82. if (JsonData.StartsWith("["))
  83. {
  84. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  85. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  86. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  87. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  88. foreach (Match ListItem in ListMatch)
  89. {
  90. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  91. }
  92. Data = List;
  93. Dic.Add("List", Data);
  94. }
  95. else
  96. {
  97. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  98. foreach (Match item in Match)
  99. {
  100. try
  101. {
  102. if (item.Groups[2].ToString().StartsWith("["))
  103. {
  104. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  105. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  106. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  107. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  108. foreach (Match ListItem in ListMatch)
  109. {
  110. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  111. }
  112. Data = List;
  113. }
  114. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  115. else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
  116. Dic.Add(item.Groups[1].ToString(), Data);
  117. }
  118. catch { }
  119. }
  120. }
  121. return Dic;
  122. }
  123. /// <summary>
  124. /// 获取LRC
  125. /// </summary>
  126. /// <param name="SQL"></param>
  127. public static string getLRC(string SENDMESSAGE)
  128. {
  129. string message = SENDMESSAGE.Trim();
  130. if (message.Length % 2 != 0)
  131. {
  132. message = message + "0";
  133. }
  134. int LRC = 0x0;
  135. for (int i = 0; i < message.Length; i = i + 2)
  136. {
  137. int inside = int.Parse(message.Substring(i, 1).ToString() + message.Substring(i + 1, 1).ToString(), System.Globalization.NumberStyles.HexNumber);
  138. LRC += inside;
  139. }
  140. string _LRC = string.Format("{0:X2}", LRC);
  141. string LRCre = "";
  142. for (int i = 0; i < _LRC.Length; i++)
  143. {
  144. int index;
  145. index = 0xF - int.Parse(_LRC.Substring(i, 1).ToString(), System.Globalization.NumberStyles.HexNumber);
  146. LRCre += string.Format("{0:X}", index);
  147. }
  148. LRCre = string.Format("{0:X}", int.Parse(LRCre, System.Globalization.NumberStyles.HexNumber) + 1);
  149. return LRCre;
  150. }
  151. public static string ByteToHexadecimalString(byte[] b, int length)
  152. {
  153. string returnStr = "";
  154. if (b != null)
  155. {
  156. for (int i = 0; i < length; i++)
  157. {
  158. returnStr += Convert.ToString(b[i], 16);//ToString("X2") 为C#中的字符串格式控制符
  159. }
  160. }
  161. return returnStr.ToUpper();
  162. }
  163. public static void CleanMemory()
  164. {
  165. GC.Collect();
  166. GC.WaitForPendingFinalizers();
  167. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  168. {
  169. SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
  170. }
  171. }
  172. private static ToolTipControllerShowEventArgs args;
  173. public static ToolTipController MyToolTipClt { get; private set; }
  174. public static void NewToolTip(Control ctl, string title, string content, int showTime, ToolTipType toolTipType, ToolTipLocation tipLocation, bool isAutoHide, ToolTipIconType tipIconType, ImageList imgList, int imgIndex)
  175. {
  176. try
  177. {
  178. MyToolTipClt = new ToolTipController();
  179. args = MyToolTipClt.CreateShowArgs();
  180. content = (string.IsNullOrEmpty(content) ? "???" : content);
  181. title = string.IsNullOrEmpty(title) ? "温馨提示" : title;
  182. MyToolTipClt.ImageList = imgList;
  183. MyToolTipClt.ImageIndex = (imgList == null ? 0 : imgIndex);
  184. args.AutoHide = isAutoHide;
  185. MyToolTipClt.ShowBeak = true;
  186. MyToolTipClt.ShowShadow = true;
  187. MyToolTipClt.Rounded = true;
  188. MyToolTipClt.AutoPopDelay = (showTime == 0 ? 2000 : showTime);
  189. MyToolTipClt.SetToolTip(ctl, content);
  190. MyToolTipClt.SetTitle(ctl, title);
  191. MyToolTipClt.SetToolTipIconType(ctl, tipIconType);
  192. MyToolTipClt.Active = true;
  193. MyToolTipClt.HideHint();
  194. MyToolTipClt.ShowHint(content, title, ctl, tipLocation);
  195. }
  196. catch (Exception)
  197. {
  198. }
  199. }
  200. /// <summary>
  201. /// 检测键值对是否发生值的变化
  202. /// </summary>
  203. public static bool CheckDicDiff(Dictionary<string, string> A, Dictionary<string, string> B)
  204. {
  205. foreach (var item in B)
  206. {
  207. //不对比产量和产出
  208. if (A.ContainsKey(item.Key) && (Main.inqty == "-1" || Main.outqty == "-1" || Main.param == "-1"))
  209. {
  210. if (A[item.Key] != item.Value)
  211. {
  212. return true;
  213. }
  214. }
  215. }
  216. return false;
  217. }
  218. /// <summary>
  219. /// 传入控件的集合和DataTable,通过判断控件的名称和数据源的列的描述来匹配,支持单层的GroupBox和Panel
  220. /// </summary>
  221. /// <param name="collection"></param>
  222. /// <param name="dt"></param>
  223. public static void SetFormValue(Control.ControlCollection collection, DataTable dt)
  224. {
  225. //DataTable存在数据才进行赋值操作
  226. if (dt.Rows.Count > 0)
  227. {
  228. for (int i = 0; i < collection.Count; i++)
  229. {
  230. //如果含有子控件则进行递归调用
  231. if (collection[i].Controls.Count > 0)
  232. SetFormValue(collection[i].Controls, dt);
  233. string controlName = collection[i].Name;
  234. string controlsTag = collection[i].Tag == null ? "" : collection[i].Tag.ToString();
  235. //默认给TextBox和Label赋值
  236. if (collection[i] is TextBox || collection[i] is ValueLabel || collection[i] is NumericUpDown)
  237. {
  238. for (int j = 0; j < dt.Columns.Count; j++)
  239. {
  240. if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper() || controlsTag.ToUpper() == dt.Columns[j].Caption.ToUpper())
  241. {
  242. //字段含有Status内容的才进行转换
  243. if (controlName.ToUpper().Contains("STATUS") || controlsTag.ToUpper().Contains("STATUS"))
  244. {
  245. //对审批状态进行判断
  246. switch (dt.Rows[0][j].ToString().ToUpper())
  247. {
  248. case "ENTERING":
  249. collection[i].Text = "在录入";
  250. break;
  251. case "UNAPPROVED":
  252. collection[i].Text = "未批准";
  253. break;
  254. case "COMMITED":
  255. collection[i].Text = "已提交";
  256. break;
  257. case "APPROVE":
  258. collection[i].Text = "已批准";
  259. break;
  260. case "AUDITED":
  261. collection[i].Text = "已审核";
  262. break;
  263. case "STARTED":
  264. collection[i].Text = "已下放";
  265. break;
  266. case "UNCHECK":
  267. collection[i].Text = "待检验";
  268. break;
  269. case "CHECKING":
  270. collection[i].Text = "检验中";
  271. break;
  272. default:
  273. collection[i].Text = dt.Rows[0][j].ToString();
  274. break;
  275. }
  276. }
  277. else
  278. collection[i].Text = dt.Rows[0][j].ToString();
  279. }
  280. }
  281. }
  282. //对封装在GroupBox的和Panel的控件进行批量赋值
  283. if (collection[i] is GroupControl || collection[i] is Panel)
  284. {
  285. for (int j = 0; j < collection[i].Controls.Count; j++)
  286. {
  287. controlName = collection[i].Controls[j].Name;
  288. if (collection[i].Controls[j] is TextBox || collection[i].Controls[j] is ValueLabel)
  289. {
  290. for (int k = 0; k < dt.Columns.Count; k++)
  291. {
  292. if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
  293. {
  294. collection[i].Controls[j].Text = dt.Rows[0][k].ToString();
  295. }
  296. }
  297. }
  298. }
  299. }
  300. }
  301. }
  302. //如果没有记录的话,将dt中含有的列的对应值设置为空
  303. else
  304. {
  305. for (int i = 0; i < collection.Count; i++)
  306. {
  307. if (collection[i] is TextBox || collection[i] is ValueLabel)
  308. {
  309. for (int j = 0; j < dt.Columns.Count; j++)
  310. {
  311. if (collection[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
  312. {
  313. collection[i].Text = "";
  314. }
  315. }
  316. }
  317. }
  318. }
  319. }
  320. public static string ASCIIToString(string ASCII)
  321. {
  322. string ReturnStr = "";
  323. ASCII = ASCII.Replace(" ", "").Replace("3A", "").Replace("DA", "").Replace("0D", "").Replace("0A", "");
  324. for (int i = 0; i <= ASCII.Length; i = i + 2)
  325. {
  326. if (i + 2 <= ASCII.Length)
  327. {
  328. switch (ASCII.Substring(i, 2))
  329. {
  330. case "30":
  331. ReturnStr += "0";
  332. break;
  333. case "31":
  334. ReturnStr += "1";
  335. break;
  336. case "32":
  337. ReturnStr += "2";
  338. break;
  339. case "33":
  340. ReturnStr += "3";
  341. break;
  342. case "34":
  343. ReturnStr += "4";
  344. break;
  345. case "35":
  346. ReturnStr += "5";
  347. break;
  348. case "36":
  349. ReturnStr += "6";
  350. break;
  351. case "37":
  352. ReturnStr += "7";
  353. break;
  354. case "38":
  355. ReturnStr += "8";
  356. break;
  357. case "39":
  358. ReturnStr += "9";
  359. break;
  360. case "41":
  361. ReturnStr += "A";
  362. break;
  363. case "42":
  364. ReturnStr += "B";
  365. break;
  366. case "43":
  367. ReturnStr += "C";
  368. break;
  369. case "44":
  370. ReturnStr += "D";
  371. break;
  372. case "45":
  373. ReturnStr += "E";
  374. break;
  375. case "46":
  376. ReturnStr += "F";
  377. break;
  378. default:
  379. break;
  380. }
  381. }
  382. }
  383. int ValueDataSize = Convert.ToInt32("0x" + (ReturnStr.Substring(4, 2)), 16) * 2;
  384. return ReturnStr.ToUpper().Substring(0, ValueDataSize + 6 + 2);//首部6位和尾部2位校验位
  385. }
  386. public static int[] GetDecimalData(string HexStr, int DataSize)
  387. {
  388. Console.WriteLine(HexStr);
  389. List<int> ReturnData = new List<int>();
  390. try
  391. {
  392. //去除前面的指令字符和数据长度字符
  393. HexStr = HexStr.Replace(":", "");
  394. if (HexStr != "")
  395. {
  396. int ValueDataSize = Convert.ToInt32("0x" + (HexStr.Substring(4, 2)), 16) * 2;
  397. string RealData = HexStr.Substring(6);
  398. RealData = RealData.Substring(0, ValueDataSize);
  399. //每个地址位存的数据是DataSize个
  400. for (int i = 0; i < RealData.Length; i = i + DataSize)
  401. {
  402. if (i + DataSize <= RealData.Length)
  403. {
  404. //低位在前,高位在后返回2710 0000,转换0000 2710
  405. string Low = RealData.Substring(i, DataSize).Substring(4, 4);
  406. string High = RealData.Substring(i, DataSize).Substring(0, 4);
  407. //Console.WriteLine(Convert.ToInt32("0x" + Low + High, 16));
  408. ReturnData.Add(Convert.ToInt32("0x" + Low + High, 16));
  409. }
  410. }
  411. }
  412. }
  413. catch (Exception ex)
  414. {
  415. Console.WriteLine(ex.Message + ex.StackTrace);
  416. }
  417. return ReturnData.ToArray();
  418. }
  419. public static void SetCacheData(string ParamName, object Value)
  420. {
  421. try
  422. {
  423. //根据地址读取xml文件
  424. XmlDocument doc = new XmlDocument();
  425. XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
  426. //忽略文档里面的注释
  427. settings.IgnoreComments = true;
  428. XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
  429. doc.Load(reader);
  430. //先得到根节点
  431. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  432. //再由根节点去找制定的节点
  433. XmlNodeList nodeList = rootNode.ChildNodes;
  434. bool flag = false;
  435. foreach (XmlNode node in nodeList)
  436. {
  437. //找到了这个节点名字
  438. if (node.Name == ParamName)
  439. {
  440. //就直接赋值
  441. node.InnerText = Value.ToString();
  442. flag = true;
  443. }
  444. }
  445. //如果没有该节点,就创建节点保存结果
  446. if (!flag)
  447. {
  448. //创建节点
  449. XmlElement newNode = doc.CreateElement(ParamName);
  450. XmlAttribute attr = doc.CreateAttribute("Type");
  451. attr.InnerText = Value.GetType().ToString();
  452. newNode.InnerText = Value.ToString();
  453. newNode.SetAttributeNode(attr);
  454. //讲新建的节点挂到根节点上
  455. rootNode.AppendChild(newNode);
  456. }
  457. //关闭Reader
  458. reader.Close();
  459. doc.Save(SystemInf.CacheFilePath);
  460. }
  461. catch (Exception e)
  462. {
  463. LogManager.DoLog(e.Message);
  464. }
  465. }
  466. public static Object GetCacheData(string ParamName)
  467. {
  468. try
  469. {
  470. Object o = null;
  471. //根据地址读取xml文件
  472. XmlDocument doc = new XmlDocument();
  473. XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
  474. //忽略文档里面的注释
  475. settings.IgnoreComments = true;
  476. XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
  477. doc.Load(reader);
  478. //先得到根节点
  479. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  480. //再由根节点去找制定的节点
  481. XmlNodeList nodeList = rootNode.ChildNodes;
  482. foreach (XmlNode node in nodeList)
  483. {
  484. //找到了这个节点名字
  485. if (node.Name == ParamName)
  486. {
  487. //返回节点的内容
  488. switch (((XmlElement)node).GetAttribute("Type"))
  489. {
  490. case "System.String":
  491. o = node.InnerText;
  492. break;
  493. case "System.Int32":
  494. o = int.Parse(node.InnerText);
  495. break;
  496. case "System.Boolean":
  497. o = node.InnerText == "True" ? true : false;
  498. break;
  499. case "System.Decimal":
  500. o = decimal.Parse(node.InnerText);
  501. break;
  502. default:
  503. break;
  504. }
  505. break;
  506. }
  507. }
  508. //关闭reader
  509. reader.Close();
  510. if (o == null)
  511. return "";
  512. else
  513. return o;
  514. }
  515. catch (Exception e)
  516. {
  517. LogManager.DoLog(e.Message);
  518. return "";
  519. }
  520. }
  521. /// <summary>
  522. ///
  523. /// </summary>
  524. /// <param name="Minutes"></param>
  525. /// <returns></returns>
  526. public static string MinutesToDayTime(int Minutes)
  527. {
  528. int Day = Minutes / 1440;
  529. int Hour = Minutes % 1440 / 60;
  530. int Mins = Minutes % 60;
  531. return Day + "天" + Hour + "小时" + Mins + "分钟";
  532. }
  533. public static string ArrayToString(List<string> Arr)
  534. {
  535. string str = "";
  536. for (int i = 0; i < Arr.Count; i++)
  537. {
  538. if (i != Arr.Count - 1)
  539. {
  540. str += "'" + Arr[i] + "',";
  541. }
  542. else
  543. {
  544. str += "'" + Arr[i] + "'";
  545. }
  546. }
  547. return str;
  548. }
  549. }
  550. }