Datagridview 画行号,第一行显示出行号
读取ini文件比较好的方法
public static string
str_systemconfig_FileName = “config.ini”;
string str = GlobalVar.str_systemconfig_AllPath +
GlobalVar.str_systemconfig_FileName;
INIFile myIniFile = new INIFile(str);
int temp_key = 0;
int temp_section = 0;
GlobalVar.i_strSecsIP =
myIniFile.IniReadValue(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++], “10.73.1.183”);
public class GlobalVar
{
public static StringCollection str_systemconfig_section = new StringCollection()
{
“ConfigInfo”,
};
}
///
/// 读取INI文件
///
///
///
///
public string IniReadValue(string Section, string Key, string Default)
{
Byte[] Buffer = new Byte[65535];
int bufLen =
GetPrivateProfileString(Section, Key, Default, Buffer, Buffer.GetUpperBound(0),
this.path);
//必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
string s =
Encoding.GetEncoding(0).GetString(Buffer);
s = s.Substring(0, bufLen);
return s.Trim();
}
public static StringCollection[] str_systemconfig_key = new
StringCollection[i_systemconfig_section_num]
{
new StringCollection()
{
“SECSIP”,
“SECSPORT”,
}
};
写ini文件
string str = GlobalVar.str_systemconfig_AllPath +
GlobalVar.str_systemconfig_FileName;
INIFile myIniFile = new INIFile(str);
int temp_key = 0;
int temp_section = 0;
myIniFile.IniWriteValue(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++],
GlobalVar.i_strSecsIP);
myIniFile.IniWriteValue(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++],
GlobalVar.i_strSecsPort);
myIniFile.WriteBool(GlobalVar.str_systemconfig_section[temp_section],
GlobalVar.str_systemconfig_key[temp_section][temp_key++],
GlobalVar.i_strUseEDID);
///
/// 写INI文件
///
///
///
///
public void IniWriteValue(string Section, string Key, string Value)
{
try
{
WritePrivateProfileString(Section, Key, Value, this.path);
}
catch
{
throw (new
ApplicationException(“写Ini文件出错”));
}
}
//写Bool
public void WriteBool(string Section, string Ident, bool Value)
{
IniWriteValue(Section, Ident,
Convert.ToString(Value));
}
//读整数
public int ReadInteger(string Section, string Ident, int Default)
{
string intStr =
IniReadValue(Section, Ident, Convert.ToString(Default));
try
{
return
Convert.ToInt32(intStr);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Default;
}
}
//写整数
public void WriteInteger(string Section, string Ident, int Value)
{
IniWriteValue(Section, Ident,
Value.ToString());
}
//读double
public double Readdouble(string Section, string Ident, double Default)
{
string intStr =
IniReadValue(Section, Ident, Convert.ToString(Default));
try
{
return
Convert.ToDouble(intStr);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Default;
}
}
//写double
public void Writedouble(string Section, string Ident, double Value)
{
IniWriteValue(Section, Ident,
Value.ToString());
}
///
/// 删除ini文件下所有段落
///
public void ClearAllSection()
{
IniWriteValue(null, null, null);
}
///
/// 删除ini文件下personal段落下的所有键
///
///
public void ClearSection(string Section)
{
IniWriteValue(Section, null, null);
}
//删除某个Section下的键
public void DeleteKey(string Section, string Ident)
{
WritePrivateProfileString(Section,
Ident, null, this.path);
}
//读取指定的Section的所有Value到列表中
public StringCollection ReadSectionValues(string Section,
NameValueCollection Values)
{
StringCollection KeyList = new StringCollection();
KeyList = ReadSection(Section);
Values.Clear();
foreach (string key in KeyList)
{
Values.Add(key,
IniReadValue(Section, key, “”));
}
return KeyList;
}
拆箱
///
/// 系统时间转换成unix时间
///
///
///
public static int DateTimeToTime_t(DateTime dateTime)
{
DateTime dt1 =
TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan ts = dateTime - dt1;
int Result = (int)ts.TotalSeconds;
return Result;
}
public static decimal ObjectToInt(object value)
{
if (value == null)
{
return 0;
}
decimal result = 0;
if (decimal.TryParse(value.ToString(),
out result))
{
return result;
}
return 0;
}
public static float ObjectToFloat(object value)
{
if (value == null)
{
return 0;
}
float result = 0;
if (float.TryParse(value.ToString(),
out result))
{
return result;
}
return 0;
}
public static string SqliteEscape(string tableName)
{
tableName = “_” + tableName;
tableName = tableName.Replace("’", “_”);
tableName = tableName.Replace("+", “_”);
tableName = tableName.Replace("[", “_”);
tableName = tableName.Replace("]", “_”);
tableName = tableName.Replace("(", “(”);
tableName = tableName.Replace(")", “)”);
tableName = tableName.Replace("-", “_”);
tableName = tableName.Replace(".", “_”);
tableName = tableName.Replace("@", “_”);
tableName = tableName.Replace("#", “_”);
tableName = tableName.Replace("%", “_”);
tableName = tableName.Replace("^", “_”);
tableName = tableName.Replace("&", “_”);
tableName = tableName.Replace("!", “_”);
tableName = tableName.Replace(" ", “_”);
return tableName;
}
public static void ButtonEdit_Click(ButtonEdit tt)
{
tt.Text = GetFilePath(tt.Text);
}
private static string GetFilePath(string oldttText)
{
string resultFilePath = “”;
FolderBrowserDialog folderDlg = new
FolderBrowserDialog();
if
(Directory.Exists(oldttText))
{
folderDlg.SelectedPath =
oldttText;
}
else
{
folderDlg.SelectedPath = “D:\”;
}
folderDlg.ShowDialog();
string str = “”;
if
(folderDlg.SelectedPath != “”)
{
str = folderDlg.SelectedPath;
if (IsDriveC(ref str))
{
MessageBox.Show(“请选择除C盘以外的路径!”);
return “”;
}
string str1 =
str.Substring(str.Length - 1, 1);
if (str1 == “\”)
{
resultFilePath = str;
}
else
{
resultFilePath = str + “\”;
}
}
return resultFilePath;
}
public static double ObjectToDouble(object value)
{
try
{
if (value == null || value == DBNull.Value)
{
return 0.0;
}
switch
(value.GetType().ToString())
{
case “System.String”:
return Double.Parse((string)value);
case “System.Int64”:
return Double.Parse(((long)value).ToString());
case “System.Int32”:
return Double.Parse(((int)value).ToString());
case “System.Boolean”:
return 0.0;
case “System.Double”:
return (int)System.Math.Round((double)value, 0);
case “System.DateTime”:
return 0.0;
case “System.Decimal”:
return (double)Convert.ToDecimal(value);
default:
return 0;
}
}
catch
{
return 0.0;
}
}
public static string ObjectToString(Object obj)
{
if (obj == null)
{
return “”;
}
switch
(obj.GetType().ToString())
{
case “System.String”:
return obj.ToString();
case “System.DateTime”:
return
((DateTime)obj).ToLongDateString();
case “System.Int32”:
return ((Int32)obj).ToString();
case “System.Int64”:
return
((Int64)obj).ToString();
case “System.Double”:
return ((double)obj).ToString();
case “System.IO.MemoryStream”:
Stream s = (Stream)obj;
StreamReader sr = new StreamReader(s);
string myString = string.Empty;
while (sr.Peek() > -1)
{
string input =
sr.ReadLine();
myString += input;
}
return myString;
case “System.Byte[]”:
return
Encoding.UTF8.GetString((byte[])obj);
case “System.Boolean”:
if ((bool)obj == false)
return “false”;
else return “true”;
default:
return null;
}
}
数据库操作相关
#region 执行增、删、改操作
///
/// 执行增、删、改操作
///
/// sql语句
/// 连接字符串
/// 返回值:-1表示出现异常
public static int Update(string sql, string connString)
{
MySqlConnection conn = new
MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand(sql,
conn);
try
{
conn.Open();
return
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
#endregion
#region 返回单行查询结果
///
/// 返回单行查询结果
///
/// sql语句
/// 连接字符串
/// 返回值:null表示出现异常
public static object GetSingleResult(string sql, string connString)
{
MySqlConnection conn = new
MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand(sql,
conn);
try
{
conn.Open();
return cmd.ExecuteScalar();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
#endregion
#region 同时执行多条查询语句,并将结果填充到对应的DataTable里面,读取时可以根据表的名称访问DataTable
///
/// 同时执行多条查询语句,并将结果填充到对应的DataTable里面,读取时可以根据表的名称访问DataTable
///
/// 使用Dictionary<string, string>封装对一个SQL语句和数据表的名称
/// 连接字符串
/// 返回值:null表示出现异常;返回一个包含若干个数据表的数据集
public static DataSet GetDataSet(Dictionary<string, string> sqlDic, string connString)
{
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlDataAdapter da = new
MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
foreach (string tableName in sqlDic.Keys)
{
cmd.CommandText =
sqlDic[tableName];
da.Fill(ds, tableName);
}
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
#endregion
#region 基于ADO.NET事务提交多条增删改SQL语句
///
/// 基于ADO.NET事务提交多条增删改SQL语句
///
/// sql语句集合
/// 连接字符串
/// 返回是否执行成功
public static bool UpdateByTran(List sqlList, string connString, ref string excuteResult)
{
MySqlConnection conn = new
MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.Transaction =
conn.BeginTransaction();
foreach (string sql in sqlList)
{
excuteResult += (“执行语句:” + sql + “\r\n”);
cmd.CommandText = sql;
int ret = cmd.ExecuteNonQuery();
excuteResult += (“受影响行数:” + ret + “\r\n”);
}
cmd.Transaction.Commit();
return true;
}
catch (Exception ex)
{
if (cmd.Transaction !=
null)
{
cmd.Transaction.Rollback();
}
throw ex;
}
finally
{
if (cmd.Transaction !=
null)
{
cmd.Transaction = null;
}
conn.Close();
}
}
#endregion
#region 获取服务器时间
public static DateTime GetDBServerTime(string connString)
{
string sql = “select getdate()”;
return
Convert.ToDateTime(GetSingleResult(sql, connString));
}
#endregion
#region 调用存储过程插入数据
///
/// 调用存储过程插入数据
///
/// 存储过程名称
/// 参数
/// 数据库连接字符串
///
public static int UpdateByProcedure(string storeProcedureName,
MySqlParameter[] param, string connString)
{
MySqlConnection conn = new
MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType =
CommandType.StoredProcedure;
cmd.CommandText =
storeProcedureName;
try
{
conn.Open();
cmd.Parameters.AddRange(param);
return
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
///
/// 创建数据库
///
/// 数据库路径
/// sql语句
///
public static int CreateDatabase(string databasePath, string sql)
{
string dbPath = “data source=” + databasePath;
if
(!File.Exists(databasePath))
{
SQLiteConnection.CreateFile(databasePath);
}
SQLiteConnection conn = new
SQLiteConnection(dbPath);
SQLiteCommand cmdCreateTable = new SQLiteCommand(sql,
conn);
try
{
conn.Open();
return
cmdCreateTable.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
}
///
/// 执行增、删、改操作
///
///
///
///
public static int Update(string databasePath, string sql)
{
string dbPath = “Data Source=” + databasePath;
SQLiteConnection conn = new
SQLiteConnection(dbPath);
SQLiteCommand cmd = new SQLiteCommand(sql,
conn);
try
{
conn.Open();
return
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
return -2;
}
finally
{
conn.Close();
}
}
///
/// 插入数据
///
/// 数据库路径
/// sql语句
///
public static int InsertData(string databasePath, string sql)
{
string dbPath = “Data Source=” + databasePath;
SQLiteConnection conn = new
SQLiteConnection(dbPath);
SQLiteCommand cmdInsert = new SQLiteCommand(sql,
conn);
try
{
conn.Open();
return
cmdInsert.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
}
///
/// 返回单行查询结果
///
///
///
///
public static object GetSingleResult(string sql, string databasePath)
{
string dbPath = “Data Source=” + databasePath;
SQLiteConnection conn = new
SQLiteConnection(dbPath);
SQLiteCommand cmdInsert = new SQLiteCommand(sql,
conn);
try
{
conn.Open();
return
cmdInsert.ExecuteScalar();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
}
///
/// 基于事务执行多条sql语句
///
/// 数据库路径
/// sql语句
///
public static bool UpdateByTran(List sqlList, string databasePath, ref string excuteResult)
{
string dbPath = “Data Source=” + databasePath;
SQLiteConnection conn = new
SQLiteConnection(dbPath);
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.Transaction =
conn.BeginTransaction();
foreach (string sql in sqlList)
{
excuteResult += (“执行语句:” + sql + “\r\n”);
cmd.CommandText = sql;
int ret =
cmd.ExecuteNonQuery();
excuteResult += (“受影响行数:” + ret + “\r\n”);
}
cmd.Transaction.Commit();
return true;
}
catch (Exception)
{
if (cmd.Transaction !=
null)
{
cmd.Transaction.Rollback();
}
return false;
}
finally
{
if (cmd.Transaction !=
null)
{
cmd.Transaction = null;
}
conn.Close();
}
}
///
/// 同时执行多条查询语句,将结果填充到对应的datatable里面
///
/// 数据库路径
/// sql语句
///
public static DataSet GetDataSet(Dictionary<string, string> sqlDic, string databasePath)
{
string dbPath = “Data Source=” + databasePath;
SQLiteConnection conn = new SQLiteConnection(dbPath);
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
SQLiteDataAdapter da = new
SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
foreach (string tableName in sqlDic.Keys)
{
cmd.CommandText =
sqlDic[tableName];
da.Fill(ds, tableName);
}
return ds;
}
catch (Exception e)
{
string ex = e.ToString();
return null;
}
finally
{
conn.Close();
}
}
public DataSet GetYieldAndReportInfo(string tableName, string connString,
DataBrowse dataBrowse)
{
string sql = $“SELECT
SNResult,AOIResult,AFResult,EDIDResult,IDDResult,WorkStation,InsertTime FROM {tableName} WHERE 1=1”;
sql += " ORDER BY InsertTime DESC;";
string sqlReport = $“SELECT * FROM {tableName} WHERE PanelID = ‘{dataBrowse.PanelID}’ ORDER BY InsertTime DESC LIMIT 1;”;
Dictionary<string, string> sqlDic = new Dictionary<string, string>() { { “Total”, sql }, { “Report”, sqlReport } };
try
{
DataSet dataSet =
MySQLHelper.GetDataSet(sqlDic, connString);
return dataSet;
}
catch (Exception ex)
{
LogService.LogMessage(LogType.DMSErrorMsg.ToString(),
“读取GetYieldAndReportInfo异常:” + ex.ToString());
return null;
}
}
DataSet dataset = gammaService.GetJYPanelInfoIDpk(Connstr, lcsMes[j]);
if (dataset != null)
{
DataTable dataTable =
dataset.Tables[“Total”];
}
CSV文件写
string reportName = string.Format("{0:yyyyMMdd}", DateTime.Now) + “.csv”;
if (IsFileUsing(path +
$"//{reportName}"))
{
path += “_Temp”;
}
if
(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += $"//{reportName}";
if
(!File.Exists(path))
{
string content = “”;
content = “线别,操作员,型号,时间,二维码,工位,检测结果,错误描述,检测耗时,缺陷类型,X像素坐标,Y像素坐标,X距离坐标,Y距离坐标,W长度,H高度,缺陷九宫格,检测参数,缺陷检出相机,缺陷画面,apiTT,产品像素坐标X,产品像素坐标Y”;
try
{
File.AppendAllText(path,
content + “\r\n”, Encoding.UTF8);
}
catch (Exception ex)
{
LogService.LogMessage(LogType.DMSErrorMsg.ToString(), “创建Report异常:” + ex.ToString());
}
}
直接datatable
ExportFileService exportFileService = new
ExportFileService();
public bool DataTableExportCSV(DataTable dt, string savaPath, string strName)
{
return
exportFileService.DataTableExportCSV(dt, savaPath, strName);
}
Chart统计表格操作
// Chart显示功能
Dictionary<string, Color> chartColor = new Dictionary<string, Color>();
List ColorLists = new List() { Color.Aquamarine,
Color.LightSalmon, Color.LightSteelBlue,
Color.LightYellow ,Color.Bisque
,Color.Gold ,Color.GreenYellow ,Color.SkyBlue ,Color.SlateGray ,Color.Lavender
, Color.Thistle,Color.Wheat ,Color.Tomato ,Color.Turquoise ,
Color.Teal,Color.Tan };
public void ShowChart(Chart chart, List dataList,
SeriesChartType chartType = SeriesChartType.Pie)
{
chart.Series.Clear();
System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
series1.ChartType = chartType;
chart.Series.Add(series1);
for (int i = 0; i <
dataList.Count; i++)
{
Color color = Color.Green;
string text = dataList[i].Text;
try
{
if
(!chartColor.ContainsKey(text))
{
switch (text)
{
case “OK”:
color =
Color.LightGreen;
break;
case “NG”:
color =
Color.Yellow;
break;
case “PASS”:
color =
Color.Red;
break;
default:
color =
ColorLists[chartColor.Count];
break;
}
chartColor.Add(text,
color);
}
else
{
color =
chartColor[text];
}
}
catch { }
double value =
dataList[i].Value;
series1.Points.AddXY(text,
value);
series1.Points[i].LabelToolTip
= text + “(” + value.ToString() + “)”;
series1.Points[i].ToolTip =
text + “(” + value.ToString() + “)”;
series1.Points[i].Label = “#AXISLABEL”;//设置标签显示的内容=X轴内容+value
series1.Points[i].LegendText = “#AXISLABEL(#VAL)(#PERCENT)”;
series1[“PieLabelStyle”] = “Inside”; //在外侧显示Lable
series1[“PieLineColor”] = “Black”;//绘制连线
series1.Points[i].Color =
color;
}
}
public class ChartData
{
public ChartData() { }
public ChartData(string text, double value)
{
this.Text = text;
this.Value = value;
}
///
/// 显示的文本
///
public string Text { get; set; }
///
/// 显示的值
///
public double Value { get; set; }
}
List GMChartData = new
List();
if
(myReportData.GAMAYieldData.GMOKCount > 0)
{
GMChartData.Add(new ChartData()
{
Text = “OK”,
Value =
myReportData.GAMAYieldData.GMOKCount,
});
}
if
(myReportData.GAMAYieldData.GMNGCount > 0)
{
GMChartData.Add(new ChartData()
{
Text = “NG”,
Value =
myReportData.GAMAYieldData.GMNGCount,
});
}
if
(myReportData.GAMAYieldData.GMPASSCount > 0)
{
GMChartData.Add(new ChartData()
{
Text = “PASS”,
Value =
myReportData.GAMAYieldData.GMPASSCount,
});
}
ShowChart(this.chart_GAMMA, GMChartData);
XML文件操作
public class
XML
{
#region XML文档节点查询和读取
///
/// 选择匹配XPath表达式的第一个节点XmlNode.
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名")///
返回XmlNode
public
static XmlNode GetXmlNodeByXpath(XmlDocument xmlDoc, string xpath)
{
//XmlDocument xmlDoc = new XmlDocument();
try
{
//xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
return xmlNode;
}
catch
(Exception ex)
{
return null;
//throw ex; //这里可以定义你自己的异常处理
}
}
///
/// 选择匹配XPath表达式的节点列表XmlNodeList.
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名")///
返回XmlNodeList
public
static XmlNodeList GetXmlNodeListByXpath(string xmlFileName, string xpath)
{
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath);
return xmlNodeList;
}
catch
(Exception ex)
{
return null;
//throw ex; //这里可以定义你自己的异常处理
}
}
///
/// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlAttributeName的属性名称///
返回xmlAttributeName
public
static XmlAttribute GetXmlAttribute(XmlDocument xmlDoc, string xpath, string
xmlAttributeName)
{
string
content = string.Empty;
//XmlDocument xmlDoc = new XmlDocument();
XmlAttribute xmlAttribute = null;
try
{
//xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
if (xmlNode.Attributes.Count > 0)
{
xmlAttribute =
xmlNode.Attributes[xmlAttributeName];
}
}
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
xmlAttribute;
}
///
/// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlAttributeName的属性名称///
返回xmlAttributeName
public
static string GetXmlByAttribute(string xmlFileName, string xpath, string name,
string xmlAttributeName, string xmlAttributeValues)
{
string
content = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
//主要
XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
XmlNode xmlNode = xlist.Cast().Where(o =>
o.Attributes.Cast().FirstOrDefault(a => a.Name ==
xmlAttributeName && a.Value == xmlAttributeValues) !=
null).FirstOrDefault();
//XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
foreach (XmlNode node in xmlNode.ChildNodes)
{
if (node.Name.ToLower() == name.ToLower())
{
//存在此节点则返回InnerText
content =
node.InnerText;
break;
}
}
}
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
content;
}
#endregion
#region XML文档创建和节点或属性的添加、修改
///
/// 创建一个XML文档
///
///
XML文档完全文件名(包含物理路径)/// XML文档根节点名称(须指定一个根节点名称)
///
XML文档版本号(必须为:"1.0")///
XML文档编码方式///
该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性///
成功返回true,失败返回false
public
static bool CreateXmlDocument(string xmlFileName, string rootNodeName, string
version, string encoding, string standalone)
{
bool
isSuccess = false;
try
{
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version,
encoding, standalone);
XmlNode root = xmlDoc.CreateElement(rootNodeName);
xmlDoc.AppendChild(xmlDeclaration);
xmlDoc.AppendChild(root);
xmlDoc.Save(xmlFileName);
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlNodeName的节点名称///
节点文本值///
要匹配xmlAttributeName的属性名称///
属性值///
成功返回true,失败返回false
public
static bool CreateXmlNodeByXPath(XmlDocument xmlDoc, string xpath, string
xmlNodeName, string innerText, string xmlAttributeName, string value)
{
bool
isSuccess = false;
//XmlDocument xmlDoc = new XmlDocument();
try
{
//xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
//存不存在此节点都创建
XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
subElement.InnerXml = innerText;
//如果属性和值参数都不为空则在此新节点上新增属性
if
(!string.IsNullOrEmpty(xmlAttributeName) &&
!string.IsNullOrEmpty(value))
{
XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
xmlAttribute.Value = value;
subElement.Attributes.Append(xmlAttribute);
}
xmlNode.AppendChild(subElement);
}
//xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlNodeName的节点名称///
节点文本值///
成功返回true,失败返回false
public
static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath,
string xmlNodeName, string innerText)
{
bool
isSuccess = false;
bool
isExistsNode = false;//标识节点是否存在
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
//XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
//XmlNode xmlNode = xlist.Cast().Where(o =>
o.InnerText == innerText).FirstOrDefault();
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
//遍历xpath节点下的所有子节点
foreach (XmlNode node in xmlNode.ChildNodes)
{
//XmlAttribute att = node.Attributes.Cast().Where(o
=> o.Name == innerText).FirstOrDefault();
if (node.Name.ToLower() == xmlNodeName.ToLower())
{
//存在此节点则更新
node.InnerXml =
innerText;
isExistsNode =
true;
break;
}
}
if (!isExistsNode)
{
//不存在此节点则创建
XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
subElement.InnerXml =
innerText;
xmlNode.AppendChild(subElement);
}
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
///
/// XML文档完全文件名(包含物理路径)
///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlNodeName的节点名称///
节点文本值///
成功返回true,失败返回false
public
static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath,
string xmlNodeName, string innerText, string XmlAttributeName, string
XmlAttributeValues)
{
bool
isSuccess = false;
bool
isExistsNode = false;//标识节点是否存在
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//遍历xpath节点下的所有子节点
foreach (XmlNode node in xmlNode.ChildNodes)
{
XmlAttribute att = node.Attributes.Cast().Where(o
=> o.Name == XmlAttributeName && o.Value ==
XmlAttributeValues).FirstOrDefault();
if (att != null && node.Name.ToLower() == xmlNodeName.ToLower())
{
//存在此节点则更新
node.InnerXml =
innerText;
isExistsNode =
true;
#region //遍历xpath节点中的所有属性
bool
isExistsAttribute = false;
foreach
(XmlAttribute attribute in node.Attributes)
{
if
(attribute.Name.ToLower() == XmlAttributeName.ToLower())
{
//节点中存在此属性则更新
attribute.Value = XmlAttributeValues;
isExistsAttribute = true;
break;
}
}
if
(!isExistsAttribute)
{
//节点中不存在此属性则创建
XmlAttribute
xmlAttribute = xmlDoc.CreateAttribute(XmlAttributeName);
xmlAttribute.Value =
XmlAttributeValues;
node.Attributes.Append(xmlAttribute);
}
#endregion
break;
}
}
if (!isExistsNode)
{
//不存在此节点则创建
XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
subElement.InnerXml = innerText;
XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(XmlAttributeName);
xmlAttribute.Value = XmlAttributeValues;
subElement.Attributes.Append(xmlAttribute);
xmlNode.AppendChild(subElement);
}
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlNodeName的节点名称///
节点文本值///
指定父节点文本值///
成功返回true,失败返回false
public
static bool CreateOrUpdateXmlNodeByXPath(XmlDocument xmlDoc, string xpath,
string xmlNodeName, string innerText)
{
bool
isSuccess = false;
bool
isExistsNode = false;//标识节点是否存在
//XmlDocument xmlDoc = new XmlDocument();
try
{
//xmlDoc.Load(xmlFileName); //加载XML文档
//XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
//主要
//XmlNode xmlNode = xlist.Cast().Where(o =>
o.Attributes.Cast().FirstOrDefault(a => a.Name ==
“CameraCount” && a.Value == parentAttributevalues) !=
null).FirstOrDefault();
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//遍历xpath节点下的所有子节点
foreach (XmlNode node in xmlNode.ChildNodes)
{
if (node.Name.ToLower() == xmlNodeName.ToLower())
{
//存在此节点则更新
node.InnerXml =
innerText;
isExistsNode =
true;
break;
}
}
if (!isExistsNode)
{
//不存在此节点则创建
XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
subElement.InnerXml = innerText;
xmlNode.AppendChild(subElement);
}
}
//xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建)
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要匹配xmlAttributeName的属性名称///
属性值///
成功返回true,失败返回false
public static
bool CreateOrUpdateXmlAttributeByXPath(XmlDocument xmlDoc, string xpath, string
xmlAttributeName, string value)
{
bool
isSuccess = false;
bool
isExistsAttribute = false;//标识属性是否存在
//XmlDocument xmlDoc = new XmlDocument();
try
{
//xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
//遍历xpath节点中的所有属性
foreach (XmlAttribute attribute in xmlNode.Attributes)
{
if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
{
//节点中存在此属性则更新
attribute.Value =
value;
isExistsAttribute =
true;
break;
}
}
if (!isExistsAttribute)
{
//节点中不存在此属性则创建
XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
xmlAttribute.Value = value;
xmlNode.Attributes.Append(xmlAttribute);
}
}
//xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
#endregion
#region XML文档节点或属性的删除
///
/// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除)
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
成功返回true,失败返回false
public
static bool DeleteXmlNodeByXPath(XmlDocument xmlDoc, string xpath)
{
bool
isSuccess = false;
try
{
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
//删除节点
xmlNode.ParentNode.RemoveChild(xmlNode);
}
isSuccess
= true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
要删除的xmlAttributeName的属性名称///
成功返回true,失败返回false
public
static bool DeleteXmlAttributeByXPath(string xmlFileName, string xpath, string
xmlAttributeName)
{
bool
isSuccess = false;
bool
isExistsAttribute = false;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
XmlAttribute xmlAttribute = null;
if
(xmlNode != null)
{
//遍历xpath节点中的所有属性
foreach (XmlAttribute attribute in xmlNode.Attributes)
{
if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
{
//节点中存在此属性
xmlAttribute =
attribute;
isExistsAttribute =
true;
break;
}
}
if (isExistsAttribute)
{
//删除节点中的属性
xmlNode.Attributes.Remove(xmlAttribute);
}
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
///
/// 删除匹配XPath表达式的第一个节点中的所有属性
///
///
XML文档完全文件名(包含物理路径)///
要匹配的XPath表达式(例如:"//节点名//子节点名///
成功返回true,失败返回false
public
static bool DeleteAllXmlAttributeByXPath(string xmlFileName, string xpath)
{
bool
isSuccess = false;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if
(xmlNode != null)
{
//遍历xpath节点中的所有属性
xmlNode.Attributes.RemoveAll();
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch
(Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return
isSuccess;
}
#endregion
#region 通过反射写入节点通用方法
///
/// 通过反射写入节点通用方法
///
///
///
///
///
///
是否将子集合写入public
static void WriteNodeByProperty(T obj, XmlDocument xmlDoc, string
xpath, bool isList)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach
(PropertyInfo info in properties)
{
if
(info.PropertyType.IsGenericType && isList)
{
dynamic value = obj.GetType().GetProperty(info.Name).GetValue(obj);
int count = 0;
foreach (var item in value)
{
CreateOrUpdateXmlNodeByXPath(xmlDoc, xpath, info.Name + count,
“”);
WriteNodeByProperty(item, xmlDoc, xpath + “//” + info.Name +
count++, isList);
}
}
else
{
if (!info.PropertyType.IsConstructedGenericType)
{
string tt = obj.GetType().GetProperty(info.Name).GetValue(obj).ToString();
CreateOrUpdateXmlNodeByXPath(xmlDoc, xpath, info.Name, tt);
}
}
}
}
#endregion
#region 通过反射读取节点通用方法
///
/// 通过反射读取节点通用方法
///
///
///
///
///
///
public
static T ReadNodeByProperty(T obj, XmlDocument xmlDoc, string xpath)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach
(PropertyInfo info in properties)
{
if
(!info.PropertyType.IsGenericType)
{
XmlNode node = GetXmlNodeByXpath(xmlDoc, xpath + “//” +
info.Name);
if (node != null)
{
object value = TypeTranslation(node.InnerText, info.PropertyType);
obj.GetType().GetProperty(info.Name).SetValue(obj, value);
}
}
}
return
obj;
}
#endregion
#region 类型转换方法
///
/// 类型转换方法
///
///
初始值///
类型///
private
static object TypeTranslation(string value, Type valuetype)
{
if (valuetype == typeof(string) ||
valuetype == typeof(String))
{
return value;
}
object
obj = new object();
try
{
if
(string.IsNullOrEmpty(value))
{
if (valuetype == typeof(int))
{
obj = default(int);
}
else if (valuetype == typeof(double) || valuetype == typeof(Double))
{
obj = default(double);
}
else if (valuetype == typeof(float))
{
obj = default(float);
}
else if (valuetype == typeof(long))
{
obj = default(long);
}
else if (valuetype == typeof(DateTime))
{
obj = default(DateTime);
}
}
else if (valuetype.IsEnum)
{
Type type = Nullable.GetUnderlyingType(valuetype) ?? valuetype;
obj = Enum.Parse(valuetype, value);
}
else
{
obj = valuetype.GetMethod(“Parse”, new Type[] { typeof(string)
}).Invoke(null, new object[] { value });
}
}
catch
(Exception)
{
}
return
obj;
}
#endregion
public
static void DeleteExceptionFile(string path)
{
try
{
if
(File.Exists(path))
{
File.Delete(path);
}
}
catch
(Exception)
{
}
}
}
数据库去重语句
string sql = $“SELECT *
FROM {tableName} b WHERE 1=1”;
if
(dataBrowse.StartTime != -1)
{
sql += $" AND InsertTime>={dataBrowse.StartTime}";
}
if (dataBrowse.EndTime
!= -1)
{
sql += $" AND InsertTime<={dataBrowse.EndTime}";
}
if (!string.IsNullOrEmpty(dataBrowse.PanelID))
{
sql += $" AND PanelID LIKE ‘%{dataBrowse.PanelID}%’";
}
sql += $" AND b.pk_No IN (SELECT e.PNo FROM (select
PanelID,count(*) as count,MAX(pk_No) as PNo from {tableName} group by PanelID
having count = 1) as e)";
sql += " UNION ALL";
sql += $" SELECT * FROM {tableName} b WHERE 1=1";
if
(dataBrowse.StartTime != -1)
{
sql += $" AND InsertTime>={dataBrowse.StartTime}";
}
if (dataBrowse.EndTime
!= -1)
{
sql += $" AND InsertTime<={dataBrowse.EndTime}";
}
if (!string.IsNullOrEmpty(dataBrowse.PanelID))
{
sql += $" AND PanelID LIKE ‘%{dataBrowse.PanelID}%’";
}
sql += $" AND b.pk_No IN (SELECT e.PNo FROM (select
PanelID,count(*) as count,MAX(pk_No) as PNo from {tableName} group by PanelID
having count> 1) as e);";
合并datatable
#region 合并表格
private DataTable MergeDataTable(DataTable dataTable1, DataTable
dataTable2)
{
//DataTable DataTable1 = new DataTable();
//DataTable DataTable2 = new DataTable();
DataTable newDataTable =
dataTable1.Columns.Count > dataTable2.Columns.Count ? dataTable1.Clone() :
dataTable2.Clone();
object[] obj = new object[newDataTable.Columns.Count];
for (int i = 0; i <
dataTable1.Rows.Count; i++)
{
dataTable1.Rows[i].ItemArray.CopyTo(obj, 0);
newDataTable.Rows.Add(obj);
}
for (int i = 0; i <
dataTable2.Rows.Count; i++)
{
dataTable2.Rows[i].ItemArray.CopyTo(obj,
0);
newDataTable.Rows.Add(obj);
}
return newDataTable;
}
ftp下载
// FTP 下载
public static bool FtpFileDownload(string savePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
{
string ftpServerPath = “ftp://” + ftpServerIP + “:21//” + fileName; //":23"指定的端口,不填默认端口为21
string ftpUser =
ftpUserID;
string ftpPwd =
ftpPassword;
string saveFilePath =
savePath;
FileStream outputStream = null;
FtpWebResponse response = null;
FtpWebRequest reqFTP;
try
{
reqFTP =
(FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath));
reqFTP.Method =
WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Timeout = 3000;
reqFTP.Credentials = new
NetworkCredential(ftpUser, ftpPwd);
response =
(FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream =
response.GetResponseStream();
int bufferSize = 2048;
int readCount;
int ftpFileReadSize =
0;
byte[] buffer = new byte[bufferSize];
readCount =
ftpStream.Read(buffer, 0, bufferSize);
outputStream = new
FileStream(saveFilePath, FileMode.Create);
while (readCount > 0)
{
ftpFileReadSize +=
readCount;
outputStream.Write(buffer,
0, readCount);
readCount =
ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
LogManager.LogMessage(LogType.SECSErrorMsg, “FtpClient异常:” + ex.Message);
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
return false;
}
return true;
}
// 获取FTP文件大小
private long GetFtpFileSize(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
{
long fileSize = 0;
string ftpServerPath = “ftp://” + ftpServerIP + “:23” + fileName;
string ftpUser =
ftpUserID;
string ftpPwd =
ftpPassword;
FtpWebResponse response = null;
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri(ftpServerPath));
reqFTP.Method =
WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Timeout = 3000;
reqFTP.Credentials = new
NetworkCredential(ftpUser, ftpPwd);
reqFTP.Method =
WebRequestMethods.Ftp.GetFileSize;//要求返回文件大小属性
response =
(FtpWebResponse)reqFTP.GetResponse();
fileSize = response.ContentLength;
response.Close();
}
catch (Exception ex)
{
LogManager.LogMessage(LogType.SECSErrorMsg, “FtpClient异常:” + ex.Message);
if (response != null)
{
response.Close();
}
return -1;
}
return fileSize;
socket连接消息发送 客户端
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VAT_WinformSocketClass;
namespace JL_OpticProduct_SECS
{
public class VAT_EDCClass
{
public int serverport = 5000;
public string serverip = “127.0.0.1”;
VAT_SocketClientClass m_VAT_SocketClientClass;
public Object locker = new Object();
private delegate int SendMesg(string msg);
private SendMesg sendMesg = null;
public VAT_EDCClass(int nport, string ipaddress)
{
sendMesg = new
SendMesg(sendMessageServer);
serverport = nport;
serverip = ipaddress;
m_VAT_SocketClientClass = new
VAT_SocketClientClass(serverport, serverip, RecieveMessageFunction,
ConnectClientFunction, DisConnectClientFunction, locker);
}
public int sendMessageServer(string strMessage)
{
int ret = 0;
ret =
m_VAT_SocketClientClass.sendMessageServer(strMessage);
if (ret == 0)//返回值0,说明发送成功
{
string strMessage1 = “[CPC->EDC][” + serverip + “]” + “发送消息:” + strMessage;
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToEDC,
strMessage1);
}
else
{
string strMessage1 = “[CPC->EDC][” + serverip + “]” + “已经断开,消息发送失败”;
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToEDC,
strMessage1);
}
return ret;
}
public void RecieveMessageFunction(string strMessage)
{
string strMessage1 = “[EDC->CPC][” + serverip + “]” + “接收到消息:” + strMessage;
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToEDC,
strMessage1);
//处理EDC发过来的信息 肖超 20171206
UpdateAsClientTCPIPReceived(strMessage);
}
public void DisConnectClientFunction()
{
string strMessage = “[CPC->EDC][” + serverip + “]” + “已经断开!”;
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToEDC,
strMessage);
GlobalVar.m_Form_B5F1.SetEDCStatus(2);
//HTGlobalVar.m_FmMain.SetEDCStatus(1);
//HTGlobalVar.m_FmMain.EDCIsConnected = false;
}
public void ConnectClientFunction()
{
string strMessage = “[CPC->EDC][” + serverip + “]” + “建立一个新的连接成功!”;
//
VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToEDC, strMessage);
GlobalVar.m_Form_B5F1.SetEDCStatus(1);
//HTGlobalVar.m_FmMain.EDCIsConnected = true;
}
///
/// 处理接收到的EDC命令
///
///
public void UpdateAsClientTCPIPReceived(string
sReceivedAsClientTCPIPData)
{
sReceivedAsClientTCPIPData =
sReceivedAsClientTCPIPData.Trim(new char[]
{
‘@’
});
string[] array =
sReceivedAsClientTCPIPData.Split(new char[]
{
‘@’
});
int num = array.Length;
for (int i = 0; i < num;
i++)
{
string[] arrayMessage =
array[i].Split(new char[]
{
‘,’
});
if
(arrayMessage.Length >= 1)
{
string info = “”;
string header =
arrayMessage[0];
if (header != “READY” && header != “MAINTAIN” && arrayMessage.Length >= 2)
{
int num2 =
array[i].IndexOf(’,’);
info =
array[i].Substring(num2 + 1);
}
if (header == “PGPowerOn” || header == “PGPowerOff” || header == “NextPattern”)
{
int num3 =
System.Convert.ToInt32(info);
}
string flag = header;
switch (flag)
{
case “JCChangeRecipeEDC”:
break;
case “JCReQuestAllRecipeNameEDC”: //查询EDC的所有recipe返回的结果
update by hxq 20180409
break;
case “EDCRecipe”: //查询EDC的当前recipe update by hxq 20180409
break;
case “PGRECIPE”: //查询PG的当前recipe update by hxq 20180409
break;
case “JCChangeRecipe”:
break;
case “INSPSTATE”:
break;
case “RECIPE”:
break;
case “READY”:
this.sendMessageServer(“READY@”);
break;
case “MAINTAIN”:
case “AUTOPAUSE”:
{
break;
}
case “ALARM”:
{
break;
}
case “START1”:
break;
case “ASKID1”:
{
break;
}
case “START2”:
break;
default:
break;
}
}
}
}
}
}
服务器端建立
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;
using System.Threading.Tasks;
using VAT_WinformSocketClass;
using BLL;
using Model;
using System.Net.Sockets;
public VAT_EDCClass
m_VAT_EDCClass;
private void Form_B5F1_Load(object sender, EventArgs
e)
m_VAT_EDCClass = new VAT_EDCClass(Convert.ToInt32(GlobalVar.i_strSecsPort),
GlobalVar.i_strEdcIP);
if (m_VAT_EDCClass != null)
{
m_VAT_EDCClass.sendMessageServer (srtdata);
}
public class VAT_EDCClass
{
public int serverport = 5000;
public string serverip = “127.0.0.1”;
VAT_SocketServerClass m_VAT_SocketServerClass;
public Object locker = new Object();
public static object PanelLock = new object();
// SECSBase SECS_Base = null;
bool m_bServerStatus = false;
public Socket client_SECS;
private delegate int SendMesg(string msg);
private SendMesg sendMesg = null;
public VAT_EDCClass(int nport)
{
serverport = nport;
//serverip=ipaddress;
try
{
m_VAT_SocketServerClass = new
VAT_SocketServerClass(serverport, RecieveMessageFunction,
ConnectClientFunction, DisConnectClientFunction, locker, out m_bServerStatus);
}
catch (Exception ex)
{
//m_VAT_SocketServerClass.m_bServerStatus = false;
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCException,
“CPC Server port:” + serverport.ToString() + " " +
ex.ToString());
LogManager.LogMessage(LogType.SECSNormalMsg, “SECS Server port:” + serverport.ToString() + " " + ex.ToString());
}
if
(m_VAT_SocketServerClass.m_bServerStatus == true) //服务器启动成功
{
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToCPC,
“CPC Server port:” + serverport.ToString() + " 服务器启动成功!");
LogManager.LogMessage(LogType.SECSNormalMsg, “SECS Server port:” + serverport.ToString() + " 服务器启动成功!");
}
else //服务器启动失败
{
//VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToCPC,
“CPC Server port:” + serverport.ToString() + " 服务器启动失败!");
LogManager.LogMessage(LogType.SECSNormalMsg, “SECS Server port:” + serverport.ToString() + " 服务器启动失败!");
}
}
public void RecieveMessageFunction(string strMessage, Socket
client)
{
string strMessage1 = “[CPCServer->CPCClient][” + client.RemoteEndPoint.ToString() + “]” + “接收到消息:” + strMessage;
LogManager.LogMessage(LogType.SECSNormalMsg , strMessage1);
try
{
strMessage = strMessage.Trim(new char[]
{
‘@’
});
string[] strReceiveMessage
= strMessage.Split(new char[]
{
‘@’
});
int nReceiveLength =
strReceiveMessage.Length;
for (int ReceiveIndex = 0;
ReceiveIndex < nReceiveLength; ReceiveIndex++)
{
string[]
strReceiveMessage1 = strReceiveMessage[ReceiveIndex].Split(new char[]
{
‘,’
});
switch
(strReceiveMessage1[0])
{
case “DFS1”:
string[] strDFS =
strReceiveMessage1[1].Split(’:’);
break;
}
}
}
catch (Exception exp)
{
Console.Read();
//
VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCException,
“RecieveMessageFunction CPC:” + exp.ToString());
LogManager.LogMessage(LogType.SECSErrorMsg, exp.ToString ());
}
}
public void ConnectClientFunction(Socket client)
{
while
(GlobalVar.m_Form_B5F1 == null)
{
Thread.Sleep(10);
}
if
(GlobalVar.m_Form_B5F1 != null)
{
GlobalVar.m_Form_B5F1.SetEDCStatus(1);
}
client_SECS = client;
//HTGlobalVar.m_strPPCIPAddress =
((System.Net.IPEndPoint)client_CPC.RemoteEndPoint).Address.ToString();//最近连接的一个客户端
string strMessage = “[CPCServer->CPCClient][” + client.RemoteEndPoint.ToString() + “]” + “建立一个新的连接成功!”;
LogManager.LogMessage(LogType.SECSNormalMsg, strMessage);
}
public void DisConnectClientFunction(Socket client)
{
string strMessage = “[SECSServer->SECSClient][” + client.RemoteEndPoint.ToString() + “]” + “已经断开!”;
LogManager.LogMessage(LogType.SECSNormalMsg , strMessage);
while
(GlobalVar.m_Form_B5F1 == null)
{
Thread.Sleep(10);
}
if
(GlobalVar.m_Form_B5F1 != null)
{
m_VAT_SocketServerClass.serverClient.Remove(client);
if
(m_VAT_SocketServerClass.serverClient.Count > 0)
{
client_SECS =
m_VAT_SocketServerClass.serverClient[m_VAT_SocketServerClass.serverClient.Count
- 1];//最近连接的一个客户端
//HTGlobalVar.m_strPPCIPAddress =
((System.Net.IPEndPoint)client_PPC.RemoteEndPoint).Address.ToString();
}
else//一个客户端都没有,才认为通信断掉
{
//HTGlobalVar.m_strPPCIPAddress = “”;
GlobalVar.m_Form_B5F1.SetEDCStatus(2);
}
}
lock (locker)
{
}
}
}
public int sendMessageServer(string strMessage,string strip)
{
int ret = 1;
try
{
IPAddress remote_ip =
((System.Net.IPEndPoint)client_CPC.RemoteEndPoint).Address;//获取远程连接IP
ret =
m_VAT_SocketServerClass.sendMessageServer(strMessage, remote_ip.ToString());
if (ret == 0)
{
string strMessage1 = “[CPCServer->CPCClient][” + remote_ip.ToString() + “]” + “发送消息:” + strMessage;
VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToCPC,
strMessage1);
}
else
{
string strMessage1 = “[CPCServer->CPCClient][” + remote_ip.ToString() + “]” + “已经断开,消息发送失败”;
VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCToCPC,
strMessage1);
}
}
catch(Exception ex)
{
VAT_ShowLog.ShowLog.SendLogMessage(HTGlobalVar.m_strLogCPCException, “IP:” + strip + " port:" + serverport.ToString() + " " + ex.ToString());
}
return ret;
}
UI
RefreshProductTable(tableName,panelID );
RefreshChat(tableName,panelID);
RefreshDefect(this.myPictureBox_DefectMapArea,
tableName, panelID);
}
}
}
private void RefreshDefect(VAT_MyControls.DrawDefectControl control,string tableName, string panelID)//显示缺陷信息 九宫格和缺陷列表
{
if (InvokeRequired)
{
this.Invoke(new MethodInvoker(()
=> { RefreshDefect(control,tableName, panelID); }));
}
else
{