123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607 |
- 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<Control> ctl = new List<Control>();
- //将控件按照索引排序
- 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<string, object> 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<string, object> dic1 = new Dictionary<string, object>();
- List<Dictionary<string, object>> dic2 = null;
- dic1 = BaseUtil.ToDictionary(Content);
- dic2 = dic1["data"] as List<Dictionary<string, object>>;
- 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<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;
- }
- public static Dictionary<string, object> ToDictionary(string JsonData, string Type)
- {
- //实例化JavaScriptSerializer类的新实例
- JavaScriptSerializer jss = new JavaScriptSerializer();
- try
- {
- //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
- return jss.Deserialize<Dictionary<string, object>>(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<string, string> Dic)
- {
- Dic = new Dictionary<string, string>();
- 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;
- }
- }
- }
- }
- }
|