BaseUtil.cs 70 KB

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