BaseUtil.cs 67 KB

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