using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using System.Windows.Forms; using System.Xml; using static System.Windows.Forms.Control; namespace FileWatcher { class BaseUtil { public static void ShowError(string errorMessage) { throw new Exception(errorMessage); } public static string AddField(string[] Fields) { string sql = " "; foreach (string field in Fields) sql += field + ","; return sql.Substring(0, sql.Length - 1); } static int SortByIndex(Control A, Control B) { return A.TabIndex.CompareTo(B.TabIndex); } public static void SetFormValue(ControlCollection collection, DataTable dt) { List ctl = new List(); //将控件按照索引排序 for (int i = 0; i < collection.Count; i++) { for (int j = 0; j < ctl.Count; j++) { if (!ctl.Contains(collection[i])) { if (collection[i].TabIndex > ctl[j].TabIndex) { ctl.Add(collection[i]); break; } else { ctl.Insert(j, collection[i]); break; } } } if (ctl.Count == 0) { ctl.Add(collection[i]); } } ctl.Sort(SortByIndex); //DataTable存在数据才进行赋值操作 if (dt.Rows.Count > 0) { for (int i = 0; i < ctl.Count; i++) { //如果含有子控件则进行递归调用 if (ctl[i].Controls.Count > 0) SetFormValue(ctl[i].Controls, dt); string controlName = ctl[i].Name; string controlsTag = ctl[i].Tag == null ? "" : ctl[i].Tag.ToString(); //默认给TextBox和Label赋值 if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox || ctl[i] is EnterTextBox || ctl[i] is NumericUpDown || ctl[i] is RichTextBox) { 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": ctl[i].Text = "在录入"; break; case "UNAPPROVED": ctl[i].Text = "未批准"; break; case "COMMITED": ctl[i].Text = "已提交"; break; case "APPROVE": ctl[i].Text = "已批准"; break; case "AUDITED": ctl[i].Text = "已审核"; break; case "STARTED": ctl[i].Text = "已下放"; break; case "UNCHECK": ctl[i].Text = "待检验"; break; case "CHECKING": ctl[i].Text = "检验中"; break; default: ctl[i].Text = dt.Rows[0][j].ToString(); break; } } else ctl[i].Text = dt.Rows[0][j].ToString(); } } } //对封装在GroupBox的和Panel的控件进行批量赋值 if (ctl[i] is GroupBox || ctl[i] is Panel) { for (int j = 0; j < ctl[i].Controls.Count; j++) { controlName = ctl[i].Controls[j].Name; if (ctl[i].Controls[j] is TextBox || ctl[i].Controls[j] is Label || ctl[i].Controls[j] is SearchTextBox) { for (int k = 0; k < dt.Columns.Count; k++) { if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper()) { ctl[i].Controls[j].Text = dt.Rows[0][k].ToString(); } } } } } } } //如果没有记录的话,将dt中含有的列的对应值设置为空 else { for (int i = 0; i < ctl.Count; i++) { if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox) { for (int j = 0; j < dt.Columns.Count; j++) { if (ctl[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper()) { ctl[i].Text = ""; } } } } } } public static string GetScreenSqlCondition(params Control[] Condition) { string condition = ""; //用于统计传入的控件的空值数 int EmptyControlCount = 0; for (int i = 0; i < Condition.Length; i++) { //如果Text不为空再进行条件的拼接 if (Condition[i].Text != "") { if (Condition[i] is ComboBox) { condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' )"; } else { condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' )"; } //如果不是最后要判断之后有没有空值的如果有一个Text的值不为空都需要添加and //添加了一次And之后跳出循环,因为如果后面多项有值会重复添加and for (int j = i + 1; j < Condition.Length; j++) { if (j < Condition.Length) { if (Condition[j].Text != "") { condition += " and "; break; } } } } else { EmptyControlCount = EmptyControlCount + 1; } } //如果所有的控件传入的都是空值则返回也为空 if (EmptyControlCount == Condition.Length) return ""; else condition = " where " + condition; return condition; } public static void CreateXml(string iSN, string iTestResult) { //创建XML文档 FileStream fcaches = new FileStream(iSN + ".xml", FileMode.OpenOrCreate, FileAccess.ReadWrite); fcaches.Close(); FileInfo info = new FileInfo(iSN + ".xml"); if (info.Length == 0) { XmlDocument doc = new XmlDocument(); //创建类型声明节点 XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", ""); doc.AppendChild(node); //创建根节点 XmlElement xeRoot = doc.CreateElement("cacheInfo"); doc.AppendChild(xeRoot); doc.Save(iSN + ".xml"); } } public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate) { dgv.AutoGenerateColumns = false; dgv.DataSource = dt; if (operate.Length > 0) { if (dgv.Columns[operate[0].Name] != null) { dgv.Columns.Remove(dgv.Columns[operate[0].Name]); } dgv.Columns.Add(operate[0]); } ////纯英文的列不予展示 //Regex regEnglish = new Regex("^[A-z]+$"); //foreach (DataGridViewColumn dgvc in dgv.Columns) //{ // if (regEnglish.IsMatch(dgvc.HeaderText)) // { // dgvc.Visible = false; // } //} } public static string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary dic, out string fp_path, out string fp_id) { fp_id = ""; fp_path = ""; try { ServicePointManager.DefaultConnectionLimit = 50; string boundary = DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1); request.Method = "POST"; request.Timeout = 10 * 10000; request.ContentType = "multipart/form-data; boundary=" + boundary; Stream rs = request.GetRequestStream(); var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n"; if (dic != null) { foreach (string key in dic.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, dic[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } } string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n"; { rs.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath)); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } } var cr = Encoding.UTF8.GetBytes("\r\n"); rs.Write(cr, 0, cr.Length); } rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); var response = request.GetResponse() as HttpWebResponse; StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string Content = newReader.ReadToEnd(); Dictionary dic1 = new Dictionary(); List> dic2 = null; dic1 = BaseUtil.ToDictionary(Content); dic2 = dic1["data"] as List>; if (dic2[0]["filepath"] != null) { fp_id = dic2[0]["filepath"].ToString(); fp_path = dic2[0]["path"].ToString(); } if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine(fp_id); return fp_id; } } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace); } return ""; } public static Dictionary ToDictionary(string JsonData) { object Data = null; Dictionary Dic = new Dictionary(); if (JsonData.StartsWith("[")) { //如果目标直接就为数组类型,则将会直接输出一个Key为List的List>集合 //使用示例List> ListDic = (List>)Dic["List"]; List> List = new List>(); 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>集合 //使用示例List> ListDic = (List>)Dic["Json中的Key"]; List> List = new List>(); 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; } public static Dictionary ToDictionary(string JsonData, string Type) { //实例化JavaScriptSerializer类的新实例 JavaScriptSerializer jss = new JavaScriptSerializer(); try { //将指定的 JSON 字符串转换为 Dictionary 类型的对象 return jss.Deserialize>(JsonData); } catch (Exception ex) { throw new Exception(ex.Message); } } public static object GetCacheData(string ParamName) { try { object returnData = null; //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, 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": returnData = node.InnerText; break; case "System.Int32": returnData = int.Parse(node.InnerText); break; case "System.Boolean": returnData = node.InnerText == "True" ? true : false; break; default: break; } break; } } //关闭reader reader.Close(); if (returnData == null) return ""; else return returnData; } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace); return ""; } } public static void SetCacheData(string ParamName, object Value) { try { //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, 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(AutoAnalysisXml.CachePath); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); } } //播放音频文件 public static void PlaySound(string FileName) { //要加载COM组件:Microsoft speech object Library if (!System.IO.File.Exists(FileName)) { return; } //SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass(); //SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass(); //spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true); //SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream; //pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename); //spFs.Close(); } public static void GetWriteInfo(string FilePath, out Dictionary Dic) { Dic = new Dictionary(); string txt = ""; StreamReader sr = new StreamReader(FilePath); while (!sr.EndOfStream) { string str = sr.ReadLine(); txt += str + "\n"; } sr.Close(); sr.Dispose(); Dic.Add("atd_sncode", FilePath.Substring(FilePath.LastIndexOf("\\") + 1).Replace(".txt", "")); Dic.Add("atd_software", Regex.Match(txt, "Program Name,\\S+").Value.Replace("Program Name,", "")); Dic.Add("atd_pot", Regex.Match(txt, "Board Segment,\\S+").Value.Replace("Board Segment,", "")); Dic.Add("atd_size", Regex.Match(txt, "Baord Size \\(L x W\\) \\[mm\\],\\S+").Value.Replace("Baord Size (L x W) [mm],", "")); Dic.Add("atd_pot1set", Regex.Match(txt, "Pot-1 Set Temp. \\[deg],\\S+").Value.Replace("Pot-1 Set Temp. [deg],", "")); Dic.Add("atd_pot2set", Regex.Match(txt, "Pot-2 Set Temp. \\[deg],\\S+").Value.Replace("Pot-2 Set Temp. [deg],", "")); Dic.Add("atd_pot1avgtemp", Regex.Match(txt, "Pot-1 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-1 Avg. Temp. [deg],", "")); Dic.Add("atd_pot2avgtemp", Regex.Match(txt, "Pot-2 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-2 Avg. Temp. [deg],", "")); Dic.Add("atd_boardtime", Regex.Match(txt, "Machine Duration \\[s],\\S+").Value.Replace("Machine Duration [s],", "")); //开始时间 MatchCollection starttime = Regex.Matches(txt, "Start TimeStamp,\\S+ \\S+"); for (int i = 0; i < starttime.Count; i++) { switch (i) { case 0: Dic.Add("atd_boardstarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; case 1: Dic.Add("atd_flstarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; case 2: Dic.Add("atd_phstarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; case 3: Dic.Add("atd_sostarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; default: break; } } MatchCollection endtime = Regex.Matches(txt, "End TimeStamp,\\S+ \\S+"); for (int i = 0; i < starttime.Count; i++) { switch (i) { case 0: Dic.Add("atd_boardendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; case 1: Dic.Add("atd_flendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; case 2: Dic.Add("atd_phendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; case 3: Dic.Add("atd_soendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; default: break; } } MatchCollection duration = Regex.Matches(txt, "Total Zone Duration \\[s],\\S+"); for (int i = 0; i < starttime.Count; i++) { switch (i) { case 0: Dic.Add("atd_fltime", duration[i].Value.Replace("Total Zone Duration [s],", "")); break; case 1: Dic.Add("atd_phtime", duration[i].Value.Replace("Total Zone Duration [s],", "")); break; case 2: Dic.Add("atd_sotime", duration[i].Value.Replace("Total Zone Duration [s],", "")); break; default: break; } } } } }