BaseUtil.cs 68 KB

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