BaseUtil.cs 66 KB

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