123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575 |
- using DevExpress.XtraEditors;
- using DevExpress.XtraEditors.Repository;
- using System;
- using System.Data;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Windows.Forms;
- using UAS_PLCDataReader.DataOperate;
- using DevExpress.Utils;
- using UAS_PLCDataReader.CustomerControl.ValueLabel;
- using System.Collections.Generic;
- using System.Xml;
- using UAS_PLCDataReader.Entity;
- using System.Text.RegularExpressions;
- namespace UAS_PLCDataReader.PublicMethod
- {
- class BaseUtil
- {
- [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
- public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
- public static void FillComBoxEditWidthDataTable(RepositoryItemComboBox combo, string TextField, string ValueField, DataTable dt)
- {
- combo.Items.Clear();
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- ComboBoxData item = new ComboBoxData();
- item.Value = dt.Rows[i][ValueField].ToString();
- item.Text = dt.Rows[i][TextField].ToString();
- combo.Items.Add(item);
- }
- }
- public static void FillComBoxEditWidthDataTable(ComboBoxEdit combo, string TextField, string ValueField, DataTable dt)
- {
- combo.Properties.Items.Clear();
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- ComboBoxData item = new ComboBoxData();
- item.Value = dt.Rows[i][ValueField].ToString();
- item.Text = dt.Rows[i][TextField].ToString();
- combo.Properties.Items.Add(item);
- }
- combo.SelectedIndex = 0;
- }
- public static void FillComBoxEditWidthDataTable(ComboBoxEdit combo, string TextField, string ValueField, DataTable dt, bool AddAll)
- {
- combo.Properties.Items.Clear();
- if (AddAll)
- {
- ComboBoxData item = new ComboBoxData();
- item.Value = "全部";
- item.Text = "全部";
- combo.Properties.Items.Add(item);
- }
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- ComboBoxData item = new ComboBoxData();
- item.Value = dt.Rows[i][ValueField].ToString();
- item.Text = dt.Rows[i][TextField].ToString();
- combo.Properties.Items.Add(item);
- }
- combo.SelectedIndex = 0;
- }
- public static DataTable ToDataTable(DataRow[] rows)
- {
- if (rows == null || rows.Length == 0) return new DataTable();
- DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
- foreach (DataRow row in rows)
- tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
- return tmp;
- }
- public static string GetComboxEditValue(ComboBoxEdit ComBox)
- {
- if (ComBox.SelectedItem == null)
- return ComBox.Text;
- else
- return (ComBox.SelectedItem as ComboBoxData).Value;
- }
- public static Dictionary<string, object> ToDictionary(string JsonData)
- {
- object Data = null;
- Dictionary<string, object> Dic = new Dictionary<string, object>();
- if (JsonData.StartsWith("["))
- {
- //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
- //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
- List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
- MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
- foreach (Match ListItem in ListMatch)
- {
- List.Add(ToDictionary(ListItem.ToString()));//递归调用
- }
- Data = List;
- Dic.Add("List", Data);
- }
- else
- {
- MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
- foreach (Match item in Match)
- {
- try
- {
- if (item.Groups[2].ToString().StartsWith("["))
- {
- //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
- //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
- List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
- MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
- foreach (Match ListItem in ListMatch)
- {
- List.Add(ToDictionary(ListItem.ToString()));//递归调用
- }
- Data = List;
- }
- else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
- else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
- Dic.Add(item.Groups[1].ToString(), Data);
- }
- catch { }
- }
- }
- return Dic;
- }
- /// <summary>
- /// 获取LRC
- /// </summary>
- /// <param name="SQL"></param>
- public static string getLRC(string SENDMESSAGE)
- {
- string message = SENDMESSAGE.Trim();
- if (message.Length % 2 != 0)
- {
- message = message + "0";
- }
- int LRC = 0x0;
- for (int i = 0; i < message.Length; i = i + 2)
- {
- int inside = int.Parse(message.Substring(i, 1).ToString() + message.Substring(i + 1, 1).ToString(), System.Globalization.NumberStyles.HexNumber);
- LRC += inside;
- }
- string _LRC = string.Format("{0:X2}", LRC);
- string LRCre = "";
- for (int i = 0; i < _LRC.Length; i++)
- {
- int index;
- index = 0xF - int.Parse(_LRC.Substring(i, 1).ToString(), System.Globalization.NumberStyles.HexNumber);
- LRCre += string.Format("{0:X}", index);
- }
- LRCre = string.Format("{0:X}", int.Parse(LRCre, System.Globalization.NumberStyles.HexNumber) + 1);
- return LRCre;
- }
- public static string ByteToHexadecimalString(byte[] b, int length)
- {
- string returnStr = "";
- if (b != null)
- {
- for (int i = 0; i < length; i++)
- {
- returnStr += Convert.ToString(b[i], 16);//ToString("X2") 为C#中的字符串格式控制符
- }
- }
- return returnStr.ToUpper();
- }
- public static void CleanMemory()
- {
- GC.Collect();
- GC.WaitForPendingFinalizers();
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- {
- SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
- }
- }
- private static ToolTipControllerShowEventArgs args;
- public static ToolTipController MyToolTipClt { get; private set; }
- public static void NewToolTip(Control ctl, string title, string content, int showTime, ToolTipType toolTipType, ToolTipLocation tipLocation, bool isAutoHide, ToolTipIconType tipIconType, ImageList imgList, int imgIndex)
- {
- try
- {
- MyToolTipClt = new ToolTipController();
- args = MyToolTipClt.CreateShowArgs();
- content = (string.IsNullOrEmpty(content) ? "???" : content);
- title = string.IsNullOrEmpty(title) ? "温馨提示" : title;
- MyToolTipClt.ImageList = imgList;
- MyToolTipClt.ImageIndex = (imgList == null ? 0 : imgIndex);
- args.AutoHide = isAutoHide;
- MyToolTipClt.ShowBeak = true;
- MyToolTipClt.ShowShadow = true;
- MyToolTipClt.Rounded = true;
- MyToolTipClt.AutoPopDelay = (showTime == 0 ? 2000 : showTime);
- MyToolTipClt.SetToolTip(ctl, content);
- MyToolTipClt.SetTitle(ctl, title);
- MyToolTipClt.SetToolTipIconType(ctl, tipIconType);
- MyToolTipClt.Active = true;
- MyToolTipClt.HideHint();
- MyToolTipClt.ShowHint(content, title, ctl, tipLocation);
- }
- catch (Exception)
- {
- }
- }
- /// <summary>
- /// 检测键值对是否发生值的变化
- /// </summary>
- public static bool CheckDicDiff(Dictionary<string, string> A, Dictionary<string, string> B)
- {
- foreach (var item in B)
- {
- //不对比产量和产出
- if (A.ContainsKey(item.Key) && (Main.inqty == "-1" || Main.outqty == "-1" || Main.param == "-1"))
- {
- if (A[item.Key] != item.Value)
- {
- return true;
- }
- }
- }
- return false;
- }
- /// <summary>
- /// 传入控件的集合和DataTable,通过判断控件的名称和数据源的列的描述来匹配,支持单层的GroupBox和Panel
- /// </summary>
- /// <param name="collection"></param>
- /// <param name="dt"></param>
- public static void SetFormValue(Control.ControlCollection collection, DataTable dt)
- {
- //DataTable存在数据才进行赋值操作
- if (dt.Rows.Count > 0)
- {
- for (int i = 0; i < collection.Count; i++)
- {
- //如果含有子控件则进行递归调用
- if (collection[i].Controls.Count > 0)
- SetFormValue(collection[i].Controls, dt);
- string controlName = collection[i].Name;
- string controlsTag = collection[i].Tag == null ? "" : collection[i].Tag.ToString();
- //默认给TextBox和Label赋值
- if (collection[i] is TextBox || collection[i] is ValueLabel || collection[i] is NumericUpDown)
- {
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper() || controlsTag.ToUpper() == dt.Columns[j].Caption.ToUpper())
- {
- //字段含有Status内容的才进行转换
- if (controlName.ToUpper().Contains("STATUS") || controlsTag.ToUpper().Contains("STATUS"))
- {
- //对审批状态进行判断
- switch (dt.Rows[0][j].ToString().ToUpper())
- {
- case "ENTERING":
- collection[i].Text = "在录入";
- break;
- case "UNAPPROVED":
- collection[i].Text = "未批准";
- break;
- case "COMMITED":
- collection[i].Text = "已提交";
- break;
- case "APPROVE":
- collection[i].Text = "已批准";
- break;
- case "AUDITED":
- collection[i].Text = "已审核";
- break;
- case "STARTED":
- collection[i].Text = "已下放";
- break;
- case "UNCHECK":
- collection[i].Text = "待检验";
- break;
- case "CHECKING":
- collection[i].Text = "检验中";
- break;
- default:
- collection[i].Text = dt.Rows[0][j].ToString();
- break;
- }
- }
- else
- collection[i].Text = dt.Rows[0][j].ToString();
- }
- }
- }
- //对封装在GroupBox的和Panel的控件进行批量赋值
- if (collection[i] is GroupControl || collection[i] is Panel)
- {
- for (int j = 0; j < collection[i].Controls.Count; j++)
- {
- controlName = collection[i].Controls[j].Name;
- if (collection[i].Controls[j] is TextBox || collection[i].Controls[j] is ValueLabel)
- {
- for (int k = 0; k < dt.Columns.Count; k++)
- {
- if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
- {
- collection[i].Controls[j].Text = dt.Rows[0][k].ToString();
- }
- }
- }
- }
- }
- }
- }
- //如果没有记录的话,将dt中含有的列的对应值设置为空
- else
- {
- for (int i = 0; i < collection.Count; i++)
- {
- if (collection[i] is TextBox || collection[i] is ValueLabel)
- {
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (collection[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
- {
- collection[i].Text = "";
- }
- }
- }
- }
- }
- }
- public static string ASCIIToString(string ASCII)
- {
- string ReturnStr = "";
- ASCII = ASCII.Replace(" ", "").Replace("3A", "").Replace("DA", "").Replace("0D", "").Replace("0A", "");
- for (int i = 0; i <= ASCII.Length; i = i + 2)
- {
- if (i + 2 <= ASCII.Length)
- {
- switch (ASCII.Substring(i, 2))
- {
- case "30":
- ReturnStr += "0";
- break;
- case "31":
- ReturnStr += "1";
- break;
- case "32":
- ReturnStr += "2";
- break;
- case "33":
- ReturnStr += "3";
- break;
- case "34":
- ReturnStr += "4";
- break;
- case "35":
- ReturnStr += "5";
- break;
- case "36":
- ReturnStr += "6";
- break;
- case "37":
- ReturnStr += "7";
- break;
- case "38":
- ReturnStr += "8";
- break;
- case "39":
- ReturnStr += "9";
- break;
- case "41":
- ReturnStr += "A";
- break;
- case "42":
- ReturnStr += "B";
- break;
- case "43":
- ReturnStr += "C";
- break;
- case "44":
- ReturnStr += "D";
- break;
- case "45":
- ReturnStr += "E";
- break;
- case "46":
- ReturnStr += "F";
- break;
- default:
- break;
- }
- }
- }
- int ValueDataSize = Convert.ToInt32("0x" + (ReturnStr.Substring(4, 2)), 16) * 2;
- return ReturnStr.ToUpper().Substring(0, ValueDataSize + 6 + 2);//首部6位和尾部2位校验位
- }
- public static int[] GetDecimalData(string HexStr, int DataSize)
- {
- Console.WriteLine(HexStr);
- List<int> ReturnData = new List<int>();
- try
- {
- //去除前面的指令字符和数据长度字符
- HexStr = HexStr.Replace(":", "");
- if (HexStr != "")
- {
- int ValueDataSize = Convert.ToInt32("0x" + (HexStr.Substring(4, 2)), 16) * 2;
- string RealData = HexStr.Substring(6);
- RealData = RealData.Substring(0, ValueDataSize);
- //每个地址位存的数据是DataSize个
- for (int i = 0; i < RealData.Length; i = i + DataSize)
- {
- if (i + DataSize <= RealData.Length)
- {
- //低位在前,高位在后返回2710 0000,转换0000 2710
- string Low = RealData.Substring(i, DataSize).Substring(4, 4);
- string High = RealData.Substring(i, DataSize).Substring(0, 4);
- //Console.WriteLine(Convert.ToInt32("0x" + Low + High, 16));
- ReturnData.Add(Convert.ToInt32("0x" + Low + High, 16));
- }
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message + ex.StackTrace);
- }
- return ReturnData.ToArray();
- }
- public static void SetCacheData(string ParamName, object Value)
- {
- try
- {
- //根据地址读取xml文件
- XmlDocument doc = new XmlDocument();
- XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
- //忽略文档里面的注释
- settings.IgnoreComments = true;
- XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
- doc.Load(reader);
- //先得到根节点
- XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
- //再由根节点去找制定的节点
- XmlNodeList nodeList = rootNode.ChildNodes;
- bool flag = false;
- foreach (XmlNode node in nodeList)
- {
- //找到了这个节点名字
- if (node.Name == ParamName)
- {
- //就直接赋值
- node.InnerText = Value.ToString();
- flag = true;
- }
- }
- //如果没有该节点,就创建节点保存结果
- if (!flag)
- {
- //创建节点
- XmlElement newNode = doc.CreateElement(ParamName);
- XmlAttribute attr = doc.CreateAttribute("Type");
- attr.InnerText = Value.GetType().ToString();
- newNode.InnerText = Value.ToString();
- newNode.SetAttributeNode(attr);
- //讲新建的节点挂到根节点上
- rootNode.AppendChild(newNode);
- }
- //关闭Reader
- reader.Close();
- doc.Save(SystemInf.CacheFilePath);
- }
- catch (Exception e)
- {
- LogManager.DoLog(e.Message);
- }
- }
- public static Object GetCacheData(string ParamName)
- {
- try
- {
- Object o = null;
- //根据地址读取xml文件
- XmlDocument doc = new XmlDocument();
- XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
- //忽略文档里面的注释
- settings.IgnoreComments = true;
- XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
- doc.Load(reader);
- //先得到根节点
- XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
- //再由根节点去找制定的节点
- XmlNodeList nodeList = rootNode.ChildNodes;
- foreach (XmlNode node in nodeList)
- {
- //找到了这个节点名字
- if (node.Name == ParamName)
- {
- //返回节点的内容
- switch (((XmlElement)node).GetAttribute("Type"))
- {
- case "System.String":
- o = node.InnerText;
- break;
- case "System.Int32":
- o = int.Parse(node.InnerText);
- break;
- case "System.Boolean":
- o = node.InnerText == "True" ? true : false;
- break;
- case "System.Decimal":
- o = decimal.Parse(node.InnerText);
- break;
- default:
- break;
- }
- break;
- }
- }
- //关闭reader
- reader.Close();
- if (o == null)
- return "";
- else
- return o;
- }
- catch (Exception e)
- {
- LogManager.DoLog(e.Message);
- return "";
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="Minutes"></param>
- /// <returns></returns>
- public static string MinutesToDayTime(int Minutes)
- {
- int Day = Minutes / 1440;
- int Hour = Minutes % 1440 / 60;
- int Mins = Minutes % 60;
- return Day + "天" + Hour + "小时" + Mins + "分钟";
- }
- public static string ArrayToString(List<string> Arr)
- {
- string str = "";
- for (int i = 0; i < Arr.Count; i++)
- {
- if (i != Arr.Count - 1)
- {
- str += "'" + Arr[i] + "',";
- }
- else
- {
- str += "'" + Arr[i] + "'";
- }
- }
- return str;
- }
- }
- }
|