BaseUtil.cs 66 KB

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