12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673 |
- using LabelManager2;
- using Seagull.BarTender.Print;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Reflection;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Windows.Forms;
- using System.Windows.Forms.DataVisualization.Charting;
- using System.Xml;
- using UAS_MES_NEW.CustomControl.DataGrid_View;
- using UAS_MES_NEW.CustomControl.GroupBoxWithBorder;
- using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
- using UAS_MES_NEW.CustomControl.ValueLabel;
- using UAS_MES_NEW.Entity;
- using static System.Windows.Forms.Control;
- namespace UAS_MES_NEW.PublicMethod
- {
- class BaseUtil
- {
- /// <summary>
- /// 检测TCP连接是否存在还是已经中断
- /// </summary>
- /// <param name="c"></param>
- /// <returns></returns>
- public static bool IsOnline(TcpClient c)
- {
- return !((c.Client.Poll(1000, SelectMode.SelectRead) && (c.Client.Available == 0)) || !c.Client.Connected);
- }
- public static Dictionary<string, object> ToDictionary(string JsonData)
- {
- object Data = null;
- Dictionary<string, object> Dic = new Dictionary<string, object>();
- if (JsonData.StartsWith("["))
- {
- //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
- //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
- List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
- MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
- foreach (Match ListItem in ListMatch)
- {
- List.Add(ToDictionary(ListItem.ToString()));//递归调用
- }
- Data = List;
- Dic.Add("List", Data);
- }
- else
- {
- MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
- foreach (Match item in Match)
- {
- try
- {
- if (item.Groups[2].ToString().StartsWith("["))
- {
- //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
- //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
- List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
- MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
- foreach (Match ListItem in ListMatch)
- {
- List.Add(ToDictionary(ListItem.ToString()));//递归调用
- }
- Data = List;
- }
- else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
- else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
- Dic.Add(item.Groups[1].ToString(), Data);
- }
- catch { }
- }
- }
- return Dic;
- }
- /// <summary>
- /// 通过DataTable的ColumnName和Caption来拼接一条语句
- /// </summary>
- /// <param name=""></param>
- /// <returns></returns>
- public static string GetGridViewSelectContent(DataGridView d)
- {
- StringBuilder selectConetnt = new StringBuilder();
- DataTable dt = (DataTable)d.DataSource;
- if (dt == null)
- {
- foreach (DataGridViewColumn dc in d.Columns)
- {
- if (dc.DataPropertyName != "" && dc.DataPropertyName != null)
- {
- selectConetnt.Append(dc.Name + " as " + dc.Name + ",");
- }
- }
- }
- else
- {
- foreach (DataColumn dc in dt.Columns)
- {
- selectConetnt.Append(dc.Caption + " as " + dc.ColumnName + ",");
- }
- }
- return selectConetnt.Remove(selectConetnt.Length - 1, 1).ToString();
- }
- /// <summary>
- /// 禁止DataGirdView排序
- /// </summary>
- /// <param name="Dgv"></param>
- public static void DataGridViewNotSort(DataGridView Dgv)
- {
- foreach (DataGridViewColumn item in Dgv.Columns)
- item.SortMode = DataGridViewColumnSortMode.NotSortable;
- }
- public static string GetLocalIP()
- {
- try
- {
- string HostName = Dns.GetHostName(); //得到主机名
- IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
- for (int i = 0; i < IpEntry.AddressList.Length; i++)
- {
- //从IP地址列表中筛选出IPv4类型的IP地址
- //AddressFamily.InterNetwork表示此IP为IPv4,
- //AddressFamily.InterNetworkV6表示此地址为IPv6类型
- if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
- {
- return IpEntry.AddressList[i].ToString();
- }
- }
- return "";
- }
- catch (Exception ex)
- {
- MessageBox.Show("获取本机IP出错:" + ex.Message);
- return "";
- }
- }
- /// <summary>
- /// 通过字段和其展示的中文值获取查询的内容
- /// </summary>
- /// <param name="field"></param>
- /// <param name="cnfield"></param>
- /// <returns></returns>
- public static string GetSelectContentByStringArray(string[] field, string[] cnfield)
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < field.Length; i++)
- {
- sb.Append(field[i] + " as " + cnfield[i] + ",");
- }
- //去掉多余的逗号
- sb.Remove(sb.Length - 1, 1);
- return sb.ToString();
- }
- static int SortByIndex(Control A, Control B)
- {
- return A.TabIndex.CompareTo(B.TabIndex);
- }
- /// <summary>
- /// 传入控件的集合和DataTable,通过判断控件的名称和数据源的列的描述来匹配,支持单层的GroupBox和Panel
- /// </summary>
- /// <param name="collection"></param>
- /// <param name="dt"></param>
- public static void SetFormValue(ControlCollection collection, DataTable dt)
- {
- List<Control> ctl = new List<Control>();
- //将控件按照索引排序
- for (int i = 0; i < collection.Count; i++)
- {
- for (int j = 0; j < ctl.Count; j++)
- {
- if (!ctl.Contains(collection[i]))
- {
- if (collection[i].TabIndex > ctl[j].TabIndex)
- {
- ctl.Add(collection[i]);
- break;
- }
- else
- {
- ctl.Insert(j, collection[i]);
- break;
- }
- }
- }
- if (ctl.Count == 0)
- {
- ctl.Add(collection[i]);
- }
- }
- ctl.Sort(SortByIndex);
- //DataTable存在数据才进行赋值操作
- if (dt.Rows.Count > 0)
- {
- for (int i = 0; i < ctl.Count; i++)
- {
- //如果含有子控件则进行递归调用
- if (ctl[i].Controls.Count > 0)
- SetFormValue(ctl[i].Controls, dt);
- string controlName = ctl[i].Name;
- string controlsTag = ctl[i].Tag == null ? "" : ctl[i].Tag.ToString();
- //默认给TextBox和Label赋值
- 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)
- {
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper() || controlsTag.ToUpper() == dt.Columns[j].Caption.ToUpper())
- {
- //字段含有Status内容的才进行转换
- if (controlName.ToUpper().Contains("STATUS") || controlsTag.ToUpper().Contains("STATUS"))
- {
- //对审批状态进行判断
- switch (dt.Rows[0][j].ToString().ToUpper())
- {
- case "ENTERING":
- ctl[i].Text = "在录入";
- break;
- case "UNAPPROVED":
- ctl[i].Text = "未批准";
- break;
- case "COMMITED":
- ctl[i].Text = "已提交";
- break;
- case "APPROVE":
- ctl[i].Text = "已批准";
- break;
- case "AUDITED":
- ctl[i].Text = "已审核";
- break;
- case "STARTED":
- ctl[i].Text = "已下放";
- break;
- case "UNCHECK":
- ctl[i].Text = "待检验";
- break;
- case "CHECKING":
- ctl[i].Text = "检验中";
- break;
- default:
- ctl[i].Text = dt.Rows[0][j].ToString();
- break;
- }
- }
- else
- ctl[i].Text = dt.Rows[0][j].ToString();
- }
- }
- }
- //对封装在GroupBox的和Panel的控件进行批量赋值
- if (ctl[i] is GroupBox || ctl[i] is Panel || ctl[i] is GroupBoxWithBorder)
- {
- for (int j = 0; j < ctl[i].Controls.Count; j++)
- {
- controlName = ctl[i].Controls[j].Name;
- 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)
- {
- for (int k = 0; k < dt.Columns.Count; k++)
- {
- if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
- {
- ctl[i].Controls[j].Text = dt.Rows[0][k].ToString();
- }
- }
- }
- }
- }
- }
- }
- //如果没有记录的话,将dt中含有的列的对应值设置为空
- else
- {
- for (int i = 0; i < ctl.Count; i++)
- {
- if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox)
- {
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (ctl[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
- {
- ctl[i].Text = "";
- }
- }
- }
- }
- }
- }
- /// <summary>
- /// 获取打印标签
- /// </summary>
- /// <param name="labelName"></param>
- /// <param name="labelUrl"></param>
- /// <param name="indate"></param>
- public static void GetPrintLabel(string labelName, string labelUrl)
- {
- BaseUtil.GetLabelUrl(labelUrl, labelName);
- }
- /// <summary>
- /// 获取打印标签
- /// </summary>
- /// <param name="labelName"></param>
- /// <param name="labelUrl"></param>
- /// <param name="indate"></param>
- public static void GetPrintLabel(string labelName, string labelUrl, string indate)
- {
- string LabelUrl = labelUrl;
- string LabelName = labelName;
- System.DateTime time = Convert.ToDateTime(indate);
- FileInfo file = new FileInfo(ftpOperater.DownLoadTo + LabelName);
- if (time.ToString() != file.LastWriteTime.ToString())
- BaseUtil.GetLabelUrl(LabelUrl, LabelName, time);
- }
- /// <summary>
- /// 获取标签的路径
- /// </summary>
- /// <param name="URL"></param>
- /// <param name="LabelName"></param>
- /// <param name="time"></param>
- /// <returns></returns>
- public static string GetLabelUrl(string URL, string LabelName, System.DateTime time)
- {
- ftpOperater ftp = new ftpOperater();
- return ftp.DownLoadFromSharePath(URL, LabelName);
- }
- /// <summary>
- /// 移除重复行
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="field"></param>
- /// <returns></returns>
- public static DataTable DeleteSameRow(DataTable dt, string field)
- {
- ArrayList indexList = new ArrayList();
- // 找出待删除的行索引
- for (int i = 0; i < dt.Rows.Count - 1; i++)
- {
- if (!IsContain(indexList, i))
- {
- for (int j = i + 1; j < dt.Rows.Count; j++)
- {
- if (dt.Rows[i][field].ToString() == dt.Rows[j][field].ToString())
- {
- indexList.Add(j);
- }
- }
- }
- }
- indexList.Sort();
- // 排序
- for (int i = indexList.Count - 1; i >= 0; i--)// 根据待删除索引列表删除行
- {
- int index = Convert.ToInt32(indexList[i]);
- dt.Rows.RemoveAt(index);
- }
- return dt;
- }
- /// <summary>
- /// 判断数组中是否存在
- /// </summary>
- /// <param name="indexList">数组</param>
- /// <param name="index">索引</param>
- /// <returns></returns>
- public static bool IsContain(ArrayList indexList, int index)
- {
- for (int i = 0; i < indexList.Count; i++)
- {
- int tempIndex = Convert.ToInt32(indexList[i]);
- if (tempIndex == index)
- {
- return true;
- }
- }
- return false;
- }
- //播放音频文件
- public static void PlaySound(string FileName)
- {
- //要加载COM组件:Microsoft speech object Library
- if (!System.IO.File.Exists(FileName))
- {
- return;
- }
- SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
- SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
- spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
- SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
- pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
- spFs.Close();
- }
- /// <summary>
- /// 从DGV获取指定的列的数据形式是数组的形式
- /// </summary>
- public static ArrayList[] GetColumnDataFromDGV(DataGridView dgv, string[] ColumnName)
- {
- ArrayList[] array = new ArrayList[ColumnName.Length];
- //实例化和查询参数个数一样的ArrayList
- for (int i = 0; i < ColumnName.Length; i++)
- {
- array[i] = new ArrayList();
- }
- DataTable dt = (DataTable)dgv.DataSource;
- //如果第一列是否选框的话
- if (dgv.Columns[0] is DataGridViewCheckBoxColumn)
- {
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
- {
- for (int j = 0; j < ColumnName.Length; j++)
- {
- array[j].Add(dt.Rows[i][ColumnName[j]]);
- }
- }
- }
- }
- //否则直接获取全部的数据
- else
- {
- for (int i = 0; i < dgv.RowCount; i++)
- {
- for (int j = 0; j < ColumnName.Length; j++)
- {
- array[j].Add(dt.Rows[i][ColumnName[j]]);
- }
- }
- }
- return array;
- }
- /// <summary>
- /// 通过DataGridView和需要隐藏的字段的数组来对字段进行隐藏
- /// </summary>
- /// <param name="dgv"></param>
- /// <param name="field"></param>
- public static void HideField(DataGridView dgv, string[] field)
- {
- DataTable dt = (DataTable)dgv.DataSource;
- foreach (DataColumn dc in dt.Columns)
- {
- foreach (string s in field)
- {
- if (dc.Caption == s)
- dgv.Columns[dc.ColumnName].Visible = false;
- }
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="dgv"></param>
- public static void ExpandDGVCheck(DataGridViewExpand dgv, DataGridViewCellEventArgs e)
- {
- if (e.ColumnIndex == 0 && e.RowIndex >= 0)
- {
- if (dgv.Rows[e.RowIndex] is CollapseDataGridViewRow)
- {
- int CollapseRowCount = (dgv.Rows[e.RowIndex] as CollapseDataGridViewRow).Rows.Count;
- if (CollapseRowCount > 0)
- {
- for (int i = (e.RowIndex + 2); i < (e.RowIndex + 1 + CollapseRowCount); i++)
- {
- try
- {
- dgv.Rows[i].Cells[0].Value = dgv.Rows[e.RowIndex].Cells[0].EditedFormattedValue;
- }
- catch (Exception) { }
- }
- }
- }
- }
- }
- /// <summary>
- /// 通过查询的内容获取到字段的描述
- /// </summary>
- /// <param name="field"></param>
- /// <returns></returns>
- public static string[] GetCaptionFromField(string field)
- {
- string[] caption = field.Split(',');
- for (int i = 0; i < caption.Length; i++)
- {
- caption[i] = caption[i].Substring(0, caption[i].LastIndexOf("as")).Trim();
- }
- return caption;
- }
- /// <summary>
- /// 通过查询的语句获取查询的字段
- /// </summary>
- /// <param name="field"></param>
- /// <returns></returns>
- public static string[] GetField(string field)
- {
- string[] fields = field.Split(',');
- for (int i = 0; i < fields.Length; i++)
- {
- fields[i] = fields[i].Substring(fields[i].LastIndexOf("as") + 2, fields[i].Length - fields[i].LastIndexOf("as") - 2).Trim();
- }
- return fields;
- }
- /// <summary>
- /// 通过描述取DataTable的列名,主要用于从配置中取数据
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="caption"></param>
- /// <returns></returns>
- public static string GetColumnNameByCaption(DataTable dt, string caption)
- {
- foreach (DataColumn dc in dt.Columns)
- {
- if (dc.Caption.ToLower() == caption)
- {
- return dc.ColumnName;
- }
- }
- return null;
- }
- //用于封装异常,也可以用于错误的提示
- public static void ShowError(string errorMessage)
- {
- throw new Exception(errorMessage);
- }
- /// <summary>
- /// 判断控件的某个事件是否已经绑定了方法
- /// </summary>
- /// <param name="Control1"></param>
- /// <param name="EventName"></param>
- /// <returns></returns>
- public static bool ControlHasEvent(Control Control1, string EventName)
- {
- //需要查询的内容
- BindingFlags myBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
- Assembly a = Assembly.GetAssembly(Control1.GetType());
- Type t = a.GetType(Control1.GetType().FullName, true);
- //获取控件的事件
- FieldInfo fi = t.GetField(EventName, myBindingFlags);
- EventHandlerList ehl = Control1.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).GetValue(Control1, null) as EventHandlerList;
- //判断事件的委托数量是否大于0
- if (ehl != null)
- {
- Delegate d = ehl[fi.GetValue(Control1)];
- if (d != null && d.GetInvocationList().Length > 0)
- {
- return true;
- }
- }
- return false;
- }
- /// <summary>
- /// 获取控件的事件列表
- /// </summary>
- /// <param name="Control1"></param>
- /// <returns></returns>
- public static FieldInfo[] GetControlsEvent(Control Control1)
- {
- BindingFlags myBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
- Assembly a = Assembly.GetAssembly(Control1.GetType());
- Type t = a.GetType(Control1.GetType().FullName, true);
- FieldInfo[] finf = t.GetFields(myBindingFlags);
- return finf;
- }
- /// <summary>
- /// 清除DataTable的结构和数据,清除列结构时需要从最后的一列开始删
- /// </summary>
- /// <param name="dt"></param>
- public static void CleanDataTable(DataTable dt)
- {
- for (int i = dt.Columns.Count - 1; i >= 0; i--)
- dt.Columns.Remove(dt.Columns[i]);
- }
- /// <summary>
- /// 获取标签的路径
- /// </summary>
- /// <param name="URL"></param>
- /// <param name="LabelName"></param>
- /// <returns></returns>
- public static string GetLabelUrl(string URL, string LabelName)
- {
- ftpOperater ftp = new ftpOperater();
- return ftp.DownLoadFromSharePath(URL, LabelName);
- }
- /// <summary>
- /// 往DataTable中添加数据
- /// </summary>
- public static void AddDataToDataTable(DataTable dt, params string[] param)
- {
- DataRow dr = dt.NewRow();
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- dr[dt.Columns[i].ColumnName] = param[i];
- }
- }
- /// <summary>
- /// 不清除表结构,只清除数据
- /// </summary>
- /// <param name="dt"></param>
- public static void CleanDataTableData(DataTable dt)
- {
- for (int i = dt.Rows.Count - 1; i >= 0; i--)
- {
- dt.Rows.Remove(dt.Rows[i]);
- }
- }
- /// <summary>
- /// 获取拼接的字段
- /// </summary>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static string GetFieldFromDataTable(DataTable dt)
- {
- StringBuilder sb = new StringBuilder();
- foreach (DataColumn dc in dt.Columns)
- {
- sb.Append(dc.Caption + ",");
- }
- return sb.ToString().Substring(sb.ToString().Length - 1, 1);
- }
- /// <summary>
- /// 已经定义好的DataGridView绑定数据,operate是用来添加操作列的
- /// </summary>
- /// <param name="dgv"></param>
- /// <param name="dt"></param>
- /// <param name="AddOpetateColumn"></param>
- /// <param name="operate"></param>
- public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate)
- {
- dgv.AutoGenerateColumns = false;
- dgv.DataSource = dt;
- if (operate.Length > 0)
- {
- if (dgv.Columns[operate[0].Name] != null)
- {
- dgv.Columns.Remove(dgv.Columns[operate[0].Name]);
- }
- dgv.Columns.Add(operate[0]);
- }
- ////纯英文的列不予展示
- //Regex regEnglish = new Regex("^[A-z]+$");
- //foreach (DataGridViewColumn dgvc in dgv.Columns)
- //{
- // if (regEnglish.IsMatch(dgvc.HeaderText))
- // {
- // dgvc.Visible = false;
- // }
- //}
- }
- /// <summary>
- /// 清除DataGridView的数据
- /// </summary>
- /// <param name="dgv"></param>
- public static void CleanDGVData(DataGridView dgv)
- {
- for (int i = dgv.Rows.Count - 1; i >= 0; i--)
- {
- dgv.Rows.RemoveAt(i);
- }
- DataTable dt = dgv.DataSource as DataTable;
- if (dt != null)
- {
- dt.AcceptChanges();
- }
- }
- public static void CleanForm(Form Form)
- {
- for (int i = 0; i < Form.Controls.Count; i++)
- {
- if (Form.Controls[i].Controls.Count > 0)
- {
- CleanControls(Form.Controls[i].Controls);
- }
- 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)
- Form.Controls[i].Text = "";
- if (Form.Controls[i] is DataGridView)
- CleanDGVData((DataGridView)Form.Controls[i]);
- }
- }
- public static void CleanControls(ControlCollection collection)
- {
- for (int i = 0; i < collection.Count; i++)
- {
- if (collection[i].Controls.Count > 0)
- CleanControls(collection[i].Controls);
- 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)
- collection[i].Text = "";
- if (collection[i] is DataGridView)
- CleanDGVData((DataGridView)collection[i]);
- }
- }
- public static void CleanControlsText(params Control[] ctl)
- {
- foreach (Control item in ctl)
- item.Text = "";
- }
- /// <summary>
- /// 需要SQL的顺序和DGV的列的顺序一致
- /// </summary>
- /// <param name="dgv"></param>
- /// <param name="dt"></param>
- /// <param name="CheckBox"></param>
- public static void FillExpandDgvWithDataTable(DataGridViewExpand dgv, DataTable dt, bool CheckBox, bool CheckBoxTrue)
- {
- CleanDGVData(dgv);
- if (CheckBox)
- {
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- CollapseDataGridViewRow collapseRow = new CollapseDataGridViewRow();
- collapseRow.IsCollapse = true;
- DataGridViewCheckBoxCell checkcell = new DataGridViewCheckBoxCell();
- collapseRow.Cells.Add(checkcell);
- checkcell.Value = CheckBoxTrue;
- //因为DGV中可能有空置的列多出,所以需要用DataTable的列进行循环
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- DataGridViewTextBoxCell textcell = new DataGridViewTextBoxCell();
- textcell.Value = dt.Rows[i][j].ToString();
- collapseRow.Cells.Add(textcell);
- textcell.ReadOnly = true;
- }
- collapseRow.Tag = "MainRow";
- dgv.Rows.Add(collapseRow);
- }
- }
- else
- {
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- CollapseDataGridViewRow collapseRow = new CollapseDataGridViewRow();
- collapseRow.IsCollapse = true;
- for (int j = 1; j <= dt.Columns.Count; j++)
- {
- DataGridViewTextBoxCell textcell = new DataGridViewTextBoxCell();
- textcell.Value = dt.Rows[i][j - 1].ToString();
- collapseRow.Cells.Add(textcell);
- }
- dgv.Rows.Add(collapseRow);
- collapseRow.ReadOnly = true;
- }
- }
- }
- /// <summary>
- /// 用于给DGV中的Combox列赋静态值
- /// </summary>
- /// <param name="dgvc"></param>
- /// <param name="displayField"></param>
- /// <param name="valueField"></param>
- /// <param name="Value"></param>
- /// <returns></returns>
- public static void SetDgvColumnComboxData(DataGridViewComboBoxColumn dgvc, string DataPropertyName, string displayField, string valueField, string[] Value)
- {
- DataTable dt = new DataTable();
- dt.Columns.Add(displayField);
- dt.Columns.Add(valueField);
- for (int i = 0; i < Value.Length; i++)
- {
- DataGridViewRow row = new DataGridViewRow();
- dt.Rows.Add(row);
- dt.Rows[i][displayField] = Value[i].Split('#')[0];
- dt.Rows[i][valueField] = Value[i].Split('#')[1];
- }
- dgvc.DataPropertyName = DataPropertyName;
- dgvc.DataSource = dt;
- dgvc.DisplayMember = displayField;
- dgvc.ValueMember = valueField;
- }
- /// <summary>
- /// 用于给DGV中的ComboxCell赋静态值
- /// </summary>
- /// <param name="dgvcc"></param>
- /// <param name="displayField"></param>
- /// <param name="valueField"></param>
- /// <param name="Value"></param>
- public static void SetDGVCellComboxData(DataGridViewComboBoxCell dgvcc, string displayField, string valueField, string[] Value)
- {
- DataTable dt = new DataTable();
- dt.Columns.Add(displayField);
- dt.Columns.Add(valueField);
- for (int i = 0; i < Value.Length; i++)
- {
- DataRow dr = dt.NewRow();
- dr[displayField] = Value[i].Split('#')[0];
- dr[valueField] = Value[i].Split('#')[1];
- dt.Rows.Add(dr);
- }
- dgvcc.DisplayMember = displayField;
- dgvcc.ValueMember = valueField;
- dgvcc.DataSource = dt;
- }
- /// <summary>
- /// 获取刷选的SQL语句,传入的是TextBox的Control,传入的SQL不带Where条件
- /// </summary>
- /// <param name="SQL"></param>
- /// <param name="Condition"></param>
- /// <returns></returns>
- public static string GetScreenSqlCondition(params Control[] Condition)
- {
- string condition = "";
- //用于统计传入的控件的空值数
- int EmptyControlCount = 0;
- for (int i = 0; i < Condition.Length; i++)
- {
- //如果Text不为空再进行条件的拼接
- if (Condition[i].Text != "")
- {
- if (Condition[i] is ComboBox)
- {
- condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' )";
- }
- else
- {
- condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' )";
- }
- //如果不是最后要判断之后有没有空值的如果有一个Text的值不为空都需要添加and
- //添加了一次And之后跳出循环,因为如果后面多项有值会重复添加and
- for (int j = i + 1; j < Condition.Length; j++)
- {
- if (j < Condition.Length)
- {
- if (Condition[j].Text != "")
- {
- condition += " and ";
- break;
- }
- }
- }
- }
- else
- {
- EmptyControlCount = EmptyControlCount + 1;
- }
- }
- //如果所有的控件传入的都是空值则返回也为空
- if (EmptyControlCount == Condition.Length)
- return "";
- else
- condition = " where " + condition;
- return condition;
- }
- public static void CleanDataGridView(DataGridView dgv)
- {
- for (int i = dgv.Columns.Count - 1; i >= 0; i--)
- {
- dgv.Columns.RemoveAt(i);
- }
- }
- /// <summary>
- /// 取出SQL中的参数占位符
- /// </summary>
- /// <param name="SQL"></param>
- /// <returns></returns>
- public static string[] GetParamFromSQL(string SQL)
- {
- string[] par = SQL.Split(':');
- //用来存参数的数组
- StringBuilder[] addpar = new StringBuilder[par.Length - 1];
- string[] param = new string[par.Length - 1];
- for (int i = 0; i < par.Length - 1; i++)
- {
- //新建一个char类型的数组用来存储每个字节的变量
- char[] c = par[i + 1].ToCharArray();
- addpar[i] = new StringBuilder();
- for (int j = 0; j < c.Length; j++)
- {
- if (c[j] != ' ' && c[j] != ',' && c[j] != ')')
- {
- addpar[i].Append(c[j]);
- }
- else
- {
- break;
- }
- }
- }
- for (int i = 0; i < par.Length - 1; i++)
- {
- param[i] = addpar[i].ToString();
- }
- return param;
- }
- public static void SetFormCenter(Form form)
- {
- form.StartPosition = FormStartPosition.CenterParent;
- }
- /// <summary>
- /// 设置DataGridView的指定列可编辑
- /// </summary>
- /// <param name="DGV"></param>
- /// <param name="EditAbleField"></param>
- public static void SetDataGridViewReadOnly(DataGridView DGV, string[] EditAbleField)
- {
- foreach (DataGridViewColumn dc in DGV.Columns)
- {
- dc.ReadOnly = true;
- foreach (string s in EditAbleField)
- {
- if (dc.Name.ToLower() == s.ToLower())
- {
- DGV.Columns[dc.Name].ReadOnly = false;
- }
- }
- }
- }
- //判断带有CheckBox的DGV是否有项目勾选了
- public static DataTable DGVIfChecked(DataGridView dgv)
- {
- int CheckCount = 0;
- DataTable dt = new DataTable();
- //第一列是勾选框,排除在循环之外
- for (int i = 1; i < dgv.Columns.Count; i++)
- {
- dt.Columns.Add(dgv.Columns[i].Name);
- }
- for (int i = 0; i < dgv.RowCount; i++)
- {
- if (dgv.Rows[i].Cells[0].Value != null)
- {
- if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
- {
- if (dgv.Rows[i].Tag.ToString() == "SonRow")
- {
- DataRow dr = dt.NewRow();
- for (int j = 1; j < dgv.ColumnCount; j++)
- {
- dr[dgv.Columns[j].Name] = dgv.Rows[i].Cells[j].FormattedValue;
- }
- dt.Rows.Add(dr);
- CheckCount++;
- }
- }
- }
- }
- //判断是否勾选了明细
- if (CheckCount == 0)
- return null;
- return dt;
- }
- public static void GetExpandDGVCheckedRow(DataGridView dgv, DataTable dt, int RowIndex, int DistinctColumnIndex)
- {
- //第一列是勾选框,排除在循环之外
- if (dt.Columns.Count == 0)
- {
- for (int i = 0; i < dgv.Columns.Count; i++)
- dt.Columns.Add(dgv.Columns[i].Name);
- }
- //是展开的子行的数据
- if (dgv.Rows[RowIndex].Tag != null && dgv.Rows[RowIndex].Tag.ToString() == "SonRow")
- {
- DataRow dr = dt.NewRow();
- DataRow[] datarow = (dt.Select(dgv.Columns[DistinctColumnIndex].Name + " ='" + dgv.Rows[RowIndex].Cells[DistinctColumnIndex].FormattedValue + "'"));
- //判断值是否存在,存在移除重新添加
- if (datarow.Length > 0)
- {
- dt.Rows.Remove(datarow[0]);
- }
- for (int j = 0; j < dgv.ColumnCount; j++)
- {
- dr[dgv.Columns[j].Name] = dgv.Rows[RowIndex].Cells[j].FormattedValue;
- }
- dt.Rows.Add(dr);
- }
- }
- /// <summary>
- /// 设置只允许输入数字
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public static void NumOnly(object sender, KeyPressEventArgs e)
- {
- if (e.KeyChar != '\b')//这是允许输入退格键
- {
- if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字
- {
- e.Handled = true;
- }
- }
- }
- public static string AddField(string[] Fields)
- {
- string sql = " ";
- foreach (string field in Fields)
- sql += field + ",";
- return sql.Substring(0, sql.Length - 1);
- }
- /// <summary>
- /// 筛选DataTable
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="condition"></param>
- /// <returns></returns>
- public static DataTable filterDataTable(DataTable dt, String condition)
- {
- if (dt == null)
- return new DataTable();
- //获取筛选条件中的列名,值
- DataRow[] dataRows = dt.Select(condition);
- DataTable ndt = dt.Clone();
- for (int i = 0; i < dataRows.Length; i++)
- {
- ndt.Rows.Add(dataRows[i].ItemArray);
- }
- return ndt;
- }
- /// <summary>
- /// 图表绘制公共方法样本
- /// </summary>
- /// <param name="chart1"></param>
- /// <param name="_dt"></param>
- /// <param name="seriesChartType"></param>
- /// <param name="_title"></param>
- /// <param name="XValueMember"></param>
- /// <param name="YValueMembers"></param>
- /// <param name="Xname"></param>
- /// <param name="Yname"></param>
- public static void ViewChart(Chart chart1, DataTable _dt, SeriesChartType seriesChartType, string _title, string XValueMember, string YValueMembers, string Xname, string Yname)
- {
- chart1.Series[0].ChartType = seriesChartType;
- chart1.DataSource = _dt;
- chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
- chart1.Series[0].MarkerSize = 8;
- chart1.Series[0].XValueMember = XValueMember;
- chart1.Series[0].YValueMembers = YValueMembers;
- chart1.Series[0].Label = "#VAL";
- chart1.Series[0].LabelToolTip = Xname + ": #VAL\r\n " + Yname + " #VALX";
- chart1.Series[0].BackSecondaryColor = Color.DarkCyan;
- chart1.Series[0].BorderColor = Color.DarkOliveGreen;
- chart1.Series[0].LabelBackColor = Color.Transparent;
- chart1.Series[0].LegendText = Yname;
- chart1.Legends[0].Title = _title;
- //chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
- }
- /// <summary>
- /// 将新增打印进程信息写入静态文件
- /// </summary>
- /// <param name="lbl"></param>
- public static void WriteLbl(ApplicationClass lbl)
- {
- Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
- Dictionary<string, int> ProInf = new Dictionary<string, int>();
- for (int i = 0; i < processes.Length; i++)
- {
- try
- {
- if (processes[i].ProcessName == "lppa")
- {
- ProInf.Add(processes[i].StartTime.ToString(), processes[i].Id);
- }
- }
- catch
- {
- }
- }
- var temp = ProInf.Keys.Max();
- String str = SystemInf.ProcessesID + "|" + ProInf[temp];
- FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Append, FileAccess.Write);
- StreamWriter sw = new StreamWriter(fs);
- sw.WriteLine(str, Encoding.UTF8);
- sw.Close();
- fs.Close();
- }
- public static void WriteLbl()
- {
- //Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
- //Dictionary<string, int> ProInf = new Dictionary<string, int>();
- //for (int i = 0; i < processes.Length; i++)
- //{
- // try
- // {
- // if (processes[i].ProcessName == "lppa")
- // {
- // ProInf.Add(processes[i].StartTime.ToString(), processes[i].Id);
- // }
- // }
- // catch
- // {
- // }
- //}
- //var temp = ProInf.Keys.Max();
- //String str = SystemInf.ProcessesID + "|" + ProInf[temp];
- //FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Append, FileAccess.Write);
- //StreamWriter sw = new StreamWriter(fs);
- //sw.WriteLine(str, Encoding.UTF8);
- //sw.Close();
- //fs.Close();
- }
- public static Object GetCacheData(string ParamName)
- {
- try
- {
- Object o = null;
- //根据地址读取xml文件
- XmlDocument doc = new XmlDocument();
- XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
- //忽略文档里面的注释
- settings.IgnoreComments = true;
- XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
- doc.Load(reader);
- //先得到根节点
- XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
- //再由根节点去找制定的节点
- XmlNodeList nodeList = rootNode.ChildNodes;
- foreach (XmlNode node in nodeList)
- {
- //找到了这个节点名字
- if (node.Name == ParamName)
- {
- //返回节点的内容
- switch (((XmlElement)node).GetAttribute("Type"))
- {
- case "System.String":
- o = node.InnerText;
- break;
- case "System.Int32":
- o = int.Parse(node.InnerText);
- break;
- case "System.Boolean":
- o = node.InnerText == "True" ? true : false;
- break;
- default:
- break;
- }
- break;
- }
- }
- //关闭reader
- reader.Close();
- if (o == null)
- return "";
- else
- return o;
- }
- catch (Exception e)
- {
- LogManager.DoLog(e.Message);
- return "";
- }
- }
- public static void SetCacheData(string ParamName, object Value)
- {
- try
- {
- //根据地址读取xml文件
- XmlDocument doc = new XmlDocument();
- XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
- //忽略文档里面的注释
- settings.IgnoreComments = true;
- XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
- doc.Load(reader);
- //先得到根节点
- XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
- //再由根节点去找制定的节点
- XmlNodeList nodeList = rootNode.ChildNodes;
- bool flag = false;
- foreach (XmlNode node in nodeList)
- {
- //找到了这个节点名字
- if (node.Name == ParamName)
- {
- //就直接赋值
- node.InnerText = Value.ToString();
- flag = true;
- }
- }
- //如果没有该节点,就创建节点保存结果
- if (!flag)
- {
- //创建节点
- XmlElement newNode = doc.CreateElement(ParamName);
- XmlAttribute attr = doc.CreateAttribute("Type");
- attr.InnerText = Value.GetType().ToString();
- newNode.InnerText = Value.ToString();
- newNode.SetAttributeNode(attr);
- //讲新建的节点挂到根节点上
- rootNode.AppendChild(newNode);
- }
- //关闭Reader
- reader.Close();
- doc.Save(SystemInf.CacheFilePath);
- }
- catch (Exception e)
- {
- LogManager.DoLog(e.Message);
- }
- }
- public static void ClosePrint(ApplicationClass lbl)
- {
- lblpro = lbl;
- Thread close = new Thread(ClosePrintProcess);
- close.Start();
- }
- public static void ClosePrint(Engine lbl)
- {
- eng = lbl;
- Thread close = new Thread(ClosePrintProcess);
- close.Start();
- }
- static Engine eng;
- static ApplicationClass lblpro;
- private static void ClosePrintProcess()
- {
- try
- {
- eng.Stop();
- }
- catch (Exception)
- {
- }
- }
- public static bool connectState(string path)
- {
- return connectState(path, "vsftpd", "vsftpd");
- }
- /// <summary>
- /// 连接远程共享文件夹
- /// </summary>
- /// <param name="path">远程共享文件夹的路径</param>
- /// <param name="userName">用户名</param>
- /// <param name="passWord">密码</param>
- /// <returns></returns>
- public static bool connectState(string path, string userName, string passWord)
- {
- bool Flag = false;
- Process proc = new Process();
- try
- {
- proc.StartInfo.FileName = "cmd.exe";
- proc.StartInfo.UseShellExecute = false;
- proc.StartInfo.RedirectStandardInput = true;
- proc.StartInfo.RedirectStandardOutput = true;
- proc.StartInfo.RedirectStandardError = true;
- proc.StartInfo.CreateNoWindow = true;
- proc.Start();
- string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
- proc.StandardInput.WriteLine(dosLine);
- proc.StandardInput.WriteLine("exit");
- while (!proc.HasExited)
- {
- proc.WaitForExit(1);
- }
- string errormsg = proc.StandardError.ReadToEnd();
- proc.StandardError.Close();
- if (string.IsNullOrEmpty(errormsg))
- {
- Flag = true;
- }
- else
- {
- throw new Exception(errormsg);
- }
- }
- catch (Exception ex)
- {
- LogManager.DoLog(ex.Message);
- }
- finally
- {
- proc.Close();
- proc.Dispose();
- }
- return Flag;
- }
- /// <summary>
- /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
- /// </summary>
- /// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
- /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
- /// <param name="fileName">保存文件的名称以及扩展名</param>
- public static void Transport(string src, string dst, string fileName)
- {
- FileStream inFileStream = new FileStream(src, FileMode.Open);
- if (!Directory.Exists(dst))
- {
- Directory.CreateDirectory(dst);
- }
- dst = dst + fileName;
- FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
- byte[] buf = new byte[inFileStream.Length];
- int byteCount;
- while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
- {
- outFileStream.Write(buf, 0, byteCount);
- }
- inFileStream.Flush();
- inFileStream.Close();
- outFileStream.Flush();
- outFileStream.Close();
- }
- /// <summary>
- /// 取两个DataTable的交集,删除重复数据
- /// </summary>
- /// <param name="sourceDataTable"></param>
- /// <param name="targetDataTable"></param>
- /// <param name="primaryKey"></param>
- /// <returns></returns>
- public static DataTable DataTableMerge(DataTable sourceDataTable, DataTable targetDataTable, string primaryKey)
- {
- if (sourceDataTable != null || targetDataTable != null || !sourceDataTable.Equals(targetDataTable))
- {
- sourceDataTable.PrimaryKey = new DataColumn[] { sourceDataTable.Columns[primaryKey] };
- DataTable dt = targetDataTable.Copy();
- foreach (DataRow tRow in dt.Rows)
- {
- try
- {
- //拒绝自上次调用 System.Data.DataRow.AcceptChanges() 以来对该行进行的所有更改。
- //因为行状态为DataRowState.Deleted时无法访问ItemArray的值
- tRow.RejectChanges();
- //在加载数据时关闭通知、索引维护和约束。
- sourceDataTable.BeginLoadData();
- //查找和更新特定行。如果找不到任何匹配行,则使用给定值创建新行。
- DataRow temp = sourceDataTable.LoadDataRow(tRow.ItemArray, false);
- sourceDataTable.EndLoadData();
- sourceDataTable.Rows.Remove(temp);
- }
- catch
- {
- }
- }
- }
- sourceDataTable.AcceptChanges();
- return sourceDataTable;
- }
- //将DataRow[] 转换成DataTable
- public static DataTable ToDataTable(DataRow[] rows)
- {
- if (rows == null || rows.Length == 0) return new DataTable();
- DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
- foreach (DataRow row in rows)
- tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
- return tmp;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="form"></param>
- /// <param name="InOrOut">True表示打开窗体,False表示关闭窗体</param>
- public static void FormStepInOrOut(Form form, bool InOrOut)
- {
- if (InOrOut)
- {
- for (int iNum = 0; iNum <= 10; iNum++)
- {
- //变更窗体的不透明度
- form.Opacity = 0.1 * iNum;
- //暂停
- System.Threading.Thread.Sleep(20);
- }
- }
- else
- {
- for (int iNum = 10; iNum >= 0; iNum--)
- {
- //变更窗体的不透明度
- form.Opacity = 0.1 * iNum;
- //暂停
- System.Threading.Thread.Sleep(20);
- }
- }
- }
- public static string GetDataFromDevice(string Param)
- {
- String cmd = System.Windows.Forms.Application.StartupPath + "\\adb.exe";
- Process p = new Process();
- p.StartInfo = new System.Diagnostics.ProcessStartInfo();
- p.StartInfo.FileName = cmd;//设定程序名
- p.StartInfo.UseShellExecute = false; //关闭shell的使用
- p.StartInfo.RedirectStandardInput = true; //重定向标准输入
- p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
- p.StartInfo.RedirectStandardError = true; //重定向错误输出
- p.StartInfo.CreateNoWindow = true;//设置不显示窗口
- string value = "";
- switch (Param)
- {
- case "IMEI":
- p.StartInfo.Arguments = " shell \n su \n service call iphonesubinfo 1";
- p.Start();
- try
- {
- p.StandardInput.Close();
- string IMEI = p.StandardOutput.ReadToEnd();
- foreach (Match item in Regex.Matches(IMEI, "'\\S+"))
- {
- value += item.Value.Replace(".", "").Replace("'", "").Replace(")", "");
- }
- p.Close();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- break;
- case "POWER":
- p.StartInfo.Arguments = " shell dumpsys battery";
- p.Start();
- value = Regex.Match(p.StandardOutput.ReadToEnd().ToUpper(), "LEVEL: \\d+").Value.Replace("LEVEL: ", "");
- p.Close();
- break;
- case "MAC":
- p.StartInfo.Arguments = " shell cat /sys/class/net/wlan0/address";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "BT":
- p.StartInfo.Arguments = " shell settings get secure bluetooth_address";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "SPEC":
- p.StartInfo.Arguments = " -d shell getprop ro.product.model";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "VERSION":
- p.StartInfo.Arguments = " shell getprop ro.build.display.id";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "CUS_VERSION":
- p.StartInfo.Arguments = " shell getprop ro.elinktek.version.release";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "SN":
- p.StartInfo.Arguments = " shell getprop ro.serialno";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "RESET":
- p.StartInfo.Arguments = " shell am start -n com.android.settings/com.android.settings.FactoryTestActivity";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "MTK":
- p.StartInfo.Arguments = " shell am start -n elink.com/elink.com.MainActivity";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- case "ZHANXUN":
- p.StartInfo.Arguments = " shell am start -n com.sprd.validationtools/com.sprd.validationtools.ValidationToolsMainActivity";
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- default:
- break;
- }
- Console.WriteLine(Param + " : " + value.Trim());
- return value.Trim();
- }
- public static string GetDataFromDevice(string Param, string Path)
- {
- String cmd = System.Windows.Forms.Application.StartupPath + "\\adb.exe";
- Process p = new Process();
- p.StartInfo = new System.Diagnostics.ProcessStartInfo();
- p.StartInfo.FileName = cmd;//设定程序名
- p.StartInfo.UseShellExecute = false; //关闭shell的使用
- p.StartInfo.RedirectStandardInput = true; //重定向标准输入
- p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
- p.StartInfo.RedirectStandardError = true; //重定向错误输出
- p.StartInfo.CreateNoWindow = true;//设置不显示窗口
- string value = "";
- switch (Param)
- {
- case "GETFILE":
- p.StartInfo.Arguments = " pull " + Path;
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
-
- break;
- case "INSTALL":
- p.StartInfo.Arguments = " install " + Path;
- p.Start();
- value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
- p.Close();
- break;
- default:
- break;
- }
- Console.WriteLine(Param + " : " + value.Trim());
- return value.Trim();
- }
- public static void GetWriteInfo(string FilePath, out string BARCODE, out string MAC, out string BT, out string IMEI0, out string IMEI1)
- {
- MAC = "";
- BT = "";
- IMEI0 = "";
- IMEI1 = "";
- BARCODE = "";
- string txt = "";
- while (true)
- {
- try
- {
- StreamReader sr = new StreamReader(FilePath);
- while (!sr.EndOfStream)
- {
- string str = sr.ReadLine().ToUpper();
- txt += str + "\n";
- }
- IMEI0 = Regex.Match(txt, "IMEI[0] = \\S[0-9]{15}\\S").Value.Replace("IMEI[", "").Replace("]", "");
- IMEI1 = Regex.Match(txt, "IMEI[1] = \\S[0-9]{15}\\S").Value.Replace("IMEI[", "").Replace("]", "");
- MAC = Regex.Match(txt, "WIFIADDRESS = \\[\\S+\\]").Value.Replace("WIFIADDRESS = [", "").Replace("]", "").Replace(":", "");
- BT = Regex.Match(txt, "BTADDRESS = \\[\\S+\\]").Value.Replace("BTADDRESS = [", "").Replace("]", "").Replace(":", "");
- BARCODE = Regex.Match(txt, "BARCODE = \\[\\S+\\]").Value.Replace("BARCODE = [", "").Replace("]", "").Replace(":", "");
- if (BARCODE == "")
- {
- IMEI0 = Regex.Match(txt, "IMEI1\\s+'\\d+'").Value.Replace("IMEI1", "").Replace("'", "").Trim();
- MAC = Regex.Match(txt, "WIFI\\s+'\\S+'").Value.Replace("WIFI", "").Replace("'", "").Trim();
- BT = Regex.Match(txt, "BT\\s+'\\S+'").Value.Replace("BT", "").Replace("'", "").Trim();
- BARCODE = Regex.Match(txt, "SN1\\s+'\\S+'").Value.Replace("SN1", "").Replace("'", "").Trim();
- }
- break;
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- Thread.Sleep(1000);
- }
- }
- }
- public static bool OpenCSVFile(ref DataTable mycsvdt, string filepath)
- {
- string strpath = filepath; //csv文件的路径
- try
- {
- int intColCount = 0;
- bool blnFlag = true;
- DataColumn mydc;
- DataRow mydr;
- string strline;
- string[] aryline;
- StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.UTF8);
- while ((strline = mysr.ReadLine()) != null)
- {
- aryline = strline.Split(new char[] { ',' });
- //给datatable加上列名
- if (blnFlag)
- {
- blnFlag = false;
- intColCount = aryline.Length;
- int col = 0;
- for (int i = 0; i < aryline.Length; i++)
- {
- col = i + 1;
- mydc = new DataColumn(col.ToString());
- mycsvdt.Columns.Add(mydc);
- }
- }
- //填充数据并加入到datatable中
- mydr = mycsvdt.NewRow();
- for (int i = 0; i < aryline.Length; i++)
- {
- mydr[i] = aryline[i];
- }
- if (mydr[0].ToString() != "")
- mycsvdt.Rows.Add(mydr);
- }
- mysr.Close();
- return true;
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message+ex.StackTrace);
- return false;
- }
- }
- }
- }
|