BaseUtil.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. using LabelManager2;
  2. using Seagull.BarTender.Print;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Diagnostics;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Sockets;
  14. using System.Reflection;
  15. using System.Text;
  16. using System.Text.RegularExpressions;
  17. using System.Threading;
  18. using System.Windows.Forms;
  19. using System.Windows.Forms.DataVisualization.Charting;
  20. using System.Xml;
  21. using UAS_MES_NEW.CustomControl.DataGrid_View;
  22. using UAS_MES_NEW.CustomControl.GroupBoxWithBorder;
  23. using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
  24. using UAS_MES_NEW.CustomControl.ValueLabel;
  25. using UAS_MES_NEW.Entity;
  26. using static System.Windows.Forms.Control;
  27. namespace UAS_MES_NEW.PublicMethod
  28. {
  29. class BaseUtil
  30. {
  31. /// <summary>
  32. /// 检测TCP连接是否存在还是已经中断
  33. /// </summary>
  34. /// <param name="c"></param>
  35. /// <returns></returns>
  36. public static bool IsOnline(TcpClient c)
  37. {
  38. return !((c.Client.Poll(1000, SelectMode.SelectRead) && (c.Client.Available == 0)) || !c.Client.Connected);
  39. }
  40. public static Dictionary<string, object> ToDictionary(string JsonData)
  41. {
  42. object Data = null;
  43. Dictionary<string, object> Dic = new Dictionary<string, object>();
  44. if (JsonData.StartsWith("["))
  45. {
  46. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  47. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  48. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  49. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  50. foreach (Match ListItem in ListMatch)
  51. {
  52. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  53. }
  54. Data = List;
  55. Dic.Add("List", Data);
  56. }
  57. else
  58. {
  59. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  60. foreach (Match item in Match)
  61. {
  62. try
  63. {
  64. if (item.Groups[2].ToString().StartsWith("["))
  65. {
  66. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  67. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  68. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  69. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  70. foreach (Match ListItem in ListMatch)
  71. {
  72. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  73. }
  74. Data = List;
  75. }
  76. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  77. else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
  78. Dic.Add(item.Groups[1].ToString(), Data);
  79. }
  80. catch { }
  81. }
  82. }
  83. return Dic;
  84. }
  85. /// <summary>
  86. /// 通过DataTable的ColumnName和Caption来拼接一条语句
  87. /// </summary>
  88. /// <param name=""></param>
  89. /// <returns></returns>
  90. public static string GetGridViewSelectContent(DataGridView d)
  91. {
  92. StringBuilder selectConetnt = new StringBuilder();
  93. DataTable dt = (DataTable)d.DataSource;
  94. if (dt == null)
  95. {
  96. foreach (DataGridViewColumn dc in d.Columns)
  97. {
  98. if (dc.DataPropertyName != "" && dc.DataPropertyName != null)
  99. {
  100. selectConetnt.Append(dc.Name + " as " + dc.Name + ",");
  101. }
  102. }
  103. }
  104. else
  105. {
  106. foreach (DataColumn dc in dt.Columns)
  107. {
  108. selectConetnt.Append(dc.Caption + " as " + dc.ColumnName + ",");
  109. }
  110. }
  111. return selectConetnt.Remove(selectConetnt.Length - 1, 1).ToString();
  112. }
  113. /// <summary>
  114. /// 禁止DataGirdView排序
  115. /// </summary>
  116. /// <param name="Dgv"></param>
  117. public static void DataGridViewNotSort(DataGridView Dgv)
  118. {
  119. foreach (DataGridViewColumn item in Dgv.Columns)
  120. item.SortMode = DataGridViewColumnSortMode.NotSortable;
  121. }
  122. public static string GetLocalIP()
  123. {
  124. try
  125. {
  126. string HostName = Dns.GetHostName(); //得到主机名
  127. IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
  128. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  129. {
  130. //从IP地址列表中筛选出IPv4类型的IP地址
  131. //AddressFamily.InterNetwork表示此IP为IPv4,
  132. //AddressFamily.InterNetworkV6表示此地址为IPv6类型
  133. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  134. {
  135. return IpEntry.AddressList[i].ToString();
  136. }
  137. }
  138. return "";
  139. }
  140. catch (Exception ex)
  141. {
  142. MessageBox.Show("获取本机IP出错:" + ex.Message);
  143. return "";
  144. }
  145. }
  146. /// <summary>
  147. /// 通过字段和其展示的中文值获取查询的内容
  148. /// </summary>
  149. /// <param name="field"></param>
  150. /// <param name="cnfield"></param>
  151. /// <returns></returns>
  152. public static string GetSelectContentByStringArray(string[] field, string[] cnfield)
  153. {
  154. StringBuilder sb = new StringBuilder();
  155. for (int i = 0; i < field.Length; i++)
  156. {
  157. sb.Append(field[i] + " as " + cnfield[i] + ",");
  158. }
  159. //去掉多余的逗号
  160. sb.Remove(sb.Length - 1, 1);
  161. return sb.ToString();
  162. }
  163. static int SortByIndex(Control A, Control B)
  164. {
  165. return A.TabIndex.CompareTo(B.TabIndex);
  166. }
  167. /// <summary>
  168. /// 传入控件的集合和DataTable,通过判断控件的名称和数据源的列的描述来匹配,支持单层的GroupBox和Panel
  169. /// </summary>
  170. /// <param name="collection"></param>
  171. /// <param name="dt"></param>
  172. public static void SetFormValue(ControlCollection collection, DataTable dt)
  173. {
  174. List<Control> ctl = new List<Control>();
  175. //将控件按照索引排序
  176. for (int i = 0; i < collection.Count; i++)
  177. {
  178. for (int j = 0; j < ctl.Count; j++)
  179. {
  180. if (!ctl.Contains(collection[i]))
  181. {
  182. if (collection[i].TabIndex > ctl[j].TabIndex)
  183. {
  184. ctl.Add(collection[i]);
  185. break;
  186. }
  187. else
  188. {
  189. ctl.Insert(j, collection[i]);
  190. break;
  191. }
  192. }
  193. }
  194. if (ctl.Count == 0)
  195. {
  196. ctl.Add(collection[i]);
  197. }
  198. }
  199. ctl.Sort(SortByIndex);
  200. //DataTable存在数据才进行赋值操作
  201. if (dt.Rows.Count > 0)
  202. {
  203. for (int i = 0; i < ctl.Count; i++)
  204. {
  205. //如果含有子控件则进行递归调用
  206. if (ctl[i].Controls.Count > 0)
  207. SetFormValue(ctl[i].Controls, dt);
  208. string controlName = ctl[i].Name;
  209. string controlsTag = ctl[i].Tag == null ? "" : ctl[i].Tag.ToString();
  210. //默认给TextBox和Label赋值
  211. if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox || ctl[i] is MaCodeSearchTextBox || ctl[i] is EnterTextBox || ctl[i] is TextBoxGeneratePaCode || ctl[i] is NumericUpDown || ctl[i] is TextBoxWithTextArea || ctl[i] is RichTextBox)
  212. {
  213. for (int j = 0; j < dt.Columns.Count; j++)
  214. {
  215. if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper() || controlsTag.ToUpper() == dt.Columns[j].Caption.ToUpper())
  216. {
  217. //字段含有Status内容的才进行转换
  218. if (controlName.ToUpper().Contains("STATUS") || controlsTag.ToUpper().Contains("STATUS"))
  219. {
  220. //对审批状态进行判断
  221. switch (dt.Rows[0][j].ToString().ToUpper())
  222. {
  223. case "ENTERING":
  224. ctl[i].Text = "在录入";
  225. break;
  226. case "UNAPPROVED":
  227. ctl[i].Text = "未批准";
  228. break;
  229. case "COMMITED":
  230. ctl[i].Text = "已提交";
  231. break;
  232. case "APPROVE":
  233. ctl[i].Text = "已批准";
  234. break;
  235. case "AUDITED":
  236. ctl[i].Text = "已审核";
  237. break;
  238. case "STARTED":
  239. ctl[i].Text = "已下放";
  240. break;
  241. case "UNCHECK":
  242. ctl[i].Text = "待检验";
  243. break;
  244. case "CHECKING":
  245. ctl[i].Text = "检验中";
  246. break;
  247. default:
  248. ctl[i].Text = dt.Rows[0][j].ToString();
  249. break;
  250. }
  251. }
  252. else
  253. ctl[i].Text = dt.Rows[0][j].ToString();
  254. }
  255. }
  256. }
  257. //对封装在GroupBox的和Panel的控件进行批量赋值
  258. if (ctl[i] is GroupBox || ctl[i] is Panel || ctl[i] is GroupBoxWithBorder)
  259. {
  260. for (int j = 0; j < ctl[i].Controls.Count; j++)
  261. {
  262. controlName = ctl[i].Controls[j].Name;
  263. if (ctl[i].Controls[j] is TextBox || ctl[i].Controls[j] is Label || ctl[i].Controls[j] is SearchTextBox || ctl[i].Controls[j] is MaCodeSearchTextBox)
  264. {
  265. for (int k = 0; k < dt.Columns.Count; k++)
  266. {
  267. if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
  268. {
  269. ctl[i].Controls[j].Text = dt.Rows[0][k].ToString();
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
  276. }
  277. //如果没有记录的话,将dt中含有的列的对应值设置为空
  278. else
  279. {
  280. for (int i = 0; i < ctl.Count; i++)
  281. {
  282. if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox)
  283. {
  284. for (int j = 0; j < dt.Columns.Count; j++)
  285. {
  286. if (ctl[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
  287. {
  288. ctl[i].Text = "";
  289. }
  290. }
  291. }
  292. }
  293. }
  294. }
  295. /// <summary>
  296. /// 获取打印标签
  297. /// </summary>
  298. /// <param name="labelName"></param>
  299. /// <param name="labelUrl"></param>
  300. /// <param name="indate"></param>
  301. public static void GetPrintLabel(string labelName, string labelUrl)
  302. {
  303. BaseUtil.GetLabelUrl(labelUrl, labelName);
  304. }
  305. /// <summary>
  306. /// 获取打印标签
  307. /// </summary>
  308. /// <param name="labelName"></param>
  309. /// <param name="labelUrl"></param>
  310. /// <param name="indate"></param>
  311. public static void GetPrintLabel(string labelName, string labelUrl, string indate)
  312. {
  313. string LabelUrl = labelUrl;
  314. string LabelName = labelName;
  315. System.DateTime time = Convert.ToDateTime(indate);
  316. FileInfo file = new FileInfo(ftpOperater.DownLoadTo + LabelName);
  317. if (time.ToString() != file.LastWriteTime.ToString())
  318. BaseUtil.GetLabelUrl(LabelUrl, LabelName, time);
  319. }
  320. /// <summary>
  321. /// 获取标签的路径
  322. /// </summary>
  323. /// <param name="URL"></param>
  324. /// <param name="LabelName"></param>
  325. /// <param name="time"></param>
  326. /// <returns></returns>
  327. public static string GetLabelUrl(string URL, string LabelName, System.DateTime time)
  328. {
  329. ftpOperater ftp = new ftpOperater();
  330. return ftp.DownLoadFromSharePath(URL, LabelName);
  331. }
  332. /// <summary>
  333. /// 移除重复行
  334. /// </summary>
  335. /// <param name="dt"></param>
  336. /// <param name="field"></param>
  337. /// <returns></returns>
  338. public static DataTable DeleteSameRow(DataTable dt, string field)
  339. {
  340. ArrayList indexList = new ArrayList();
  341. // 找出待删除的行索引
  342. for (int i = 0; i < dt.Rows.Count - 1; i++)
  343. {
  344. if (!IsContain(indexList, i))
  345. {
  346. for (int j = i + 1; j < dt.Rows.Count; j++)
  347. {
  348. if (dt.Rows[i][field].ToString() == dt.Rows[j][field].ToString())
  349. {
  350. indexList.Add(j);
  351. }
  352. }
  353. }
  354. }
  355. indexList.Sort();
  356. // 排序
  357. for (int i = indexList.Count - 1; i >= 0; i--)// 根据待删除索引列表删除行
  358. {
  359. int index = Convert.ToInt32(indexList[i]);
  360. dt.Rows.RemoveAt(index);
  361. }
  362. return dt;
  363. }
  364. /// <summary>
  365. /// 判断数组中是否存在
  366. /// </summary>
  367. /// <param name="indexList">数组</param>
  368. /// <param name="index">索引</param>
  369. /// <returns></returns>
  370. public static bool IsContain(ArrayList indexList, int index)
  371. {
  372. for (int i = 0; i < indexList.Count; i++)
  373. {
  374. int tempIndex = Convert.ToInt32(indexList[i]);
  375. if (tempIndex == index)
  376. {
  377. return true;
  378. }
  379. }
  380. return false;
  381. }
  382. //播放音频文件
  383. public static void PlaySound(string FileName)
  384. {
  385. //要加载COM组件:Microsoft speech object Library
  386. if (!System.IO.File.Exists(FileName))
  387. {
  388. return;
  389. }
  390. SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
  391. SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
  392. spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
  393. SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
  394. pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
  395. spFs.Close();
  396. }
  397. /// <summary>
  398. /// 从DGV获取指定的列的数据形式是数组的形式
  399. /// </summary>
  400. public static ArrayList[] GetColumnDataFromDGV(DataGridView dgv, string[] ColumnName)
  401. {
  402. ArrayList[] array = new ArrayList[ColumnName.Length];
  403. //实例化和查询参数个数一样的ArrayList
  404. for (int i = 0; i < ColumnName.Length; i++)
  405. {
  406. array[i] = new ArrayList();
  407. }
  408. DataTable dt = (DataTable)dgv.DataSource;
  409. //如果第一列是否选框的话
  410. if (dgv.Columns[0] is DataGridViewCheckBoxColumn)
  411. {
  412. for (int i = 0; i < dt.Rows.Count; i++)
  413. {
  414. if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
  415. {
  416. for (int j = 0; j < ColumnName.Length; j++)
  417. {
  418. array[j].Add(dt.Rows[i][ColumnName[j]]);
  419. }
  420. }
  421. }
  422. }
  423. //否则直接获取全部的数据
  424. else
  425. {
  426. for (int i = 0; i < dgv.RowCount; i++)
  427. {
  428. for (int j = 0; j < ColumnName.Length; j++)
  429. {
  430. array[j].Add(dt.Rows[i][ColumnName[j]]);
  431. }
  432. }
  433. }
  434. return array;
  435. }
  436. /// <summary>
  437. /// 通过DataGridView和需要隐藏的字段的数组来对字段进行隐藏
  438. /// </summary>
  439. /// <param name="dgv"></param>
  440. /// <param name="field"></param>
  441. public static void HideField(DataGridView dgv, string[] field)
  442. {
  443. DataTable dt = (DataTable)dgv.DataSource;
  444. foreach (DataColumn dc in dt.Columns)
  445. {
  446. foreach (string s in field)
  447. {
  448. if (dc.Caption == s)
  449. dgv.Columns[dc.ColumnName].Visible = false;
  450. }
  451. }
  452. }
  453. /// <summary>
  454. ///
  455. /// </summary>
  456. /// <param name="dgv"></param>
  457. public static void ExpandDGVCheck(DataGridViewExpand dgv, DataGridViewCellEventArgs e)
  458. {
  459. if (e.ColumnIndex == 0 && e.RowIndex >= 0)
  460. {
  461. if (dgv.Rows[e.RowIndex] is CollapseDataGridViewRow)
  462. {
  463. int CollapseRowCount = (dgv.Rows[e.RowIndex] as CollapseDataGridViewRow).Rows.Count;
  464. if (CollapseRowCount > 0)
  465. {
  466. for (int i = (e.RowIndex + 2); i < (e.RowIndex + 1 + CollapseRowCount); i++)
  467. {
  468. try
  469. {
  470. dgv.Rows[i].Cells[0].Value = dgv.Rows[e.RowIndex].Cells[0].EditedFormattedValue;
  471. }
  472. catch (Exception) { }
  473. }
  474. }
  475. }
  476. }
  477. }
  478. /// <summary>
  479. /// 通过查询的内容获取到字段的描述
  480. /// </summary>
  481. /// <param name="field"></param>
  482. /// <returns></returns>
  483. public static string[] GetCaptionFromField(string field)
  484. {
  485. string[] caption = field.Split(',');
  486. for (int i = 0; i < caption.Length; i++)
  487. {
  488. caption[i] = caption[i].Substring(0, caption[i].LastIndexOf("as")).Trim();
  489. }
  490. return caption;
  491. }
  492. /// <summary>
  493. /// 通过查询的语句获取查询的字段
  494. /// </summary>
  495. /// <param name="field"></param>
  496. /// <returns></returns>
  497. public static string[] GetField(string field)
  498. {
  499. string[] fields = field.Split(',');
  500. for (int i = 0; i < fields.Length; i++)
  501. {
  502. fields[i] = fields[i].Substring(fields[i].LastIndexOf("as") + 2, fields[i].Length - fields[i].LastIndexOf("as") - 2).Trim();
  503. }
  504. return fields;
  505. }
  506. /// <summary>
  507. /// 通过描述取DataTable的列名,主要用于从配置中取数据
  508. /// </summary>
  509. /// <param name="dt"></param>
  510. /// <param name="caption"></param>
  511. /// <returns></returns>
  512. public static string GetColumnNameByCaption(DataTable dt, string caption)
  513. {
  514. foreach (DataColumn dc in dt.Columns)
  515. {
  516. if (dc.Caption.ToLower() == caption)
  517. {
  518. return dc.ColumnName;
  519. }
  520. }
  521. return null;
  522. }
  523. //用于封装异常,也可以用于错误的提示
  524. public static void ShowError(string errorMessage)
  525. {
  526. throw new Exception(errorMessage);
  527. }
  528. /// <summary>
  529. /// 判断控件的某个事件是否已经绑定了方法
  530. /// </summary>
  531. /// <param name="Control1"></param>
  532. /// <param name="EventName"></param>
  533. /// <returns></returns>
  534. public static bool ControlHasEvent(Control Control1, string EventName)
  535. {
  536. //需要查询的内容
  537. BindingFlags myBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  538. Assembly a = Assembly.GetAssembly(Control1.GetType());
  539. Type t = a.GetType(Control1.GetType().FullName, true);
  540. //获取控件的事件
  541. FieldInfo fi = t.GetField(EventName, myBindingFlags);
  542. EventHandlerList ehl = Control1.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).GetValue(Control1, null) as EventHandlerList;
  543. //判断事件的委托数量是否大于0
  544. if (ehl != null)
  545. {
  546. Delegate d = ehl[fi.GetValue(Control1)];
  547. if (d != null && d.GetInvocationList().Length > 0)
  548. {
  549. return true;
  550. }
  551. }
  552. return false;
  553. }
  554. /// <summary>
  555. /// 获取控件的事件列表
  556. /// </summary>
  557. /// <param name="Control1"></param>
  558. /// <returns></returns>
  559. public static FieldInfo[] GetControlsEvent(Control Control1)
  560. {
  561. BindingFlags myBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  562. Assembly a = Assembly.GetAssembly(Control1.GetType());
  563. Type t = a.GetType(Control1.GetType().FullName, true);
  564. FieldInfo[] finf = t.GetFields(myBindingFlags);
  565. return finf;
  566. }
  567. /// <summary>
  568. /// 清除DataTable的结构和数据,清除列结构时需要从最后的一列开始删
  569. /// </summary>
  570. /// <param name="dt"></param>
  571. public static void CleanDataTable(DataTable dt)
  572. {
  573. for (int i = dt.Columns.Count - 1; i >= 0; i--)
  574. dt.Columns.Remove(dt.Columns[i]);
  575. }
  576. /// <summary>
  577. /// 获取标签的路径
  578. /// </summary>
  579. /// <param name="URL"></param>
  580. /// <param name="LabelName"></param>
  581. /// <returns></returns>
  582. public static string GetLabelUrl(string URL, string LabelName)
  583. {
  584. ftpOperater ftp = new ftpOperater();
  585. return ftp.DownLoadFromSharePath(URL, LabelName);
  586. }
  587. /// <summary>
  588. /// 往DataTable中添加数据
  589. /// </summary>
  590. public static void AddDataToDataTable(DataTable dt, params string[] param)
  591. {
  592. DataRow dr = dt.NewRow();
  593. for (int i = 0; i < dt.Columns.Count; i++)
  594. {
  595. dr[dt.Columns[i].ColumnName] = param[i];
  596. }
  597. }
  598. /// <summary>
  599. /// 不清除表结构,只清除数据
  600. /// </summary>
  601. /// <param name="dt"></param>
  602. public static void CleanDataTableData(DataTable dt)
  603. {
  604. for (int i = dt.Rows.Count - 1; i >= 0; i--)
  605. {
  606. dt.Rows.Remove(dt.Rows[i]);
  607. }
  608. }
  609. /// <summary>
  610. /// 获取拼接的字段
  611. /// </summary>
  612. /// <param name="dt"></param>
  613. /// <returns></returns>
  614. public static string GetFieldFromDataTable(DataTable dt)
  615. {
  616. StringBuilder sb = new StringBuilder();
  617. foreach (DataColumn dc in dt.Columns)
  618. {
  619. sb.Append(dc.Caption + ",");
  620. }
  621. return sb.ToString().Substring(sb.ToString().Length - 1, 1);
  622. }
  623. /// <summary>
  624. /// 已经定义好的DataGridView绑定数据,operate是用来添加操作列的
  625. /// </summary>
  626. /// <param name="dgv"></param>
  627. /// <param name="dt"></param>
  628. /// <param name="AddOpetateColumn"></param>
  629. /// <param name="operate"></param>
  630. public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate)
  631. {
  632. dgv.AutoGenerateColumns = false;
  633. dgv.DataSource = dt;
  634. if (operate.Length > 0)
  635. {
  636. if (dgv.Columns[operate[0].Name] != null)
  637. {
  638. dgv.Columns.Remove(dgv.Columns[operate[0].Name]);
  639. }
  640. dgv.Columns.Add(operate[0]);
  641. }
  642. ////纯英文的列不予展示
  643. //Regex regEnglish = new Regex("^[A-z]+$");
  644. //foreach (DataGridViewColumn dgvc in dgv.Columns)
  645. //{
  646. // if (regEnglish.IsMatch(dgvc.HeaderText))
  647. // {
  648. // dgvc.Visible = false;
  649. // }
  650. //}
  651. }
  652. /// <summary>
  653. /// 清除DataGridView的数据
  654. /// </summary>
  655. /// <param name="dgv"></param>
  656. public static void CleanDGVData(DataGridView dgv)
  657. {
  658. for (int i = dgv.Rows.Count - 1; i >= 0; i--)
  659. {
  660. dgv.Rows.RemoveAt(i);
  661. }
  662. DataTable dt = dgv.DataSource as DataTable;
  663. if (dt != null)
  664. {
  665. dt.AcceptChanges();
  666. }
  667. }
  668. public static void CleanForm(Form Form)
  669. {
  670. for (int i = 0; i < Form.Controls.Count; i++)
  671. {
  672. if (Form.Controls[i].Controls.Count > 0)
  673. {
  674. CleanControls(Form.Controls[i].Controls);
  675. }
  676. if (Form.Controls[i] is EnterTextBox || Form.Controls[i] is TextBox || Form.Controls[i] is ValueLabel || Form.Controls[i] is SearchTextBox || Form.Controls[i] is ValueNumLabel || Form.Controls[i] is MaCodeSearchTextBox)
  677. Form.Controls[i].Text = "";
  678. if (Form.Controls[i] is DataGridView)
  679. CleanDGVData((DataGridView)Form.Controls[i]);
  680. }
  681. }
  682. public static void CleanControls(ControlCollection collection)
  683. {
  684. for (int i = 0; i < collection.Count; i++)
  685. {
  686. if (collection[i].Controls.Count > 0)
  687. CleanControls(collection[i].Controls);
  688. if (collection[i] is EnterTextBox || collection[i] is TextBox || collection[i] is ValueLabel || collection[i] is SearchTextBox || collection[i] is ValueNumLabel || collection[i] is MaCodeSearchTextBox)
  689. collection[i].Text = "";
  690. if (collection[i] is DataGridView)
  691. CleanDGVData((DataGridView)collection[i]);
  692. }
  693. }
  694. public static void CleanControlsText(params Control[] ctl)
  695. {
  696. foreach (Control item in ctl)
  697. item.Text = "";
  698. }
  699. /// <summary>
  700. /// 需要SQL的顺序和DGV的列的顺序一致
  701. /// </summary>
  702. /// <param name="dgv"></param>
  703. /// <param name="dt"></param>
  704. /// <param name="CheckBox"></param>
  705. public static void FillExpandDgvWithDataTable(DataGridViewExpand dgv, DataTable dt, bool CheckBox, bool CheckBoxTrue)
  706. {
  707. CleanDGVData(dgv);
  708. if (CheckBox)
  709. {
  710. for (int i = 0; i < dt.Rows.Count; i++)
  711. {
  712. CollapseDataGridViewRow collapseRow = new CollapseDataGridViewRow();
  713. collapseRow.IsCollapse = true;
  714. DataGridViewCheckBoxCell checkcell = new DataGridViewCheckBoxCell();
  715. collapseRow.Cells.Add(checkcell);
  716. checkcell.Value = CheckBoxTrue;
  717. //因为DGV中可能有空置的列多出,所以需要用DataTable的列进行循环
  718. for (int j = 0; j < dt.Columns.Count; j++)
  719. {
  720. DataGridViewTextBoxCell textcell = new DataGridViewTextBoxCell();
  721. textcell.Value = dt.Rows[i][j].ToString();
  722. collapseRow.Cells.Add(textcell);
  723. textcell.ReadOnly = true;
  724. }
  725. collapseRow.Tag = "MainRow";
  726. dgv.Rows.Add(collapseRow);
  727. }
  728. }
  729. else
  730. {
  731. for (int i = 0; i < dt.Rows.Count; i++)
  732. {
  733. CollapseDataGridViewRow collapseRow = new CollapseDataGridViewRow();
  734. collapseRow.IsCollapse = true;
  735. for (int j = 1; j <= dt.Columns.Count; j++)
  736. {
  737. DataGridViewTextBoxCell textcell = new DataGridViewTextBoxCell();
  738. textcell.Value = dt.Rows[i][j - 1].ToString();
  739. collapseRow.Cells.Add(textcell);
  740. }
  741. dgv.Rows.Add(collapseRow);
  742. collapseRow.ReadOnly = true;
  743. }
  744. }
  745. }
  746. /// <summary>
  747. /// 用于给DGV中的Combox列赋静态值
  748. /// </summary>
  749. /// <param name="dgvc"></param>
  750. /// <param name="displayField"></param>
  751. /// <param name="valueField"></param>
  752. /// <param name="Value"></param>
  753. /// <returns></returns>
  754. public static void SetDgvColumnComboxData(DataGridViewComboBoxColumn dgvc, string DataPropertyName, string displayField, string valueField, string[] Value)
  755. {
  756. DataTable dt = new DataTable();
  757. dt.Columns.Add(displayField);
  758. dt.Columns.Add(valueField);
  759. for (int i = 0; i < Value.Length; i++)
  760. {
  761. DataGridViewRow row = new DataGridViewRow();
  762. dt.Rows.Add(row);
  763. dt.Rows[i][displayField] = Value[i].Split('#')[0];
  764. dt.Rows[i][valueField] = Value[i].Split('#')[1];
  765. }
  766. dgvc.DataPropertyName = DataPropertyName;
  767. dgvc.DataSource = dt;
  768. dgvc.DisplayMember = displayField;
  769. dgvc.ValueMember = valueField;
  770. }
  771. /// <summary>
  772. /// 用于给DGV中的ComboxCell赋静态值
  773. /// </summary>
  774. /// <param name="dgvcc"></param>
  775. /// <param name="displayField"></param>
  776. /// <param name="valueField"></param>
  777. /// <param name="Value"></param>
  778. public static void SetDGVCellComboxData(DataGridViewComboBoxCell dgvcc, string displayField, string valueField, string[] Value)
  779. {
  780. DataTable dt = new DataTable();
  781. dt.Columns.Add(displayField);
  782. dt.Columns.Add(valueField);
  783. for (int i = 0; i < Value.Length; i++)
  784. {
  785. DataRow dr = dt.NewRow();
  786. dr[displayField] = Value[i].Split('#')[0];
  787. dr[valueField] = Value[i].Split('#')[1];
  788. dt.Rows.Add(dr);
  789. }
  790. dgvcc.DisplayMember = displayField;
  791. dgvcc.ValueMember = valueField;
  792. dgvcc.DataSource = dt;
  793. }
  794. /// <summary>
  795. /// 获取刷选的SQL语句,传入的是TextBox的Control,传入的SQL不带Where条件
  796. /// </summary>
  797. /// <param name="SQL"></param>
  798. /// <param name="Condition"></param>
  799. /// <returns></returns>
  800. public static string GetScreenSqlCondition(params Control[] Condition)
  801. {
  802. string condition = "";
  803. //用于统计传入的控件的空值数
  804. int EmptyControlCount = 0;
  805. for (int i = 0; i < Condition.Length; i++)
  806. {
  807. //如果Text不为空再进行条件的拼接
  808. if (Condition[i].Text != "")
  809. {
  810. if (Condition[i] is ComboBox)
  811. {
  812. condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' )";
  813. }
  814. else
  815. {
  816. condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' )";
  817. }
  818. //如果不是最后要判断之后有没有空值的如果有一个Text的值不为空都需要添加and
  819. //添加了一次And之后跳出循环,因为如果后面多项有值会重复添加and
  820. for (int j = i + 1; j < Condition.Length; j++)
  821. {
  822. if (j < Condition.Length)
  823. {
  824. if (Condition[j].Text != "")
  825. {
  826. condition += " and ";
  827. break;
  828. }
  829. }
  830. }
  831. }
  832. else
  833. {
  834. EmptyControlCount = EmptyControlCount + 1;
  835. }
  836. }
  837. //如果所有的控件传入的都是空值则返回也为空
  838. if (EmptyControlCount == Condition.Length)
  839. return "";
  840. else
  841. condition = " where " + condition;
  842. return condition;
  843. }
  844. public static void CleanDataGridView(DataGridView dgv)
  845. {
  846. for (int i = dgv.Columns.Count - 1; i >= 0; i--)
  847. {
  848. dgv.Columns.RemoveAt(i);
  849. }
  850. }
  851. /// <summary>
  852. /// 取出SQL中的参数占位符
  853. /// </summary>
  854. /// <param name="SQL"></param>
  855. /// <returns></returns>
  856. public static string[] GetParamFromSQL(string SQL)
  857. {
  858. string[] par = SQL.Split(':');
  859. //用来存参数的数组
  860. StringBuilder[] addpar = new StringBuilder[par.Length - 1];
  861. string[] param = new string[par.Length - 1];
  862. for (int i = 0; i < par.Length - 1; i++)
  863. {
  864. //新建一个char类型的数组用来存储每个字节的变量
  865. char[] c = par[i + 1].ToCharArray();
  866. addpar[i] = new StringBuilder();
  867. for (int j = 0; j < c.Length; j++)
  868. {
  869. if (c[j] != ' ' && c[j] != ',' && c[j] != ')')
  870. {
  871. addpar[i].Append(c[j]);
  872. }
  873. else
  874. {
  875. break;
  876. }
  877. }
  878. }
  879. for (int i = 0; i < par.Length - 1; i++)
  880. {
  881. param[i] = addpar[i].ToString();
  882. }
  883. return param;
  884. }
  885. public static void SetFormCenter(Form form)
  886. {
  887. form.StartPosition = FormStartPosition.CenterParent;
  888. }
  889. /// <summary>
  890. /// 设置DataGridView的指定列可编辑
  891. /// </summary>
  892. /// <param name="DGV"></param>
  893. /// <param name="EditAbleField"></param>
  894. public static void SetDataGridViewReadOnly(DataGridView DGV, string[] EditAbleField)
  895. {
  896. foreach (DataGridViewColumn dc in DGV.Columns)
  897. {
  898. dc.ReadOnly = true;
  899. foreach (string s in EditAbleField)
  900. {
  901. if (dc.Name.ToLower() == s.ToLower())
  902. {
  903. DGV.Columns[dc.Name].ReadOnly = false;
  904. }
  905. }
  906. }
  907. }
  908. //判断带有CheckBox的DGV是否有项目勾选了
  909. public static DataTable DGVIfChecked(DataGridView dgv)
  910. {
  911. int CheckCount = 0;
  912. DataTable dt = new DataTable();
  913. //第一列是勾选框,排除在循环之外
  914. for (int i = 1; i < dgv.Columns.Count; i++)
  915. {
  916. dt.Columns.Add(dgv.Columns[i].Name);
  917. }
  918. for (int i = 0; i < dgv.RowCount; i++)
  919. {
  920. if (dgv.Rows[i].Cells[0].Value != null)
  921. {
  922. if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
  923. {
  924. if (dgv.Rows[i].Tag.ToString() == "SonRow")
  925. {
  926. DataRow dr = dt.NewRow();
  927. for (int j = 1; j < dgv.ColumnCount; j++)
  928. {
  929. dr[dgv.Columns[j].Name] = dgv.Rows[i].Cells[j].FormattedValue;
  930. }
  931. dt.Rows.Add(dr);
  932. CheckCount++;
  933. }
  934. }
  935. }
  936. }
  937. //判断是否勾选了明细
  938. if (CheckCount == 0)
  939. return null;
  940. return dt;
  941. }
  942. public static void GetExpandDGVCheckedRow(DataGridView dgv, DataTable dt, int RowIndex, int DistinctColumnIndex)
  943. {
  944. //第一列是勾选框,排除在循环之外
  945. if (dt.Columns.Count == 0)
  946. {
  947. for (int i = 0; i < dgv.Columns.Count; i++)
  948. dt.Columns.Add(dgv.Columns[i].Name);
  949. }
  950. //是展开的子行的数据
  951. if (dgv.Rows[RowIndex].Tag != null && dgv.Rows[RowIndex].Tag.ToString() == "SonRow")
  952. {
  953. DataRow dr = dt.NewRow();
  954. DataRow[] datarow = (dt.Select(dgv.Columns[DistinctColumnIndex].Name + " ='" + dgv.Rows[RowIndex].Cells[DistinctColumnIndex].FormattedValue + "'"));
  955. //判断值是否存在,存在移除重新添加
  956. if (datarow.Length > 0)
  957. {
  958. dt.Rows.Remove(datarow[0]);
  959. }
  960. for (int j = 0; j < dgv.ColumnCount; j++)
  961. {
  962. dr[dgv.Columns[j].Name] = dgv.Rows[RowIndex].Cells[j].FormattedValue;
  963. }
  964. dt.Rows.Add(dr);
  965. }
  966. }
  967. /// <summary>
  968. /// 设置只允许输入数字
  969. /// </summary>
  970. /// <param name="sender"></param>
  971. /// <param name="e"></param>
  972. public static void NumOnly(object sender, KeyPressEventArgs e)
  973. {
  974. if (e.KeyChar != '\b')//这是允许输入退格键
  975. {
  976. if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字
  977. {
  978. e.Handled = true;
  979. }
  980. }
  981. }
  982. public static string AddField(string[] Fields)
  983. {
  984. string sql = " ";
  985. foreach (string field in Fields)
  986. sql += field + ",";
  987. return sql.Substring(0, sql.Length - 1);
  988. }
  989. /// <summary>
  990. /// 筛选DataTable
  991. /// </summary>
  992. /// <param name="dt"></param>
  993. /// <param name="condition"></param>
  994. /// <returns></returns>
  995. public static DataTable filterDataTable(DataTable dt, String condition)
  996. {
  997. if (dt == null)
  998. return new DataTable();
  999. //获取筛选条件中的列名,值
  1000. DataRow[] dataRows = dt.Select(condition);
  1001. DataTable ndt = dt.Clone();
  1002. for (int i = 0; i < dataRows.Length; i++)
  1003. {
  1004. ndt.Rows.Add(dataRows[i].ItemArray);
  1005. }
  1006. return ndt;
  1007. }
  1008. /// <summary>
  1009. /// 图表绘制公共方法样本
  1010. /// </summary>
  1011. /// <param name="chart1"></param>
  1012. /// <param name="_dt"></param>
  1013. /// <param name="seriesChartType"></param>
  1014. /// <param name="_title"></param>
  1015. /// <param name="XValueMember"></param>
  1016. /// <param name="YValueMembers"></param>
  1017. /// <param name="Xname"></param>
  1018. /// <param name="Yname"></param>
  1019. public static void ViewChart(Chart chart1, DataTable _dt, SeriesChartType seriesChartType, string _title, string XValueMember, string YValueMembers, string Xname, string Yname)
  1020. {
  1021. chart1.Series[0].ChartType = seriesChartType;
  1022. chart1.DataSource = _dt;
  1023. chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
  1024. chart1.Series[0].MarkerSize = 8;
  1025. chart1.Series[0].XValueMember = XValueMember;
  1026. chart1.Series[0].YValueMembers = YValueMembers;
  1027. chart1.Series[0].Label = "#VAL";
  1028. chart1.Series[0].LabelToolTip = Xname + ": #VAL\r\n " + Yname + " #VALX";
  1029. chart1.Series[0].BackSecondaryColor = Color.DarkCyan;
  1030. chart1.Series[0].BorderColor = Color.DarkOliveGreen;
  1031. chart1.Series[0].LabelBackColor = Color.Transparent;
  1032. chart1.Series[0].LegendText = Yname;
  1033. chart1.Legends[0].Title = _title;
  1034. //chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
  1035. }
  1036. /// <summary>
  1037. /// 将新增打印进程信息写入静态文件
  1038. /// </summary>
  1039. /// <param name="lbl"></param>
  1040. public static void WriteLbl(ApplicationClass lbl)
  1041. {
  1042. Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
  1043. Dictionary<string, int> ProInf = new Dictionary<string, int>();
  1044. for (int i = 0; i < processes.Length; i++)
  1045. {
  1046. try
  1047. {
  1048. if (processes[i].ProcessName == "lppa")
  1049. {
  1050. ProInf.Add(processes[i].StartTime.ToString(), processes[i].Id);
  1051. }
  1052. }
  1053. catch
  1054. {
  1055. }
  1056. }
  1057. var temp = ProInf.Keys.Max();
  1058. String str = SystemInf.ProcessesID + "|" + ProInf[temp];
  1059. FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Append, FileAccess.Write);
  1060. StreamWriter sw = new StreamWriter(fs);
  1061. sw.WriteLine(str, Encoding.UTF8);
  1062. sw.Close();
  1063. fs.Close();
  1064. }
  1065. public static void WriteLbl()
  1066. {
  1067. //Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
  1068. //Dictionary<string, int> ProInf = new Dictionary<string, int>();
  1069. //for (int i = 0; i < processes.Length; i++)
  1070. //{
  1071. // try
  1072. // {
  1073. // if (processes[i].ProcessName == "lppa")
  1074. // {
  1075. // ProInf.Add(processes[i].StartTime.ToString(), processes[i].Id);
  1076. // }
  1077. // }
  1078. // catch
  1079. // {
  1080. // }
  1081. //}
  1082. //var temp = ProInf.Keys.Max();
  1083. //String str = SystemInf.ProcessesID + "|" + ProInf[temp];
  1084. //FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Append, FileAccess.Write);
  1085. //StreamWriter sw = new StreamWriter(fs);
  1086. //sw.WriteLine(str, Encoding.UTF8);
  1087. //sw.Close();
  1088. //fs.Close();
  1089. }
  1090. public static Object GetCacheData(string ParamName)
  1091. {
  1092. try
  1093. {
  1094. Object o = null;
  1095. //根据地址读取xml文件
  1096. XmlDocument doc = new XmlDocument();
  1097. XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
  1098. //忽略文档里面的注释
  1099. settings.IgnoreComments = true;
  1100. XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
  1101. doc.Load(reader);
  1102. //先得到根节点
  1103. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  1104. //再由根节点去找制定的节点
  1105. XmlNodeList nodeList = rootNode.ChildNodes;
  1106. foreach (XmlNode node in nodeList)
  1107. {
  1108. //找到了这个节点名字
  1109. if (node.Name == ParamName)
  1110. {
  1111. //返回节点的内容
  1112. switch (((XmlElement)node).GetAttribute("Type"))
  1113. {
  1114. case "System.String":
  1115. o = node.InnerText;
  1116. break;
  1117. case "System.Int32":
  1118. o = int.Parse(node.InnerText);
  1119. break;
  1120. case "System.Boolean":
  1121. o = node.InnerText == "True" ? true : false;
  1122. break;
  1123. default:
  1124. break;
  1125. }
  1126. break;
  1127. }
  1128. }
  1129. //关闭reader
  1130. reader.Close();
  1131. if (o == null)
  1132. return "";
  1133. else
  1134. return o;
  1135. }
  1136. catch (Exception e)
  1137. {
  1138. LogManager.DoLog(e.Message);
  1139. return "";
  1140. }
  1141. }
  1142. public static void SetCacheData(string ParamName, object Value)
  1143. {
  1144. try
  1145. {
  1146. //根据地址读取xml文件
  1147. XmlDocument doc = new XmlDocument();
  1148. XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
  1149. //忽略文档里面的注释
  1150. settings.IgnoreComments = true;
  1151. XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
  1152. doc.Load(reader);
  1153. //先得到根节点
  1154. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  1155. //再由根节点去找制定的节点
  1156. XmlNodeList nodeList = rootNode.ChildNodes;
  1157. bool flag = false;
  1158. foreach (XmlNode node in nodeList)
  1159. {
  1160. //找到了这个节点名字
  1161. if (node.Name == ParamName)
  1162. {
  1163. //就直接赋值
  1164. node.InnerText = Value.ToString();
  1165. flag = true;
  1166. }
  1167. }
  1168. //如果没有该节点,就创建节点保存结果
  1169. if (!flag)
  1170. {
  1171. //创建节点
  1172. XmlElement newNode = doc.CreateElement(ParamName);
  1173. XmlAttribute attr = doc.CreateAttribute("Type");
  1174. attr.InnerText = Value.GetType().ToString();
  1175. newNode.InnerText = Value.ToString();
  1176. newNode.SetAttributeNode(attr);
  1177. //讲新建的节点挂到根节点上
  1178. rootNode.AppendChild(newNode);
  1179. }
  1180. //关闭Reader
  1181. reader.Close();
  1182. doc.Save(SystemInf.CacheFilePath);
  1183. }
  1184. catch (Exception e)
  1185. {
  1186. LogManager.DoLog(e.Message);
  1187. }
  1188. }
  1189. public static void ClosePrint(ApplicationClass lbl)
  1190. {
  1191. lblpro = lbl;
  1192. Thread close = new Thread(ClosePrintProcess);
  1193. close.Start();
  1194. }
  1195. public static void ClosePrint(Engine lbl)
  1196. {
  1197. eng = lbl;
  1198. Thread close = new Thread(ClosePrintProcess);
  1199. close.Start();
  1200. }
  1201. static Engine eng;
  1202. static ApplicationClass lblpro;
  1203. private static void ClosePrintProcess()
  1204. {
  1205. try
  1206. {
  1207. eng.Stop();
  1208. }
  1209. catch (Exception)
  1210. {
  1211. }
  1212. }
  1213. public static bool connectState(string path)
  1214. {
  1215. return connectState(path, "vsftpd", "vsftpd");
  1216. }
  1217. /// <summary>
  1218. /// 连接远程共享文件夹
  1219. /// </summary>
  1220. /// <param name="path">远程共享文件夹的路径</param>
  1221. /// <param name="userName">用户名</param>
  1222. /// <param name="passWord">密码</param>
  1223. /// <returns></returns>
  1224. public static bool connectState(string path, string userName, string passWord)
  1225. {
  1226. bool Flag = false;
  1227. Process proc = new Process();
  1228. try
  1229. {
  1230. proc.StartInfo.FileName = "cmd.exe";
  1231. proc.StartInfo.UseShellExecute = false;
  1232. proc.StartInfo.RedirectStandardInput = true;
  1233. proc.StartInfo.RedirectStandardOutput = true;
  1234. proc.StartInfo.RedirectStandardError = true;
  1235. proc.StartInfo.CreateNoWindow = true;
  1236. proc.Start();
  1237. string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
  1238. proc.StandardInput.WriteLine(dosLine);
  1239. proc.StandardInput.WriteLine("exit");
  1240. while (!proc.HasExited)
  1241. {
  1242. proc.WaitForExit(1);
  1243. }
  1244. string errormsg = proc.StandardError.ReadToEnd();
  1245. proc.StandardError.Close();
  1246. if (string.IsNullOrEmpty(errormsg))
  1247. {
  1248. Flag = true;
  1249. }
  1250. else
  1251. {
  1252. throw new Exception(errormsg);
  1253. }
  1254. }
  1255. catch (Exception ex)
  1256. {
  1257. LogManager.DoLog(ex.Message);
  1258. }
  1259. finally
  1260. {
  1261. proc.Close();
  1262. proc.Dispose();
  1263. }
  1264. return Flag;
  1265. }
  1266. /// <summary>
  1267. /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
  1268. /// </summary>
  1269. /// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
  1270. /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
  1271. /// <param name="fileName">保存文件的名称以及扩展名</param>
  1272. public static void Transport(string src, string dst, string fileName)
  1273. {
  1274. FileStream inFileStream = new FileStream(src, FileMode.Open);
  1275. if (!Directory.Exists(dst))
  1276. {
  1277. Directory.CreateDirectory(dst);
  1278. }
  1279. dst = dst + fileName;
  1280. FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
  1281. byte[] buf = new byte[inFileStream.Length];
  1282. int byteCount;
  1283. while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
  1284. {
  1285. outFileStream.Write(buf, 0, byteCount);
  1286. }
  1287. inFileStream.Flush();
  1288. inFileStream.Close();
  1289. outFileStream.Flush();
  1290. outFileStream.Close();
  1291. }
  1292. /// <summary>
  1293. /// 取两个DataTable的交集,删除重复数据
  1294. /// </summary>
  1295. /// <param name="sourceDataTable"></param>
  1296. /// <param name="targetDataTable"></param>
  1297. /// <param name="primaryKey"></param>
  1298. /// <returns></returns>
  1299. public static DataTable DataTableMerge(DataTable sourceDataTable, DataTable targetDataTable, string primaryKey)
  1300. {
  1301. if (sourceDataTable != null || targetDataTable != null || !sourceDataTable.Equals(targetDataTable))
  1302. {
  1303. sourceDataTable.PrimaryKey = new DataColumn[] { sourceDataTable.Columns[primaryKey] };
  1304. DataTable dt = targetDataTable.Copy();
  1305. foreach (DataRow tRow in dt.Rows)
  1306. {
  1307. try
  1308. {
  1309. //拒绝自上次调用 System.Data.DataRow.AcceptChanges() 以来对该行进行的所有更改。
  1310. //因为行状态为DataRowState.Deleted时无法访问ItemArray的值
  1311. tRow.RejectChanges();
  1312. //在加载数据时关闭通知、索引维护和约束。
  1313. sourceDataTable.BeginLoadData();
  1314. //查找和更新特定行。如果找不到任何匹配行,则使用给定值创建新行。
  1315. DataRow temp = sourceDataTable.LoadDataRow(tRow.ItemArray, false);
  1316. sourceDataTable.EndLoadData();
  1317. sourceDataTable.Rows.Remove(temp);
  1318. }
  1319. catch
  1320. {
  1321. }
  1322. }
  1323. }
  1324. sourceDataTable.AcceptChanges();
  1325. return sourceDataTable;
  1326. }
  1327. //将DataRow[] 转换成DataTable
  1328. public static DataTable ToDataTable(DataRow[] rows)
  1329. {
  1330. if (rows == null || rows.Length == 0) return new DataTable();
  1331. DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
  1332. foreach (DataRow row in rows)
  1333. tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
  1334. return tmp;
  1335. }
  1336. /// <summary>
  1337. ///
  1338. /// </summary>
  1339. /// <param name="form"></param>
  1340. /// <param name="InOrOut">True表示打开窗体,False表示关闭窗体</param>
  1341. public static void FormStepInOrOut(Form form, bool InOrOut)
  1342. {
  1343. if (InOrOut)
  1344. {
  1345. for (int iNum = 0; iNum <= 10; iNum++)
  1346. {
  1347. //变更窗体的不透明度
  1348. form.Opacity = 0.1 * iNum;
  1349. //暂停
  1350. System.Threading.Thread.Sleep(20);
  1351. }
  1352. }
  1353. else
  1354. {
  1355. for (int iNum = 10; iNum >= 0; iNum--)
  1356. {
  1357. //变更窗体的不透明度
  1358. form.Opacity = 0.1 * iNum;
  1359. //暂停
  1360. System.Threading.Thread.Sleep(20);
  1361. }
  1362. }
  1363. }
  1364. public static string GetDataFromDevice(string Param)
  1365. {
  1366. String cmd = System.Windows.Forms.Application.StartupPath + "\\adb.exe";
  1367. Process p = new Process();
  1368. p.StartInfo = new System.Diagnostics.ProcessStartInfo();
  1369. p.StartInfo.FileName = cmd;//设定程序名
  1370. p.StartInfo.UseShellExecute = false; //关闭shell的使用
  1371. p.StartInfo.RedirectStandardInput = true; //重定向标准输入
  1372. p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
  1373. p.StartInfo.RedirectStandardError = true; //重定向错误输出
  1374. p.StartInfo.CreateNoWindow = true;//设置不显示窗口
  1375. string value = "";
  1376. switch (Param)
  1377. {
  1378. case "IMEI":
  1379. p.StartInfo.Arguments = " shell \n su \n service call iphonesubinfo 1";
  1380. p.Start();
  1381. try
  1382. {
  1383. p.StandardInput.Close();
  1384. string IMEI = p.StandardOutput.ReadToEnd();
  1385. foreach (Match item in Regex.Matches(IMEI, "'\\S+"))
  1386. {
  1387. value += item.Value.Replace(".", "").Replace("'", "").Replace(")", "");
  1388. }
  1389. p.Close();
  1390. }
  1391. catch (Exception ex)
  1392. {
  1393. Console.WriteLine(ex.Message);
  1394. }
  1395. break;
  1396. case "POWER":
  1397. p.StartInfo.Arguments = " shell dumpsys battery";
  1398. p.Start();
  1399. value = Regex.Match(p.StandardOutput.ReadToEnd().ToUpper(), "LEVEL: \\d+").Value.Replace("LEVEL: ", "");
  1400. p.Close();
  1401. break;
  1402. case "MAC":
  1403. p.StartInfo.Arguments = " shell cat /sys/class/net/wlan0/address";
  1404. p.Start();
  1405. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1406. p.Close();
  1407. break;
  1408. case "BT":
  1409. p.StartInfo.Arguments = " shell settings get secure bluetooth_address";
  1410. p.Start();
  1411. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1412. p.Close();
  1413. break;
  1414. case "SPEC":
  1415. p.StartInfo.Arguments = " -d shell getprop ro.product.model";
  1416. p.Start();
  1417. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1418. p.Close();
  1419. break;
  1420. case "VERSION":
  1421. p.StartInfo.Arguments = " shell getprop ro.build.display.id";
  1422. p.Start();
  1423. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1424. p.Close();
  1425. break;
  1426. case "CUS_VERSION":
  1427. p.StartInfo.Arguments = " shell getprop ro.elinktek.version.release";
  1428. p.Start();
  1429. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1430. p.Close();
  1431. break;
  1432. case "SN":
  1433. p.StartInfo.Arguments = " shell getprop ro.serialno";
  1434. p.Start();
  1435. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1436. p.Close();
  1437. break;
  1438. case "RESET":
  1439. p.StartInfo.Arguments = " shell am start -n com.android.settings/com.android.settings.FactoryTestActivity";
  1440. p.Start();
  1441. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1442. p.Close();
  1443. break;
  1444. case "MTK":
  1445. p.StartInfo.Arguments = " shell am start -n elink.com/elink.com.MainActivity";
  1446. p.Start();
  1447. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1448. p.Close();
  1449. break;
  1450. case "ZHANXUN":
  1451. p.StartInfo.Arguments = " shell am start -n com.sprd.validationtools/com.sprd.validationtools.ValidationToolsMainActivity";
  1452. p.Start();
  1453. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1454. p.Close();
  1455. break;
  1456. default:
  1457. break;
  1458. }
  1459. Console.WriteLine(Param + " : " + value.Trim());
  1460. return value.Trim();
  1461. }
  1462. public static string GetDataFromDevice(string Param, string Path)
  1463. {
  1464. String cmd = System.Windows.Forms.Application.StartupPath + "\\adb.exe";
  1465. Process p = new Process();
  1466. p.StartInfo = new System.Diagnostics.ProcessStartInfo();
  1467. p.StartInfo.FileName = cmd;//设定程序名
  1468. p.StartInfo.UseShellExecute = false; //关闭shell的使用
  1469. p.StartInfo.RedirectStandardInput = true; //重定向标准输入
  1470. p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
  1471. p.StartInfo.RedirectStandardError = true; //重定向错误输出
  1472. p.StartInfo.CreateNoWindow = true;//设置不显示窗口
  1473. string value = "";
  1474. switch (Param)
  1475. {
  1476. case "GETFILE":
  1477. p.StartInfo.Arguments = " pull " + Path;
  1478. p.Start();
  1479. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1480. p.Close();
  1481. break;
  1482. case "INSTALL":
  1483. p.StartInfo.Arguments = " install " + Path;
  1484. p.Start();
  1485. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1486. p.Close();
  1487. break;
  1488. default:
  1489. break;
  1490. }
  1491. Console.WriteLine(Param + " : " + value.Trim());
  1492. return value.Trim();
  1493. }
  1494. public static void GetWriteInfo(string FilePath, out string BARCODE, out string MAC, out string BT, out string IMEI0, out string IMEI1)
  1495. {
  1496. MAC = "";
  1497. BT = "";
  1498. IMEI0 = "";
  1499. IMEI1 = "";
  1500. BARCODE = "";
  1501. string txt = "";
  1502. while (true)
  1503. {
  1504. try
  1505. {
  1506. StreamReader sr = new StreamReader(FilePath);
  1507. while (!sr.EndOfStream)
  1508. {
  1509. string str = sr.ReadLine().ToUpper();
  1510. txt += str + "\n";
  1511. }
  1512. IMEI0 = Regex.Match(txt, "IMEI[0] = \\S[0-9]{15}\\S").Value.Replace("IMEI[", "").Replace("]", "");
  1513. IMEI1 = Regex.Match(txt, "IMEI[1] = \\S[0-9]{15}\\S").Value.Replace("IMEI[", "").Replace("]", "");
  1514. MAC = Regex.Match(txt, "WIFIADDRESS = \\[\\S+\\]").Value.Replace("WIFIADDRESS = [", "").Replace("]", "").Replace(":", "");
  1515. BT = Regex.Match(txt, "BTADDRESS = \\[\\S+\\]").Value.Replace("BTADDRESS = [", "").Replace("]", "").Replace(":", "");
  1516. BARCODE = Regex.Match(txt, "BARCODE = \\[\\S+\\]").Value.Replace("BARCODE = [", "").Replace("]", "").Replace(":", "");
  1517. if (BARCODE == "")
  1518. {
  1519. IMEI0 = Regex.Match(txt, "IMEI1\\s+'\\d+'").Value.Replace("IMEI1", "").Replace("'", "").Trim();
  1520. MAC = Regex.Match(txt, "WIFI\\s+'\\S+'").Value.Replace("WIFI", "").Replace("'", "").Trim();
  1521. BT = Regex.Match(txt, "BT\\s+'\\S+'").Value.Replace("BT", "").Replace("'", "").Trim();
  1522. BARCODE = Regex.Match(txt, "SN1\\s+'\\S+'").Value.Replace("SN1", "").Replace("'", "").Trim();
  1523. }
  1524. break;
  1525. }
  1526. catch (Exception e)
  1527. {
  1528. Console.WriteLine(e.Message);
  1529. Thread.Sleep(1000);
  1530. }
  1531. }
  1532. }
  1533. public static bool OpenCSVFile(ref DataTable mycsvdt, string filepath)
  1534. {
  1535. string strpath = filepath; //csv文件的路径
  1536.             try
  1537. {
  1538. int intColCount = 0;
  1539. bool blnFlag = true;
  1540. DataColumn mydc;
  1541. DataRow mydr;
  1542. string strline;
  1543. string[] aryline;
  1544. StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.UTF8);
  1545. while ((strline = mysr.ReadLine()) != null)
  1546. {
  1547. aryline = strline.Split(new char[] { ',' });
  1548. //给datatable加上列名
  1549. if (blnFlag)
  1550. {
  1551. blnFlag = false;
  1552. intColCount = aryline.Length;
  1553. int col = 0;
  1554. for (int i = 0; i < aryline.Length; i++)
  1555. {
  1556. col = i + 1;
  1557. mydc = new DataColumn(col.ToString());
  1558. mycsvdt.Columns.Add(mydc);
  1559. }
  1560. }
  1561. //填充数据并加入到datatable中
  1562. mydr = mycsvdt.NewRow();
  1563. for (int i = 0; i < aryline.Length; i++)
  1564. {
  1565. mydr[i] = aryline[i];
  1566. }
  1567. if (mydr[0].ToString() != "")
  1568. mycsvdt.Rows.Add(mydr);
  1569. }
  1570. mysr.Close();
  1571. return true;
  1572. }
  1573. catch (Exception ex)
  1574. {
  1575. Console.WriteLine(ex.Message+ex.StackTrace);
  1576. return false;
  1577. }
  1578. }
  1579. }
  1580. }