BaseUtil.cs 68 KB

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