老的采集程序

This commit is contained in:
廖德云 2025-11-08 08:17:36 +08:00
commit 214368166a
116 changed files with 12653 additions and 0 deletions

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

View File

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleGetPLCData.CS
{
/// <summary>
/// 通讯编码格式提供者,为通讯服务提供编码和解码服务
/// 你可以在继承类中定制自己的编码方式如:数据加密传输等
/// </summary>
public class Coder
{
/// <summary>
/// 编码方式
/// </summary>
private EncodingMothord _encodingMothord;
protected Coder()
{
}
public Coder(EncodingMothord encodingMothord)
{
_encodingMothord = encodingMothord;
}
public enum EncodingMothord
{
Default = 0,
Unicode,
UTF8,
ASCII,
}
/// <summary>
/// 通讯数据解码
/// </summary>
/// <param name="dataBytes">需要解码的数据</param>
/// <returns>编码后的数据</returns>
public virtual string GetEncodingString(byte[] dataBytes, int start, int size)
{
switch (_encodingMothord)
{
case EncodingMothord.Default:
{
return Encoding.Default.GetString(dataBytes, start, size);
}
case EncodingMothord.Unicode:
{
return Encoding.Unicode.GetString(dataBytes, start, size);
}
case EncodingMothord.UTF8:
{
return Encoding.UTF8.GetString(dataBytes, start, size);
}
case EncodingMothord.ASCII:
{
return Encoding.ASCII.GetString(dataBytes, start, size);
}
default:
{
throw (new Exception("未定义的编码格式"));
}
}
}
/// <summary>
/// Saves the file.
/// </summary>
/// <param name="FileName">Name of the file.</param>
/// <param name="Result">The result.</param>
public void SaveFile(string FileName, byte[] Result)
{
try
{
FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate);
fs.Write(Result, 5 + Result[1], Result[2] * 65536 + Result[3] * 256 + Result[4]);
fs.Flush();
fs.Close();
}
catch
{
}
}
StreamWriter writer = null;
/// <summary>
/// Saves the file.
/// </summary>
/// <param name="FileName">Name of the file.</param>
/// <param name="Result">The result.</param>
public void WriteFile(string FileName, string Result)
{
try
{
if (writer == null)
{
writer = new StreamWriter(FileName);
}
writer.Write(string.Concat(Result.ToString(), Environment.NewLine));
writer.Flush();
}
catch
{
}
}
/// <summary>
/// 数据编码
/// </summary>
/// <param name="datagram">需要编码的报文</param>
/// <returns>编码后的数据</returns>
public virtual byte[] GetTextBytes(string datagram)
{
byte[] rbyte = new byte[Encoding.UTF8.GetBytes(datagram).Length + 1];
rbyte[0] = 0x55;
switch (_encodingMothord)
{
case EncodingMothord.Default:
{
Encoding.Default.GetBytes(datagram, 0, datagram.Length, rbyte, 1);
return rbyte;
}
case EncodingMothord.Unicode:
{
Encoding.Unicode.GetBytes(datagram, 0, datagram.Length, rbyte, 1);
return rbyte;
}
case EncodingMothord.UTF8:
{
Encoding.UTF8.GetBytes(datagram, 0, datagram.Length, rbyte, 1);
return rbyte;
}
case EncodingMothord.ASCII:
{
Encoding.ASCII.GetBytes(datagram, 0, datagram.Length, rbyte, 1);
return rbyte;
}
default:
{
throw (new Exception("未定义的编码格式"));
}
}
}
public virtual byte[] GetFileBytes(string FilePath)
{
if (File.Exists(FilePath))
{
string fileName = Path.GetFileName(FilePath);
byte[] bytFileName = this.GetTextBytes(fileName);
FileStream fs = new FileStream(FilePath, FileMode.Open);
Byte[] RByte = new byte[fs.Length + 5 + bytFileName.Length];
RByte[0] = 0x66;
RByte[1] = (byte)(bytFileName.Length);
RByte[2] = (byte)(fs.Length / 65536);
RByte[3] = (byte)(fs.Length / 256);
RByte[4] = (byte)(fs.Length % 256);
bytFileName.CopyTo(RByte, 5);
fs.Read(RByte, 5 + bytFileName.Length, (int)fs.Length);
return RByte;
}
else
{
throw (new Exception("文件不存在"));
}
}
}
}

View File

@ -0,0 +1,114 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleGetPLCData.CS
{
/// <summary>
/// 数据报文分析器,通过分析接收到的原始数据,得到完整的数据报文.
/// 继承该类可以实现自己的报文解析方法.
/// 通常的报文识别方法包括:固定长度,长度标记,标记符等方法
/// 本类的现实的是标记符的方法,你可以在继承类中实现其他的方法
/// </summary>
public class DatagramResolver
{
/// <summary>
/// 报文结束标记
/// </summary>
private string endTag;
/// <summary>
/// 返回结束标记
/// </summary>
public string EndTag
{
get
{
return endTag;
}
}
/// <summary>
/// 受保护的默认构造函数,提供给继承类使用
/// </summary>
protected DatagramResolver()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="endTag">报文结束标记</param>
public DatagramResolver(string endTag)
{
if (endTag == null)
{
throw (new ArgumentNullException("结束标记不能为null"));
}
if (endTag == "")
{
throw (new ArgumentException("结束标记符号不能为空字符串"));
}
this.endTag = endTag;
}
/// <summary>
/// 解析报文
/// </summary>
/// <param name="rawDatagram">原始数据,返回未使用的报文片断,
/// 该片断会保存在Session的Datagram对象中</param>
/// <returns>报文数组,原始数据可能包含多个报文</returns>
public virtual string[] Resolve(ref string rawDatagram)
{
ArrayList datagrams = new ArrayList();
//末尾标记位置索引
int tagIndex = -1;
while (true)
{
tagIndex = rawDatagram.IndexOf(endTag, tagIndex + 1);
if (tagIndex == -1)
{
break;
}
else
{
//按照末尾标记把字符串分为左右两个部分
string newDatagram = rawDatagram.Substring(
0, tagIndex + endTag.Length);
datagrams.Add(newDatagram);
if (tagIndex + endTag.Length >= rawDatagram.Length)
{
rawDatagram = "";
break;
}
rawDatagram = rawDatagram.Substring(tagIndex + endTag.Length,
rawDatagram.Length - newDatagram.Length);
//从开始位置开始查找
tagIndex = 0;
}
}
string[] results = new string[datagrams.Count];
datagrams.CopyTo(results);
return results;
}
}
}

View File

@ -0,0 +1,688 @@
using ConsoleGetPLCData.CS;
using GetData_PLC;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ConsoleGetPLCData
{
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
class GETDataGPRS
{
stStation Station = new stStation();
private ModbusIpMaster master;
private TcpClient client;
private bool WriteDateTimeFlag;
public static ManualResetEvent allDone = new ManualResetEvent(false);
DataTable dtToday_Flow = new DataTable(); //今日流量总累计 表格
DataTable dtYesToday_FLOW = new DataTable();//昨日流量总累计 表格
//private bool readFlag; //读取盘古积算仪 昨日 今日累积量标志
bool SaveFlag; //保存盘古积算仪 总累计量标志
DataRow[] drDataTemp;//GPRS PLC设备采集上来的数据临时存放再赋值
static int intTimes = 0;
static bool blReadSucess = false;
///构造函数 初始化
public GETDataGPRS(stStation strZhan)
{
Station = strZhan;
}
/// <summary>
/// 线程入口函数
/// </summary>
public void GetDataStart()
{
GetDataByGPRS_YB();//异步通信
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + "准备采集" + Station.ZCName + "数据");
}
#region ---------------------
/// <summary>
/// 带地址的计量点设备,采用异步通信方式
/// </summary>
private void GetDataByGPRS_YB()
{
try
{
//当点击开始监听的时候 在服务器端创建一个负责监IP地址跟端口号的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(Station.ip);
//IPAddress ip = IPAddress.Parse("127.0.0.1");
//创建端口号对象
IPEndPoint point = new IPEndPoint(ip, Station.port);
//监听
socketWatch.Bind(point);
socketWatch.Listen(10);
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + Station.ZCName + "监听成功!");
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
//socketWatch.BeginAccept(new AsyncCallback(AcceptCallback), socketWatch);
}
catch (Exception ex)
{
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + Station.ZCName + ex.Message);
}
}
/// <summary>
/// 等待客户端的连接 并且创建与之通信用的Socket
/// </summary>
///
void Listen(object o)
{
Socket socketWatch = o as Socket;
//等待客户端的连接 并且创建一个负责通信的Socket
//while (true)
{
try
{
//开始一个一步操作接受一个连接尝试
socketWatch.BeginAccept(new AsyncCallback(AcceptCallback), socketWatch);
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + Station.ZCName + "连接成功!");
//开启 一个新线程不停的接受客户端发送过来的消息
}
catch
{ }
Thread.Sleep(1000);
}
}
/// <summary>
/// 异步通信回调函数
/// </summary>
/// <param name="ar"></param>
public void AcceptCallback(IAsyncResult ar)
{
//allDone.Set();
Socket socketSend = (Socket)ar.AsyncState;
Socket socketRecive = socketSend.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = socketRecive;
if (Station.MeterTYPE == "1" || Station.MeterTYPE == "5")
{
readTodayYesTerdayQL();
}
if (Station.MeterTYPE == "0") //PLC赋值 定义一个数组 暂存 采集上来的所有计量点的数据再一并赋值给数据集jldID 和ID转换
{
int jldMax = ProgramGetData.dsJLDataRealTime.Tables[this.Station.ZCID].Rows.Count;
}
while (true)
{
try
{
byte[] SendByte = new byte[8];
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "正在采集......");
switch (Station.MeterTYPE)
{
case "0": //施耐德PLC 异步通讯 采集计量点数目变化 来判断采集的是哪一个计量点的数据
for (int i = 0; i < ProgramGetData.dsJLDataRealTime.Tables[this.Station.ZCID].Rows.Count; i++) //计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
int _jldID = int.Parse(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[i]["jld_id"].ToString());
//读取PLC的时钟
SendByte = TranData.Modbus_ReadData(1, 3, 16, 4);
SendByte = TranData.Modbus_ReadData(1, 3, 400 + _jldID * 20, 20);
socketRecive.Send(SendByte);
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_PLC), state);
Thread.Sleep(1000);
}
break;
case "1": //盘古积算仪
for (int i = 0; i < ProgramGetData.dsJLDataRealTime.Tables[this.Station.ZCID].Rows.Count; i++) //计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
int _jldID = int.Parse(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[i]["jld_id"].ToString());
SendByte = TranData.Modbus_ReadData(_jldID + 1, 3, 0, 16);
socketRecive.Send(SendByte);
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-发送采集命令:" + getString(SendByte, 8));
Thread.Sleep(1000);
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_PG), state);
if ((DateTime.Now.Hour == 0 & DateTime.Now.Minute == 0 & DateTime.Now.Second == 10)) //过了零点存取累计总量,然后读取昨日累计总量
{
SaveFlag = true;
}
if (SaveFlag & blReadSucess)
{
SaveTable(0);
readTodayYesTerdayQL();
//Console.WriteLine("存数据库成功" + readFlag.ToString() + timeNow.ToString() + "--" + (SbType == "2" & (timeNow.Hour == 20 & timeNow.Minute == 45 & timeNow.Second > 10) & readFlag == false).ToString ());
SaveFlag = false;
}
}
break;
case "2": //103
for (int i = 0; i < ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows.Count; i++) //计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
int _jldID = int.Parse(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[i]["jld_id"].ToString());
SendByte = TranData.Modbus_ReadData(_jldID + 1, 3, 7102, 22);
socketRecive.Send(SendByte);
Console.WriteLine(DateTime.Now.ToString()+"------" + Station.ZCName + "-发送采集命令:" + getString(SendByte,8));
Thread.Sleep(1000);
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_103), state);
}
break;
case "3":
break;
case "4": //爱知超声波流量计
for (int i = 0; i < ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows.Count; i++) //计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
int _jldID = int.Parse(ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[i]["jld_id"].ToString());
SendByte = TranData.Modbus_ReadData(_jldID + 1, 3, 511, 15);
socketRecive.Send(SendByte);
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-发送采集命令:" + getString(SendByte, 8));
Thread.Sleep(2000);
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_CSB), state);
}
break;
case "5":// 温州福鑫旋进旋涡流量计
for (int i = 0; i < ProgramGetData.dsJLDataRealTime.Tables[this.Station.ZCID].Rows.Count; i++) //计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
int _jldID = int.Parse(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[i]["jld_id"].ToString());
SendByte = TranData.Modbus_ReadData(_jldID + 1, 3, 4, 30);
socketRecive.Send(SendByte);
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-发送采集命令:" + getString(SendByte, 8));
Thread.Sleep(1000);
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_WZFX), state);
if ((DateTime.Now.Hour == 0 & DateTime.Now.Minute == 0 & DateTime.Now.Second == 10)) //过了零点存取累计总量,然后读取昨日累计总量
{
SaveFlag = true;
}
if (SaveFlag & blReadSucess )
{
SaveTable(0);
readTodayYesTerdayQL();
//Console.WriteLine("存数据库成功" + readFlag.ToString() + timeNow.ToString() + "--" + (SbType == "2" & (timeNow.Hour == 20 & timeNow.Minute == 45 & timeNow.Second > 10) & readFlag == false).ToString ());
SaveFlag = false;
}
}
break;
case "6": //腾空PLC
for (int i = 0; i < ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows.Count; i++) //计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
int _jldID = int.Parse(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[i]["jld_id"].ToString());
SendByte = TranData.Modbus_ReadData(_jldID + 1, 3, 10100, 22);
socketRecive.Send(SendByte);
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-发送采集命令:" + getString(SendByte, 8));
Thread.Sleep(1000);
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_103), state);
}
break;
default:
break;
}
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString() + "------" + ex.Message );
}
if (DateTime.Now.Hour == 23 && DateTime.Now.Minute == 59)
{
Thread.Sleep(2000);
}
else
{
if (intTimes > 5)
{
intTimes = 5;
Thread.Sleep(Station.readDiffTime);
}
else
{
Thread.Sleep(3000);
}
}
intTimes = intTimes + 1;
}
}
public static string getString(Byte[] temp,int intCount)
{
string strTemp = "";
for (int i = 0; i < intCount; i++)
{
strTemp = strTemp + temp[i].ToString() + " ";
}
return strTemp;
}
/// <summary>
/// 解析GPRS读取的PLC数据
/// </summary>
/// <param name="ar"></param>
public void ReadCallback_PLC(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket socketRecive = state.workSocket;
//从远程设备读取数据
int bytesRead = socketRecive.EndReceive(ar);
int dataNum;
dataNum = state.buffer[2];
try
{
if (dataNum == 8) //读取的时钟
{
ProgramGetData.dsZhanDateTime.Tables[Station.ZCID].Rows[0]["PLCTime"] = getPLCDateTime(state.buffer); //获取PLC时间
}
}
catch
{ }
try
{
if (dataNum == 40) // 代表1个计量点 jldID=0
{
DataRow[] drJldS = { drDataTemp[0] };
DataRow[] drData = TranData.GetDataTran_GPRS(drJldS, state.buffer, Station.MeterTYPE);
drDataTemp[0].ItemArray = drData[0].ItemArray;
}
}
catch
{ }
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_PLC), state);
}
catch (Exception ex)
{
}
}
/// <summary>
/// 获取并解析福鑫的数据
/// </summary>
/// <param name="ar"></param>
public void ReadCallback_WZFX(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket socketRecive = state.workSocket;
//从远程设备读取数据
int bytesRead = socketRecive.EndReceive(ar);
int dataNum;
dataNum = state.buffer[2];
int jldID = state.buffer[0] - 1;
if (dataNum == 60)
{
Console.WriteLine(DateTime.Now.ToString()+ "------" + Station.ZCName + "-接收数据:" + getString(state.buffer, dataNum));
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID].ItemArray = TranData.GetDataTran_GPRS(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID], state.buffer, Station.MeterTYPE).ItemArray;
blReadSucess = true;
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"] = ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"];
try
{
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["CXFlag"] = TranData.GetCxFlag(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SSGKLL"].ToString(), ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["CLXX"].ToString(), ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["CLSX"].ToString());
}
catch { }
ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["Gr"] = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SYL"];
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SYL"] = "";
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_WZFX), state);
}
#region //提取昨日凌晨总累积量 计算今日量
try
{
string strTotalFlowNow = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["LJL"].ToString();
DataRow[] drTotay; ;
drTotay = dtToday_Flow.Select("JLD_ID in( '" + jldID + "')");
//Console.WriteLine("时间:" + DateTime.Now + "JLD_ID in( '" + jldID + "')--" + drTotay.Length.ToString() + "\n");
if (drTotay.Length == 0) //如果今日流量记录为空 把当前的流量总量写入表格 并保存到数据库中
{
DataRow drToday = dtToday_Flow.NewRow();
drToday["rtime"] = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
drToday["station_id"] = Station.ZCID;
drToday["jld_id"] = jldID;
drToday["flowtotal"] = strTotalFlowNow;
dtToday_Flow.Rows.Add(drToday);
SaveFlag = true;
}
else
{
//今日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JRL"] = float.Parse(strTotalFlowNow) - float.Parse(drTotay[0]["flowtotal"].ToString());
}
DataRow[] drYesterday;
drYesterday = dtYesToday_FLOW.Select("JLD_ID in ('" + jldID + "')");
//Console.WriteLine("时间:" + DateTime.Now + "JLD_ID in( '" + jldID + "')--" + drYesterday.Length.ToString() + "\n");
if (drYesterday.Length < 1)
{
//昨日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["ZRL"] = "";
}
else
{
//昨日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["ZRL"] = float.Parse(drTotay[0]["flowtotal"].ToString()) - float.Parse(drYesterday[0]["flowtotal"].ToString()); ;
}
}
catch { }
#endregion
}
catch
{
blReadSucess = false;
}
}
/// <summary>
/// 获取并解析盘古积算仪的数据
/// </summary>
/// <param name="ar"></param>
public void ReadCallback_PG(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket socketRecive = state.workSocket;
//从远程设备读取数据
int bytesRead = socketRecive.EndReceive(ar);
int dataNum;
dataNum = state.buffer[2];
int jldID = state.buffer[0] - 1;
if (dataNum == 32)
{
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-接收数据:" + getString(state.buffer, dataNum));
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID].ItemArray = TranData.GetDataTran_GPRS(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID], state.buffer, Station.MeterTYPE).ItemArray;
blReadSucess = true;
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"] = ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"];
try
{
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["CXFlag"] = TranData.GetCxFlag(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SSGKLL"].ToString(), ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["CLXX"].ToString(), ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["CLSX"].ToString());
}
catch (Exception ex)
{ }
ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["Gr"] = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SYL"];
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SYL"] = "";
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_PG), state);
}
#region //提取昨日凌晨总累积量 计算今日量
try
{
string strTotalFlowNow = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["LJL"].ToString();
DataRow[] drTotay; ;
drTotay = dtToday_Flow.Select("JLD_ID in( '" + jldID + "')");
//Console.WriteLine("时间:" + DateTime.Now + "JLD_ID in( '" + jldID + "')--" + drTotay.Length.ToString() + "\n");
if (drTotay.Length == 0) //如果今日流量记录为空 把当前的流量总量写入表格 并保存到数据库中
{
DataRow drToday = dtToday_Flow.NewRow();
drToday["rtime"] = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
drToday["station_id"] = Station.ZCID;
drToday["jld_id"] = jldID;
drToday["flowtotal"] = strTotalFlowNow;
dtToday_Flow.Rows.Add(drToday);
SaveFlag = true;
}
else
{
//今日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JRL"] = float.Parse(strTotalFlowNow) - float.Parse(drTotay[0]["flowtotal"].ToString());
}
DataRow[] drYesterday;
drYesterday = dtYesToday_FLOW.Select("JLD_ID in ('" + jldID + "')");
//Console.WriteLine("时间:" + DateTime.Now + "JLD_ID in( '" + jldID + "')--" + drYesterday.Length.ToString() + "\n");
if (drYesterday.Length < 1)
{
//昨日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["ZRL"] = "";
}
else
{
//昨日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["ZRL"] = float.Parse(drTotay[0]["flowtotal"].ToString()) - float.Parse(drYesterday[0]["flowtotal"].ToString()); ;
}
}
catch { }
#endregion
}
catch
{
blReadSucess = false;
}
}
/// <summary>
/// 获取并解析爱知超声波的数据
/// </summary>
/// <param name="ar"></param>
public void ReadCallback_CSB(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket socketRecive = state.workSocket;
//从远程设备读取数据
int bytesRead = socketRecive.EndReceive(ar);
int dataNum;
dataNum = state.buffer[2];
int jldID = state.buffer[0] - 1;
if (dataNum == 30)
{
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-接收数据:" + getString(state.buffer, dataNum));
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID].ItemArray = TranData.GetDataTran_GPRS(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID], state.buffer, Station.MeterTYPE).ItemArray;
blReadSucess = true;
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"] = ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"];
try
{
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["CXFlag"] = TranData.GetCxFlag(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SSGKLL"].ToString(), ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["CLXX"].ToString(), ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["CLSX"].ToString());
}
catch { }
ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["Gr"] = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SYL"];
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["SYL"] = "";
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_PG), state);
}
#region //提取昨日凌晨总累积量 计算今日量
try
{
string strTotalFlowNow = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["LJL"].ToString();
DataRow[] drTotay; ;
drTotay = dtToday_Flow.Select("JLD_ID in( '" + jldID + "')");
//Console.WriteLine("时间:" + DateTime.Now + "JLD_ID in( '" + jldID + "')--" + drTotay.Length.ToString() + "\n");
if (drTotay.Length == 0) //如果今日流量记录为空 把当前的流量总量写入表格 并保存到数据库中
{
DataRow drToday = dtToday_Flow.NewRow();
drToday["rtime"] = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
drToday["station_id"] = Station.ZCID;
drToday["jld_id"] = jldID;
drToday["flowtotal"] = strTotalFlowNow;
dtToday_Flow.Rows.Add(drToday);
SaveFlag = true;
}
else
{
//今日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JRL"] = float.Parse(strTotalFlowNow) - float.Parse(drTotay[0]["flowtotal"].ToString());
}
DataRow[] drYesterday;
drYesterday = dtYesToday_FLOW.Select("JLD_ID in ('" + jldID + "')");
//Console.WriteLine("时间:" + DateTime.Now + "JLD_ID in( '" + jldID + "')--" + drYesterday.Length.ToString() + "\n");
if (drYesterday.Length < 1)
{
//昨日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["ZRL"] = "";
}
else
{
//昨日量
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["ZRL"] = float.Parse(drTotay[0]["flowtotal"].ToString()) - float.Parse(drYesterday[0]["flowtotal"].ToString()); ;
}
}
catch { }
#endregion
}
catch
{
blReadSucess = false;
}
}
/// <summary>
/// 获取并解析103的数据
/// </summary>
/// <param name="ar"></param>
public void ReadCallback_103(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket socketRecive = state.workSocket;
//从远程设备读取数据
int bytesRead = socketRecive.EndReceive(ar);
int dataNum;
dataNum = state.buffer[2];
int jldID = state.buffer[0] - 1;
if (dataNum == 44)
{
Console.WriteLine(DateTime.Now.ToString() + "------" + Station.ZCName + "-接收数据:" + getString(state.buffer, dataNum));
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID].ItemArray = TranData.GetDataTran_GPRS(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID], state.buffer, Station.MeterTYPE).ItemArray;
blReadSucess = true;
ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"] = ProgramGetData.dsPparameter.Tables[Station.ZCID].Rows[jldID]["JLD_NAME"];
socketRecive.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback_103), state);
}
}
catch
{
}
}
/// <summary>
/// 获得打印数据监视字符串
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
private string strPrint(DataRow dr)
{
return dr["JLD_NAME"] + "\t瞬时量" + dr["SSL"] + "\t温度" + dr["WD"] + "\t压力" + dr["YL"] + "\t累积量" + dr["LJL"];
}
/// <summary>
/// 对于没在PLC的设备每次采集程序启动读取存储的昨日量 今日量的总累积量
/// </summary>
private void readTodayYesTerdayQL()
{
DateTime _Date = DateTime.Now.AddDays(-1);
_Date = DateTime.Parse(_Date.ToString("yyyy-MM-dd"));
string strSQL = SQL_Strings.strSQL_Read_Today_YesterDay_Flow + " where STATION_ID='" + Station.ZCID + "' and RTIME=to_date('" + _Date.ToShortDateString() + "', 'yyyy-mm-dd') order by JLD_ID";
dtToday_Flow = OracleLink.ExecuteDataTable(strSQL, "DTJK", "");
strSQL = SQL_Strings.strSQL_Read_Today_YesterDay_Flow + " where STATION_ID='" + Station.ZCID + "' and RTIME=to_date('" + _Date.AddDays(-1).ToShortDateString() + "', 'yyyy-mm-dd') order by JLD_ID";
dtYesToday_FLOW = OracleLink.ExecuteDataTable(strSQL, "DTJK", "");
}
/// <summary>
/// 保存昨日量、今日量到数据库
/// </summary>
/// <param name="intSaveFlag"></param>
private void SaveTable(int intSaveFlag)
{
SaveFlag = true;
Thread.Sleep(2000);
string strSQL = SQL_Strings.strSQL_Read_Today_YesterDay_Flow + " where STATION_ID='" + Station.ZCID + "'";
OracleLink.SaveDataTable(strSQL, dtToday_Flow, "DTJK", "");
}
/// <summary>
/// 读取GPRS站场PLC的时间
/// </summary>
/// <returns></returns>
private string getPLCDateTime(byte[] plc_DateTime)
{
string[] Uplc_DateTime = new string[4];
Uplc_DateTime[0] = plc_DateTime[4].ToString("X2") + plc_DateTime[3].ToString("X2");
Uplc_DateTime[1] = plc_DateTime[6].ToString("X2") + plc_DateTime[5].ToString("X2");
Uplc_DateTime[2] = plc_DateTime[8].ToString("X2") + plc_DateTime[7].ToString("X2");
Uplc_DateTime[3] = plc_DateTime[10].ToString("X2") + plc_DateTime[9].ToString("X2");
string plc_Year = Uplc_DateTime[0];
string plc_Month = Uplc_DateTime[1];
string plc_Minute = Uplc_DateTime[2];
string plc_Second = Uplc_DateTime[3];
string plcDatetime = plc_Year + "-" + plc_Month.Substring(0, 2) + "-" + plc_Month.Substring(2, 2) + " " + plc_Minute.Substring(0, 2) + ":" + plc_Minute.Substring(2, 2) + ":" + plc_Second;//.Substring(0, 2);// +plc_Second.Substring(2, 2);
return plcDatetime;
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,341 @@
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ConsoleGetPLCData.CS
{
class GetDataNet
{
stStation Station = new stStation();
private ModbusIpMaster master;
private TcpClient client;
private bool WriteDateTimeFlag;
public static ManualResetEvent allDone = new ManualResetEvent(false);
///构造函数 初始化
public GetDataNet(stStation strZhan)
{
Station = strZhan;
}
/// <summary>
/// 线程入口函数
/// </summary>
public void GetPLCData()
{
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + "开始采集" + Station.ZCName + "数据");
GetDataByNet();
}
#region
/// <summary>
/// 局域网获取PLC的数据
/// </summary>
private void GetDataByNet()
{
while (true)
{
using (client = new TcpClient())
{
try
{
client.Connect(Station.ip, Station.port);
master = ModbusIpMaster.CreateIp(client);
int JldNum = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows.Count;
}
catch (SystemException err)
{
if (err.Message != null)
{
// string strZCIDtemp[]=Station.ZCID.Split ('_');
// if (strZCIDtemp .Length >1)
//{
//}
// else
// {
int JldNum = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows.Count;
//}
for (int i = 0; i < ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows.Count; i++) //PLC计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
{
//故障赋值
//TranData.netError(ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows[i]);
}
foreach (DataRow dr in ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows)
{
TranData.netError(dr);
}
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + Station.ZCName + Station.ZCID + "网络连接故障!");
}
}
try
{
int JldNum = ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows.Count;
ProgramGetData.dsZhanDateTime.Tables[Station.ZCID].Rows[0]["PLCTime"] = getPLCDateTime(); //获取PLC时间
SetPLCDateTime(); //同步PLC时间
//PLC计量点读取循环 循环数由主程序建立该站的实时数据表中的记录数决定
foreach (DataRow dr in ProgramGetData.dsJLDataRealTime.Tables[Station.ZCID].Rows)
{
int _jldID = 0;
try
{
_jldID = int.Parse(dr["jld_id"].ToString());
}
catch (Exception ex)
{
}
DataRow[] drPars = ProgramGetData.dsPparameter.Tables[Station.ZCID].Select("jld_id='" + _jldID.ToString() + "'");
//判断是否读取计量点参数
if (dr["readparflag"].ToString() == "1")
{
ushort[] ParWord = master.ReadHoldingRegisters(Convert.ToUInt16((int)(24360 + (240 * _jldID))), 60);
drPars[0].ItemArray = TranData.GetPLCPar_Net(drPars[0], ParWord, Station.MeterTYPE).ItemArray;
dr["readparflag"] = "0";
drPars[0]["ReadTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
//采集实时计量数据
ushort[] Word = master.ReadHoldingRegisters(Convert.ToUInt16((int)(400 + (20 * _jldID))), 20);
//解析数据 根据设备类型解析
dr.ItemArray = TranData.GetDataTran_Net(dr, Word, Station.MeterTYPE).ItemArray;
//读取计算脉冲仪表的工况流量或雷诺数
string strPlusNum = "";
try
{
if (dr["MeterTYPE"].ToString() == "脉冲")
{
//采集脉冲数
ushort[] PlusNum = master.ReadHoldingRegisters(Convert.ToUInt16((int)(5000 + (80 * _jldID))), 4);
//采集K系数
ushort[] PlusK = master.ReadHoldingRegisters(Convert.ToUInt16((int)(2600 + (30 * _jldID))), 4);
string ssgkll = TranData.GetFlowGK(PlusNum, PlusK, out strPlusNum);
dr["SSGKLL"] = ssgkll;
string strCxXx = drPars[0]["CLXX"].ToString();
string strCxSx = drPars[0]["CLSX"].ToString();
dr["CXFlag"] = TranData.GetCxFlag(ssgkll, strCxXx, strCxSx);
}
dr["JLD_NAME"] = drPars[0]["JLD_NAME"];
if (dr["MeterTYPE"].ToString() == "脉冲") dr["CY"] = strPlusNum;
//差压式流量计则计算雷诺数
if (dr["MeterTYPE"].ToString() != "脉冲")
{
string strXdmd = drPars[0]["Gr"].ToString();
string strGj = drPars[0]["gj"].ToString();
float sngDlnd = 19768.8f;
string strQn = dr["SSL"].ToString();
if (strQn == "") strQn = "0";
if (strXdmd == "") strXdmd = "0";
if (Station.ZCID == "4708")
{
}
if (strGj != "")
{
dr["SSGKLL"] = (1615.7238 * Convert.ToSingle(strQn) * Convert.ToSingle(strXdmd) / Convert.ToSingle(strGj)).ToString("#.#");
}
dr["CXFlag"] = TranData.GetCxFlag(dr["CY"].ToString());
}
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
if (ex.Message != null)
{
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + Station.ZCName + Station.ZCID + "计量点 " + "读取寄存器错误!");
continue;
}
}
Thread.Sleep(Station.readDiffTime);
}
}
}
/// <summary>
/// 将服务器的时间同步到PLC
/// </summary>
private void SetPLCDateTime()
{
DateTime SAVETIME = DateTime.Now;
if ((SAVETIME.Hour.ToString() == "16" && SAVETIME.Minute == 00 && WriteDateTimeFlag == false) || (ProgramGetData.dsZhanDateTime.Tables[Station.ZCID].Rows[0]["TongBuFlag"].ToString() == "同步")) //到每日23:40 同步时间
{
try
{
ushort[] DateData = getTimeData();
master.WriteSingleRegister(380, DateData[0]);
master.WriteSingleRegister(381, DateData[1]);
master.WriteSingleRegister(382, DateData[2]);
master.WriteSingleRegister(383, DateData[3]);
master.WriteSingleRegister(384, 1);
master.WriteSingleRegister(386, 1);
ProgramGetData.dsZhanDateTime.Tables[Station.ZCID].Rows[0]["TongBuTime"] = SAVETIME;
ProgramGetData.dsZhanDateTime.Tables[Station.ZCID].Rows[0]["TongBuFlag"] = "成功";
WriteDateTimeFlag = true;
}
catch (SystemException error)
{
if (error.Message != null)
{
ProgramGetData.strAppend(DateTime.Now.ToString() + "------" + Station.ZCName + Station.ZCID + "时间同步失败!");
}
}
}
if (SAVETIME.Hour.ToString() != "16" && SAVETIME.Minute != 00) // 同步时间标志位false
{
WriteDateTimeFlag = false;
}
}
/// <summary>
/// 读取局域网站场PLC的时间
/// </summary>
/// <returns></returns>
private string getPLCDateTime()
{
//读取站场PLC的系统时间
ushort[] plc_DateTime = master.ReadHoldingRegisters(16, 4);
string plc_Year = plc_DateTime[0].ToString("x4");
string plc_Month = plc_DateTime[1].ToString("x4");
string plc_Minute = plc_DateTime[2].ToString("x4");
string plc_Second = plc_DateTime[3].ToString("x4");
string plcDatetime = plc_Year + "-" + plc_Month.Substring(0, 2) + "-" + plc_Month.Substring(2, 2) + " " + plc_Minute.Substring(0, 2) + ":" + plc_Minute.Substring(2, 2) + ":" + plc_Second;//.Substring(0, 2);// +plc_Second.Substring(2, 2);
return plcDatetime;
}
/// <summary>
/// 将日期时间转换为Ushort类型数组
/// </summary>
/// <returns></returns>
private ushort[] getTimeData()
{
ushort[] data = new ushort[4];
DateTime now = new DateTime();
now = DateTime.Now;
string str = "";
str = now.Year.ToString();
int num4 = Convert.ToInt16(str.Substring(0, 1));
int num5 = Convert.ToInt16(str.Substring(1, 1));
int num6 = Convert.ToInt16(str.Substring(2, 1));
int num7 = Convert.ToInt16(str.Substring(3, 1));
data[0] = (ushort)((((((num4 * 0x10) * 0x10) * 0x10) + ((num5 * 0x10) * 0x10)) + (num6 * 0x10)) + num7);
string str3 = "";
if (now.Month < 10)
{
str3 = str3 + "0" + now.Month.ToString();
}
else
{
str3 = str3 + now.Month.ToString();
}
if (now.Day < 10)
{
str3 = str3 + "0" + now.Day.ToString();
}
else
{
str3 = str3 + now.Day.ToString();
}
str = str3;
num4 = Convert.ToInt16(str.Substring(0, 1));
num5 = Convert.ToInt16(str.Substring(1, 1));
num6 = Convert.ToInt16(str.Substring(2, 1));
num7 = Convert.ToInt16(str.Substring(3, 1));
data[1] = (ushort)((((((num4 * 0x10) * 0x10) * 0x10) + ((num5 * 0x10) * 0x10)) + (num6 * 0x10)) + num7);
string str4 = "";
if (now.Hour < 10)
{
str4 = str4 + "0" + now.Hour.ToString();
}
else
{
str4 = str4 + now.Hour.ToString();
}
if (now.Minute < 10)
{
str4 = str4 + "0" + now.Minute.ToString();
}
else
{
str4 = str4 + now.Minute.ToString();
}
str = str4;
num4 = Convert.ToInt16(str.Substring(0, 1));
num5 = Convert.ToInt16(str.Substring(1, 1));
num6 = Convert.ToInt16(str.Substring(2, 1));
num7 = Convert.ToInt16(str.Substring(3, 1));
data[2] = (ushort)((((((num4 * 0x10) * 0x10) * 0x10) + ((num5 * 0x10) * 0x10)) + (num6 * 0x10)) + num7);
string str5 = "";
if (now.Second < 10)
{
str5 = str5 + "000" + now.Second.ToString();
}
else
{
str5 = str5 + "00" + now.Second.ToString();
}
str = str5;
num4 = Convert.ToInt16(str.Substring(0, 1));
num5 = Convert.ToInt16(str.Substring(1, 1));
num6 = Convert.ToInt16(str.Substring(2, 1));
num7 = Convert.ToInt16(str.Substring(3, 1));
data[3] = (ushort)((((((num4 * 0x10) * 0x10) * 0x10) + ((num5 * 0x10) * 0x10)) + (num6 * 0x10)) + num7);
return data;
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleGetPLCData.CS
{
public delegate void NetEvent(object sender, NetEventArgs e);
/// <summary>
/// 服务器程序的事件参数,包含了激发该事件的会话对象
/// </summary>
public class NetEventArgs : EventArgs
{
#region
/// <summary>
/// 客户端与服务器之间的会话
/// </summary>
private Session _client;
#endregion
#region
/// <summary>
/// 构造函数
/// </summary>
/// <param name="client">客户端会话</param>
public NetEventArgs(Session client)
{
if (null == client)
{
throw (new ArgumentNullException());
}
_client = client;
}
#endregion
#region
/// <summary>
/// 获得激发该事件的会话对象
/// </summary>
public Session Client
{
get
{
return _client;
}
}
#endregion
}
}

View File

@ -0,0 +1,282 @@

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using GetData_PLC;
namespace ConsoleGetPLCData.CS
{
class ScCal
{
string strError="";
public void ZhanXianScCal() //通过selcet语句从 oracle 输差配置读取站内所有输差类型 ,再分系统计算输差
{
Thread .Sleep (2000);
ProgramGetData.strAppend( DateTime.Now.ToString() + "------开始计算输差");
while (true)
{
DataSet dsSsData = new DataSet(); ;
DataTable dtTotal = new DataTable();
dtTotal.TableName = "TotalData";
try
{
dsSsData.ReadXml(ProgramGetData.strDataPath + "SsData.xml", XmlReadMode.ReadSchema);
for (int i = 0; i < dsSsData.Tables.Count; i++) //构建出实时数据总表
{
dtTotal.Merge(dsSsData.Tables[i].Copy());
}
dtTotal.WriteXml(ProgramGetData.strDataPath + "TotalData.xml",XmlWriteMode .WriteSchema);
if (dtTotal.Rows.Count > 0)
{
for (int i = 0; i < ProgramGetData.dtScRealTime.Rows.Count; i++)
{
Thread.Sleep(10); //暂停10毫秒 释放资源
ScDataCal(ProgramGetData.dtScRealTime.Rows[i], dtTotal);
}
ProgramGetData.dtScRealTime.WriteXml(ProgramGetData.strDataPath + "ScData.xml", XmlWriteMode.WriteSchema);
DataRow[] drScRealTime = ProgramGetData.dtScRealTime.Select("sctype='管线输差'"); //写线输差xml
DataTable dtScTemp = ProgramGetData.dtScRealTime.Clone();
for (int mm = 0; mm < drScRealTime.Length; mm++)
{
DataRow dr = dtScTemp.NewRow();
dr.ItemArray = drScRealTime[mm].ItemArray;
dtScTemp.Rows.Add(dr);
}
dtScTemp.WriteXml(ProgramGetData.strDataPath + "\\ScData\\XIANSC.xml", XmlWriteMode.WriteSchema);
drScRealTime = ProgramGetData.dtScRealTime.Select("sctype='站场输差'"); //写线输差xml
dtScTemp = ProgramGetData.dtScRealTime.Clone();
for (int mm = 0; mm < drScRealTime.Length; mm++)
{
DataRow dr = dtScTemp.NewRow();
dr.ItemArray = drScRealTime[mm].ItemArray;
dtScTemp.Rows.Add(dr);
}
dtScTemp.WriteXml(ProgramGetData.strDataPath + "\\ScData\\ZHANSC.xml", XmlWriteMode.WriteSchema);
drScRealTime = ProgramGetData.dtScRealTime.Select("sctype='自定义输差'"); //写线输差xml
dtScTemp = ProgramGetData.dtScRealTime.Clone();
for (int mm = 0; mm < drScRealTime.Length; mm++)
{
DataRow dr = dtScTemp.NewRow();
dr.ItemArray = drScRealTime[mm].ItemArray;
dtScTemp.Rows.Add(dr);
}
dtScTemp.WriteXml(ProgramGetData.strDataPath + "\\ScData\\ZDYSC.xml", XmlWriteMode.WriteSchema);
//drScRealTime = ProgramGetData.dtScRealTime.Select("sctype='管线输差' and DEPT_ID='14'"); //巡线一支队
//dtScTemp = ProgramGetData.dtScRealTime.Clone();
//for (int mm = 0; mm < drScRealTime.Length; mm++)
//{
// DataRow dr = dtScTemp.NewRow();
// dr.ItemArray = drScRealTime[mm].ItemArray;
// dtScTemp.Rows.Add(dr);
//}
//dtScTemp.WriteXml(ProgramGetData.strDataPath + "\\ScData\\14.xml", XmlWriteMode.WriteSchema);
}
}
catch (SystemException err)
{
if (err.Message != null)
{
ProgramGetData.strAppend( DateTime.Now.ToString() + "------输差计算读取总表格xml时 文件占用");
}
}
Thread.Sleep(1799);
}
}
private void ScDataCal(DataRow _DataRow, DataTable dtTotalData)
{
try
{
//_ScDataTable.Rows.Clear();
string strInJLD = _DataRow["IN_JLD_ID"].ToString();
string strOutJLD = _DataRow["OUT_JLD_ID"].ToString();
string strScType = _DataRow["SCTYPE"].ToString();
string Express = "";
Single SsSumIn = 0;
Single JrSumIn = 0;
Single ZrSumIn = 0;
Single SsSumOut = 0;
Single JrSumOut = 0;
Single ZrSumOut = 0;
string strIn_P = "";
string strOut_P = "";
if (strInJLD != "")
{
Express = "ID in(" + strInJLD + ")";
DataRow[] SumRow = dtTotalData.Select(Express);
if (SumRow.Length >= 0)
{
SsSumIn = 0; JrSumIn = 0; ZrSumIn = 0;
SsSumIn = sumColumon(SumRow, "SSL");
JrSumIn = sumColumon(SumRow, "JRL");
ZrSumIn = sumColumon(SumRow, "ZRL");
if (strScType == "管线输差")
{
for (int m = 0; m < SumRow.Length; m++)
{
strIn_P = strIn_P + SumRow[m]["YL"].ToString() + "★";
}
if (strIn_P.Length > 0)
strIn_P = strIn_P.Substring(0, strIn_P.Length - 1);
}
}
else
{
SsSumIn = 0; JrSumIn = 0; ZrSumIn = 0; strIn_P = "";
}
}
if (strOutJLD != "")
{
Express = "ID in(" + strOutJLD + ")";
DataRow[] SumRow = dtTotalData.Select(Express);
if (SumRow.Length >= 0)
{
SsSumOut = 0; JrSumOut = 0; ZrSumOut = 0;
SsSumOut = sumColumon(SumRow, "SSL");
JrSumOut = sumColumon(SumRow, "JRL");
ZrSumOut = sumColumon(SumRow, "ZRL");
if (strScType == "管线输差")
{
for (int m = 0; m < SumRow.Length; m++)
{
strOut_P = strOut_P + SumRow[m]["YL"].ToString() + "★";
}
if (strOut_P.Length > 0)
strOut_P = strOut_P.Substring(0, strOut_P.Length - 1);
}
}
else
{
SsSumOut = 0; JrSumOut = 0; ZrSumOut = 0; strOut_P = "";
}
}
_DataRow["IN_P"] =strIn_P ;
_DataRow["OUT_P"] = strOut_P ;
_DataRow["SsInTotal"] = SsSumIn.ToString("0.####");
_DataRow["SsOutTotal"] = SsSumOut.ToString("0.###");
_DataRow["SsSc"] = (SsSumOut - SsSumIn).ToString("0.####");
if (SsSumIn != 0)
{
_DataRow["SsPer"] = ((SsSumOut - SsSumIn) * 100 / SsSumIn).ToString("0.##") + "%";
}
else
{
if (SsSumOut == 0)
{
_DataRow["SsSc"] = "0";
_DataRow["SsPer"] = "0%";
}
else
{
_DataRow["SsPer"] = "故障";
}
}
_DataRow["JrInTotal"] = JrSumIn.ToString("0.####");
_DataRow["JrOutTotal"] = JrSumOut.ToString("0.###");
_DataRow["JrSc"] = (JrSumOut - JrSumIn).ToString("0.####");
if (JrSumIn != 0)
{
_DataRow["JrPer"] = ((JrSumOut - JrSumIn) * 100 / JrSumIn).ToString("0.##") + "%";
}
else
{
if (JrSumOut == 0)
{
_DataRow["JrSc"] = "0";
_DataRow["JrPer"] = "0%";
}
else
{
_DataRow["JrPer"] = "故障";
}
}
_DataRow["ZrInTotal"] = ZrSumIn.ToString("0.####");
_DataRow["ZrOutTotal"] = ZrSumOut.ToString("0.###");
_DataRow["ZrSc"] = (ZrSumOut - ZrSumIn).ToString("0.####");
if (ZrSumIn != 0)
{
_DataRow["ZrPer"] = ((ZrSumOut - ZrSumIn) * 100 / ZrSumIn).ToString("0.##") + "%";
}
else
{
if (ZrSumOut == 0)
{
_DataRow["ZrSc"] = "0";
_DataRow["ZrPer"] = "0%";
}
else
{
_DataRow["ZrPer"] = "故障";
}
}
}
catch (SystemException err)
{
if (err.Message != null)
{
ProgramGetData . strAppend( DateTime.Now.ToString() + "------" + "输差计算时出错");
}
}
}
private float sumColumon(DataRow[] _DataRow, string _ColumonName)
{
float FlowSum = 0;
foreach (DataRow Dr1 in _DataRow)
{
try
{
FlowSum = FlowSum + float.Parse(Dr1[_ColumonName].ToString());
}
catch (SystemException err)
{
if (err.Message != "")
{
continue;
}
}
}
return FlowSum;
}
}
}

View File

@ -0,0 +1,287 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace ConsoleGetPLCData.CS
{
/// <summary>
/// 客户端与服务器之间的会话类
///
/// 说明:
/// 会话类包含远程通讯端的状态,这些状态包括Socket,报文内容,
/// 客户端退出的类型(正常关闭,强制退出两种类型)
/// </summary>
public class Session : ICloneable
{
#region
/// <summary>
/// 会话ID
/// </summary>
private SessionId _id;
/// <summary>
/// 客户端发送到服务器的报文
/// 注意:在有些情况下报文可能只是报文的片断而不完整
/// </summary>
private string _datagram;
/// <summary>
/// 客户端发送到服务器的以字节形式的报文,
/// 注意:在有些情况下报文可能只是报文的片断而不完整
/// </summary>
private byte[] _databuffer;
/// <summary>
/// 客户端的Socket
/// </summary>
private Socket _cliSock;
/// <summary>
/// 客户端的退出类型
/// </summary>
private ExitType _exitType;
/// <summary>
/// 退出类型枚举
/// </summary>
public enum ExitType
{
NormalExit,
ExceptionExit
};
#endregion
#region
/// <summary>
/// 返回会话的ID
/// </summary>
public SessionId ID
{
get
{
return _id;
}
}
/// <summary>
/// 存取会话的报文
/// </summary>
public string Datagram
{
get
{
return _datagram;
}
set
{
_datagram = value;
}
}
/// <summary>
/// 存取以二进制形式存放会话的报文
/// </summary>
public byte[] DataBuffer
{
get
{
return _databuffer;
}
set
{
_databuffer = value;
}
}
/// <summary>
/// 获得与客户端会话关联的Socket对象
/// </summary>
public Socket ClientSocket
{
get
{
return _cliSock;
}
}
/// <summary>
/// 存取客户端的退出方式
/// </summary>
public ExitType TypeOfExit
{
get
{
return _exitType;
}
set
{
_exitType = value;
}
}
#endregion
#region
/// <summary>
/// 使用Socket对象的Handle值作为HashCode,它具有良好的线性特征.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return (int)_cliSock.Handle;
}
/// <summary>
/// 返回两个Session是否代表同一个客户端
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
Session rightObj = (Session)obj;
return (int)_cliSock.Handle == (int)rightObj.ClientSocket.Handle;
}
/// <summary>
/// 重载ToString()方法,返回Session对象的特征
/// </summary>
/// <returns></returns>
public override string ToString()
{
string result = string.Format("Session:{0},IP:{1}",
_id, _cliSock.RemoteEndPoint.ToString());
//result.C
return result;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="cliSock">会话使用的Socket连接</param>
public Session(Socket cliSock)
{
Debug.Assert(cliSock != null);
_cliSock = cliSock;
_id = new SessionId((int)cliSock.Handle);
}
/// <summary>
/// 关闭会话
/// </summary>
public void Close()
{
Debug.Assert(_cliSock != null);
//关闭数据的接受和发送
_cliSock.Shutdown(SocketShutdown.Both);
//清理资源
_cliSock.Close();
}
#endregion
#region ICloneable
object System.ICloneable.Clone()
{
Session newSession = new Session(_cliSock);
newSession.Datagram = _datagram;
newSession.TypeOfExit = _exitType;
return newSession;
}
#endregion
}
/// <summary>
/// 唯一的标志一个Session,辅助Session对象在Hash表中完成特定功能
/// </summary>
public class SessionId
{
/// <summary>
/// 与Session对象的Socket对象的Handle值相同,必须用这个值来初始化它
/// </summary>
private int _id;
/// <summary>
/// 返回ID值
/// </summary>
public int ID
{
get
{
return _id;
}
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="id">Socket的Handle值</param>
public SessionId(int id)
{
_id = id;
}
/// <summary>
/// 重载.为了符合Hashtable键值特征
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj != null)
{
SessionId right = (SessionId)obj;
return _id == right._id;
}
else if (this == null)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 重载.为了符合Hashtable键值特征
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return _id;
}
/// <summary>
/// 重载,为了方便显示输出
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _id.ToString();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A2378DFD-D382-44FB-B280-61224B8E0ACA}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ConsoleGetPLCData</RootNamespace>
<AssemblyName>ConsoleGetPLCData</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>D:\GetPLCData\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="FtdAdapter, Version=1.8.0.0, Culture=neutral, PublicKeyToken=b5aba55fcbc8d946, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\FtdAdapter.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\log4net.dll</HintPath>
</Reference>
<Reference Include="Modbus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=b5aba55fcbc8d946, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\Modbus.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CS\Coder.cs" />
<Compile Include="CS\DatagramResolver.cs" />
<Compile Include="CS\GetDataNet.cs" />
<Compile Include="CS\GetDataThread.cs" />
<Compile Include="CS\GETDataGPRS——.cs" />
<Compile Include="CS\NetEvent.cs" />
<Compile Include="CS\ScCal.cs" />
<Compile Include="CS\Session.cs" />
<Compile Include="CS\TranData.cs" />
<Compile Include="CS\GETDataGPRS.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GetData_PLC\GetData_PLC.csproj">
<Project>{3412cc68-9c7e-4f3e-a9db-285efd5f55db}</Project>
<Name>GetData_PLC</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

1084
ConsoleGetPLCData/Program.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ConsoleGetPLCData")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ConsoleGetPLCData")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("5f2100e3-472a-4a38-becc-5a4631636f82")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Binary file not shown.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

Binary file not shown.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

View File

@ -0,0 +1,53 @@
2015/3/26 21:19:55------启动实时采集程序!
2015/3/26 21:19:55------开始初始化相关表格!
2015/3/26 21:19:55------查询数据库获取所有站场资料!
2015/3/26 21:19:56------站场资料获取成功!
2015/3/26 21:19:56------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:19:56------初始化完成!
2015/3/26 21:20:06------启动实时采集程序!
2015/3/26 21:20:06------开始初始化相关表格!
2015/3/26 21:20:06------查询数据库获取所有站场资料!
2015/3/26 21:20:06------站场资料获取成功!
2015/3/26 21:20:06------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:20:06------初始化完成!
2015/3/26 21:21:08------启动实时采集程序!
2015/3/26 21:21:08------开始初始化相关表格!
2015/3/26 21:21:08------查询数据库获取所有站场资料!
2015/3/26 21:21:08------站场资料获取成功!
2015/3/26 21:21:08------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:21:08------初始化完成!
2015/3/26 21:22:14------启动实时采集程序!
2015/3/26 21:22:14------开始初始化相关表格!
2015/3/26 21:22:14------查询数据库获取所有站场资料!
2015/3/26 21:22:18------站场资料获取成功!
2015/3/26 21:22:18------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:22:18------初始化完成!
2015/3/26 21:23:01------启动实时采集程序!
2015/3/26 21:23:01------开始初始化相关表格!
2015/3/26 21:23:01------查询数据库获取所有站场资料!
2015/3/26 21:23:01------站场资料获取成功!
2015/3/26 21:23:09------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:24:16------启动实时采集程序!
2015/3/26 21:24:16------开始初始化相关表格!
2015/3/26 21:24:16------查询数据库获取所有站场资料!
2015/3/26 21:24:17------站场资料获取成功!
2015/3/26 21:24:20------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:24:25------站场参数、计量点、时间结构和数据表格初始化完成!
2015/3/26 21:24:25------初始化输差表格 开始!
2015/3/26 21:24:25------初始化完成!
2015/3/26 21:26:16------启动实时采集程序!
2015/3/26 21:26:16------开始初始化相关表格!
2015/3/26 21:26:16------查询数据库获取所有站场资料!
2015/3/26 21:26:16------站场资料获取成功!
2015/3/26 21:26:16------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:26:17------站场参数、计量点、时间结构和数据表格初始化完成!
2015/3/26 21:26:17------初始化输差表格 开始!
2015/3/26 21:26:17------初始化完成!
2015/3/26 21:55:02------启动实时采集程序!
2015/3/26 21:55:02------开始初始化相关表格!
2015/3/26 21:55:02------查询数据库获取所有站场资料!
2015/3/26 21:55:02------站场资料获取成功!
2015/3/26 21:55:02------初始化局域网站场计量点表格和计量点参数
2015/3/26 21:55:03------站场参数、计量点、时间结构和数据表格初始化完成!
2015/3/26 21:55:03------初始化输差表格 开始!
2015/3/26 21:55:03------初始化完成!

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,24 @@
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\bin\Debug\ConsoleGetPLCData.exe.config
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\bin\Debug\ConsoleGetPLCData.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\bin\Debug\ConsoleGetPLCData.pdb
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\bin\Debug\GetData_PLC.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\bin\Debug\GetData_PLC.pdb
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\bin\Debug\Unme.Common.dll
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.csprojResolveAssemblyReference.cache
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.pdb
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.csprojResolveAssemblyReference.cache
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.exe
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.pdb
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.csprojResolveAssemblyReference.cache
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.exe
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.pdb
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.exe
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.pdb
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.csprojResolveAssemblyReference.cache
D:\GetPLCData\ConsoleGetPLCData.exe.config
D:\GetPLCData\ConsoleGetPLCData.exe
D:\GetPLCData\ConsoleGetPLCData.pdb
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.csprojResolveAssemblyReference.cache
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.exe
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\ConsoleGetPLCData\obj\Debug\ConsoleGetPLCData.pdb

Binary file not shown.

Binary file not shown.

34
GetData_PLC.sln Normal file
View File

@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GetData_PLC", "GetData_PLC\GetData_PLC.csproj", "{3412CC68-9C7E-4F3E-A9DB-285EFD5F55DB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleGetPLCData", "ConsoleGetPLCData\ConsoleGetPLCData.csproj", "{A2378DFD-D382-44FB-B280-61224B8E0ACA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpdateMeter", "UpdateMeter\UpdateMeter.csproj", "{07D0B046-C0AD-49E9-BDA6-C6BB0252F26A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3412CC68-9C7E-4F3E-A9DB-285EFD5F55DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3412CC68-9C7E-4F3E-A9DB-285EFD5F55DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3412CC68-9C7E-4F3E-A9DB-285EFD5F55DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3412CC68-9C7E-4F3E-A9DB-285EFD5F55DB}.Release|Any CPU.Build.0 = Release|Any CPU
{A2378DFD-D382-44FB-B280-61224B8E0ACA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A2378DFD-D382-44FB-B280-61224B8E0ACA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A2378DFD-D382-44FB-B280-61224B8E0ACA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A2378DFD-D382-44FB-B280-61224B8E0ACA}.Release|Any CPU.Build.0 = Release|Any CPU
{07D0B046-C0AD-49E9-BDA6-C6BB0252F26A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07D0B046-C0AD-49E9-BDA6-C6BB0252F26A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07D0B046-C0AD-49E9-BDA6-C6BB0252F26A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07D0B046-C0AD-49E9-BDA6-C6BB0252F26A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

BIN
GetData_PLC.v11.suo Normal file

Binary file not shown.

BIN
GetData_PLC.v12.suo Normal file

Binary file not shown.

16
GetData_PLC/App.config Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<connectionStrings>
<add name="qConnectionString_Jlxt" connectionString="=trqgis;user id=jlxt;password=123456" providerName="System.Data.OleDb" />
<add name="qConnectionString_Dtjk" connectionString="data source=TRQCXC_10.75.167.5;user id=dtjk;password=dtjk_123" providerName="System.Data.OleDb" />
</connectionStrings>
<appSettings>
</appSettings>
</configuration>

218
GetData_PLC/DataToByte.cs Normal file
View File

@ -0,0 +1,218 @@
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Text;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
namespace GetData_PLC
{
class DataToByte
{
public DataToByte() { }
public static int TranNetDataByte()
{
try
{
return 1;
}
catch (Exception ex)
{
return 0;
}
}
/// <summary>
/// 将DataSet格式化成字节数组byte[]
/// </summary>
/// <param name="dsOriginal">DataSet对象</param>
/// <returns>字节数组</returns>
public static byte[] GetBinaryFormatData(DataSet dsOriginal)
{
byte[] binaryDataResult = null;
MemoryStream memStream = new MemoryStream();
IFormatter brFormatter = new BinaryFormatter();
dsOriginal.RemotingFormat = SerializationFormat.Binary;
brFormatter.Serialize(memStream, dsOriginal);
binaryDataResult = memStream.ToArray();
memStream.Close();
memStream.Dispose();
return binaryDataResult;
}
/// <summary>
/// 将DataSet格式化成字节数组byte[],并且已经经过压缩
/// </summary>
/// <param name="dsOriginal">DataSet对象</param>
/// <returns>字节数组</returns>
public static byte[] GetBinaryFormatDataCompress(DataSet dsOriginal)
{
byte[] binaryDataResult = null;
MemoryStream memStream = new MemoryStream();
IFormatter brFormatter = new BinaryFormatter();
dsOriginal.RemotingFormat = SerializationFormat.Binary;
brFormatter.Serialize(memStream, dsOriginal);
binaryDataResult = memStream.ToArray();
memStream.Close();
memStream.Dispose();
return Compress(binaryDataResult);
}
/// <summary>
/// 解压数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Decompress(byte[] data)
{
byte[] bData;
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
GZipStream stream = new GZipStream(ms, CompressionMode.Decompress, true);
byte[] buffer = new byte[1024];
MemoryStream temp = new MemoryStream();
int read = stream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
temp.Write(buffer, 0, read);
read = stream.Read(buffer, 0, buffer.Length);
}
//必须把stream流关闭才能返回ms流数据,不然数据会不完整
stream.Close();
stream.Dispose();
ms.Close();
ms.Dispose();
bData = temp.ToArray();
temp.Close();
temp.Dispose();
return bData;
}
/// <summary>
/// 压缩数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Compress(byte[] data)
{
byte[] bData;
MemoryStream ms = new MemoryStream();
GZipStream stream = new GZipStream(ms, CompressionMode.Compress, true);
stream.Write(data, 0, data.Length);
stream.Close();
stream.Dispose();
//必须把stream流关闭才能返回ms流数据,不然数据会不完整
//并且解压缩方法stream.Read(buffer, 0, buffer.Length)时会返回0
bData = ms.ToArray();
ms.Close();
ms.Dispose();
return bData;
}
/// <summary>
/// 将字节数组反序列化成DataSet对象
/// </summary>
/// <param name="binaryData">字节数组</param>
/// <returns>DataSet对象</returns>
public static DataSet RetrieveDataSet(byte[] binaryData)
{
DataSet ds = null;
MemoryStream memStream = new MemoryStream(binaryData,true);
//byte[] bs = memStream.GetBuffer();
// memStream.Write(bs, 0, bs.Length);
//memStream.Seek(0, SeekOrigin.Begin);
IFormatter brFormatter = new BinaryFormatter();
ds =(DataSet)brFormatter.Deserialize(memStream);
return ds;
}
/// <summary>
/// 将字节数组反解压后序列化成DataSet对象
/// </summary>
/// <param name="binaryData">字节数组</param>
/// <returns>DataSet对象</returns>
public static DataSet RetrieveDataSetDecompress(byte[] binaryData)
{
DataSet dsOriginal = null;
MemoryStream memStream = new MemoryStream(Decompress(binaryData));
IFormatter brFormatter = new BinaryFormatter();
Object obj = brFormatter.Deserialize(memStream);
dsOriginal = (DataSet)obj;
return dsOriginal;
}
/// <summary>
/// 将object格式化成字节数组byte[]
/// </summary>
/// <param name="dsOriginal">object对象</param>
/// <returns>字节数组</returns>
public static byte[] GetBinaryFormatData(object dsOriginal)
{
byte[] binaryDataResult = null;
MemoryStream memStream = new MemoryStream();
IFormatter brFormatter = new BinaryFormatter();
brFormatter.Serialize(memStream, dsOriginal);
binaryDataResult = memStream.ToArray();
memStream.Close();
memStream.Dispose();
return binaryDataResult;
}
/// <summary>
/// 将objec格式化成字节数组byte[],并压缩
/// </summary>
/// <param name="dsOriginal">object对象</param>
/// <returns>字节数组</returns>
public static byte[] GetBinaryFormatDataCompress(object dsOriginal)
{
byte[] binaryDataResult = null;
MemoryStream memStream = new MemoryStream();
IFormatter brFormatter = new BinaryFormatter();
brFormatter.Serialize(memStream, dsOriginal);
binaryDataResult = memStream.ToArray();
memStream.Close();
memStream.Dispose();
return Compress(binaryDataResult);
}
/// <summary>
/// 将字节数组反序列化成object对象
/// </summary>
/// <param name="binaryData">字节数组</param>
/// <returns>object对象</returns>
public static object RetrieveObject(byte[] binaryData)
{
MemoryStream memStream = new MemoryStream(binaryData);
IFormatter brFormatter = new BinaryFormatter();
Object obj = brFormatter.Deserialize(memStream);
return obj;
}
/// <summary>
/// 将字节数组解压后反序列化成object对象
/// </summary>
/// <param name="binaryData">字节数组</param>
/// <returns>object对象</returns>
public static object RetrieveObjectDecompress(byte[] binaryData)
{
MemoryStream memStream = new MemoryStream(Decompress(binaryData));
IFormatter brFormatter = new BinaryFormatter();
Object obj = brFormatter.Deserialize(memStream);
return obj;
}
}
}

View File

@ -0,0 +1,158 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{3412CC68-9C7E-4F3E-A9DB-285EFD5F55DB}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>GetData_PLC</RootNamespace>
<AssemblyName>GetData_PLC</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>D:\GetPLCData\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<AutorunEnabled>true</AutorunEnabled>
<ApplicationRevision>1</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>D:\GetPLCData\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>C9CCE7BB53638EA44ED6B3046F9EB5C26E69B6CF</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>GetData_PLC_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<SignManifests>false</SignManifests>
</PropertyGroup>
<PropertyGroup>
<StartupObject>GetData_PLC.Program</StartupObject>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>Mario.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DataToByte.cs" />
<Compile Include="frmMain.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="frmMain.Designer.cs">
<DependentUpon>frmMain.cs</DependentUpon>
</Compile>
<Compile Include="OracleLink.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="strFileCaoZuo.cs" />
<Compile Include="strSQL.cs" />
<EmbeddedResource Include="frmMain.resx">
<DependentUpon>frmMain.cs</DependentUpon>
<SubType>Designer</SubType>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="GetData_PLC_TemporaryKey.pfx" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.4.5">
<Visible>False</Visible>
<ProductName>Windows Installer 4.5</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Content Include="Mario.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishUrlHistory />
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
<BootstrapperUrlHistory />
<ErrorReportUrlHistory />
<FallbackCulture>zh-CN</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
</Project>

Binary file not shown.

BIN
GetData_PLC/Mario.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

164
GetData_PLC/OracleLink.cs Normal file
View File

@ -0,0 +1,164 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Text;
#pragma warning disable 0618
namespace GetData_PLC
{
public class OracleLink
{
private static string strCon_jlxt = "data source=orcl;user id=cxc;password=cxc";
private static string strCon_Dtjk = "data source=TRQSCADA;user id=dtjk;password=Dtjk_123";
public static void SaveDataTable(string sql, DataTable _TempTable, string strDataBaseName, string strErr)
{
// Create a new Oracle command
OracleCommand command = null;
string ConnectionStrings = "";
if (strDataBaseName == "JLXT") ConnectionStrings = strCon_jlxt;
if (strDataBaseName == "DTJK") ConnectionStrings = strCon_Dtjk;
try
{
//Create a connection
using (OracleConnection connection = new OracleConnection(ConnectionStrings))
{
command = new OracleCommand(sql, connection);
OracleDataAdapter adapter = new OracleDataAdapter(command);
OracleCommandBuilder cb = new OracleCommandBuilder(adapter);
adapter.Update(_TempTable);
strErr = "";
//return _TempTable;
}
}
catch (Exception ex)
{
strErr = " oracle保存表格错误" + ex.Message;
}
}
public static string getStationName(string strID)
{
DataTable dtStation = new DataTable();
dtStation = ExecuteDataTable("select * from SYS_ORGANISE where ORG_ID='" + strID + "'", "JLXT", "");
if (dtStation.Rows.Count > 0)
{
return dtStation.Rows[0]["ORG_NAME"].ToString();
}
else
{
return "";
}
}
public static string getStationName(string strID,ref string strDeptID)
{
DataTable dtStation = new DataTable();
dtStation = ExecuteDataTable("select * from SYS_ORGANISE where ORG_ID='" + strID + "'", "JLXT", "");
if (dtStation.Rows.Count > 0)
{
strDeptID = dtStation.Rows[0]["PARENT_ORG_ID"].ToString();
return dtStation.Rows[0]["ORG_NAME"].ToString();
}
else
{
return "";
}
}
public static string getDeptID(string strID)
{
DataTable dtStation = new DataTable();
dtStation = ExecuteDataTable("select * from SYS_ORGANISE where ORG_ID='" + strID + "'", "JLXT", "");
if (dtStation.Rows.Count > 0)
{
return dtStation.Rows[0]["PARENT_ORG_ID"].ToString();
}
else
{
return "";
}
}
public static DataTable ExecuteDataTable(string sql,string strDataBaseName,string strError)
{
// Create a new Oracle command
OracleCommand command = null;
string ConnectionStrings="";
if (strDataBaseName == "JLXT") ConnectionStrings = strCon_jlxt;
if (strDataBaseName == "DTJK") ConnectionStrings = strCon_Dtjk;
try
{
//Create a connection
using (OracleConnection connection = new OracleConnection(ConnectionStrings))
{
command = new OracleCommand(sql, connection);
OracleDataAdapter adapter = new OracleDataAdapter(command);
DataSet ds = new DataSet();
//System.Threading.Thread.Sleep(10)
adapter.Fill(ds);
//if(ds.Tables.Count<1)
// return;
DataTable dt = ds.Tables[0].Copy();
ds.Dispose();
strError = "";
return dt;
}
}
catch (Exception ex)
{
strError = " oracle查询表格出错" + ex.Message;
return null;
}
}
public static int ExecuteNonQuery(string sql, string strDataBaseName, string strError)
{
string ConnectionStrings = "";
if (strDataBaseName == "JLXT") ConnectionStrings = strCon_jlxt;
if (strDataBaseName == "DTJK") ConnectionStrings = strCon_Dtjk;
using (OracleConnection con = new OracleConnection(ConnectionStrings))
{
int Num;
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
Num = cmd.ExecuteNonQuery();
con.Close();
return Num;
}
}
public static void strAppend(string strFilePath, string strMessage)
{
using (StreamWriter sw = File.AppendText(strFilePath))
{
sw.WriteLine(strMessage);
sw.Flush();
sw.Close();
}
}
}
}

44
GetData_PLC/Program.cs Normal file
View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GetData_PLC
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//frmMain frmMainSingle = frmMain.getSingle();
//Application.Run(frmMainSingle);
bool createdNew; Mutex instance = new Mutex(true, "互斥名(保证在本机中唯一)", out createdNew);
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
instance.ReleaseMutex();
}
else
{
MessageBox.Show("已经启动了一个程序,请先退出!", "系统提示", MessageBoxButtons.OK,
MessageBoxIcon.Error);
Application.Exit();
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("GetData_PLC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("GetData_PLC")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("d0ed4364-25a9-4717-a315-632b20646a80")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.18444
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace GetData_PLC.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GetData_PLC.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 使用此强类型资源类,为所有资源查找
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.18444
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace GetData_PLC.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

Binary file not shown.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

Binary file not shown.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<assemblyIdentity name="GetData_PLC.application" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="msil" xmlns="urn:schemas-microsoft-com:asm.v1" />
<description asmv2:publisher="Microsoft" asmv2:product="GetData_PLC" xmlns="urn:schemas-microsoft-com:asm.v1" />
<deployment install="true" mapFileExtensions="true" />
<compatibleFrameworks xmlns="urn:schemas-microsoft-com:clickonce.v2">
<framework targetVersion="4.0" profile="Full" supportedRuntime="4.0.30319" />
</compatibleFrameworks>
<dependency>
<dependentAssembly dependencyType="install" codebase="GetData_PLC.exe.manifest" size="3405">
<assemblyIdentity name="GetData_PLC.exe" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="msil" type="win32" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>gsYXw7AaTnDdt4jSKteFW0iOfUI=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
</asmv1:assembly>

Binary file not shown.

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<connectionStrings>
<add name="qConnectionString_Jlxt" connectionString="data source=trqgis;user id=jlxt;password=123456" providerName="System.Data.OleDb" />
<add name="qConnectionString_Dtjk" connectionString="data source=TRQCXC_10.75.167.5;user id=dtjk;password=dtjk_123" providerName="System.Data.OleDb" />
</connectionStrings>
<appSettings>
</appSettings>
</configuration>

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<asmv1:assemblyIdentity name="GetData_PLC.exe" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="msil" type="win32" />
<application />
<entryPoint>
<assemblyIdentity name="GetData_PLC" version="1.0.0.0" language="neutral" processorArchitecture="msil" />
<commandLine file="GetData_PLC.exe" parameters="" />
</entryPoint>
<trustInfo>
<security>
<applicationRequestMinimum>
<PermissionSet Unrestricted="true" ID="Custom" SameSite="site" />
<defaultAssemblyRequest permissionSetReference="Custom" />
</applicationRequestMinimum>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!--
UAC 清单选项
如果要更改 Windows 用户帐户控制级别,请用以下节点之一替换
requestedExecutionLevel 节点。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
如果要利用文件和注册表虚拟化提供
向后兼容性,请删除 requestedExecutionLevel 节点。
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentOS>
<osVersionInfo>
<os majorVersion="5" minorVersion="1" buildNumber="2600" servicePackMajor="0" />
</osVersionInfo>
</dependentOS>
</dependency>
<dependency>
<dependentAssembly dependencyType="preRequisite" allowDelayedBinding="true">
<assemblyIdentity name="Microsoft.Windows.CommonLanguageRuntime" version="4.0.30319.0" />
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="GetData_PLC.exe" size="29184">
<assemblyIdentity name="GetData_PLC" version="1.0.0.0" language="neutral" processorArchitecture="msil" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>43jSD4jmjgww0RXnhxmLOXSBso0=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
<file name="GetData_PLC.exe.config" size="576">
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>mRxWD7Tvc0gMvp8wlC1jcMSFaVc=</dsig:DigestValue>
</hash>
</file>
</asmv1:assembly>

Binary file not shown.

340
GetData_PLC/frmMain.Designer.cs generated Normal file
View File

@ -0,0 +1,340 @@
namespace GetData_PLC
{
partial class frmMain
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.button4 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button3 = new System.Windows.Forms.Button();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.textBox1 = new System.Windows.Forms.TextBox();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel4 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel5 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel6 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel7 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel8 = new System.Windows.Forms.ToolStripStatusLabel();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.timer2 = new System.Windows.Forms.Timer(this.components);
this.timer3 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Top;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.button4);
this.splitContainer1.Panel1.Controls.Add(this.label1);
this.splitContainer1.Panel1.Controls.Add(this.textBox2);
this.splitContainer1.Panel1.Controls.Add(this.button3);
this.splitContainer1.Panel1.Controls.Add(this.checkBox1);
this.splitContainer1.Panel1.Controls.Add(this.button2);
this.splitContainer1.Panel1.Controls.Add(this.button1);
this.splitContainer1.Panel1.Controls.Add(this.comboBox1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer1.Size = new System.Drawing.Size(1250, 616);
this.splitContainer1.SplitterDistance = 49;
this.splitContainer1.TabIndex = 0;
//
// button4
//
this.button4.Location = new System.Drawing.Point(992, 18);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(66, 23);
this.button4.TabIndex = 5;
this.button4.Text = "浏览……";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(629, 23);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(137, 12);
this.label1.TabIndex = 4;
this.label1.Text = "Copy实时采集文件Data到";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(772, 20);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(214, 21);
this.textBox2.TabIndex = 3;
//
// button3
//
this.button3.Location = new System.Drawing.Point(532, 15);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 2;
this.button3.Text = "重启线程";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(250, 15);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(96, 16);
this.checkBox1.TabIndex = 2;
this.checkBox1.Text = "保存到数据库";
this.checkBox1.UseVisualStyleBackColor = true;
//
// button2
//
this.button2.Location = new System.Drawing.Point(123, 11);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(10, 11);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(405, 14);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 20);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// splitContainer2
//
this.splitContainer2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.dataGridView1);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.textBox1);
this.splitContainer2.Size = new System.Drawing.Size(1250, 563);
this.splitContainer2.SplitterDistance = 973;
this.splitContainer2.TabIndex = 1;
//
// dataGridView1
//
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.ColumnHeader;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 0);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowTemplate.Height = 23;
this.dataGridView1.Size = new System.Drawing.Size(969, 559);
this.dataGridView1.TabIndex = 0;
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(269, 559);
this.textBox1.TabIndex = 0;
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1,
this.toolStripStatusLabel2,
this.toolStripStatusLabel3,
this.toolStripStatusLabel4,
this.toolStripStatusLabel5,
this.toolStripStatusLabel6,
this.toolStripStatusLabel7,
this.toolStripStatusLabel8});
this.statusStrip1.Location = new System.Drawing.Point(0, 619);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1250, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel2
//
this.toolStripStatusLabel2.Name = "toolStripStatusLabel2";
this.toolStripStatusLabel2.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel3
//
this.toolStripStatusLabel3.Name = "toolStripStatusLabel3";
this.toolStripStatusLabel3.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel4
//
this.toolStripStatusLabel4.Name = "toolStripStatusLabel4";
this.toolStripStatusLabel4.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel5
//
this.toolStripStatusLabel5.Name = "toolStripStatusLabel5";
this.toolStripStatusLabel5.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel6
//
this.toolStripStatusLabel6.Name = "toolStripStatusLabel6";
this.toolStripStatusLabel6.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel7
//
this.toolStripStatusLabel7.Name = "toolStripStatusLabel7";
this.toolStripStatusLabel7.Size = new System.Drawing.Size(0, 17);
//
// toolStripStatusLabel8
//
this.toolStripStatusLabel8.Name = "toolStripStatusLabel8";
this.toolStripStatusLabel8.Size = new System.Drawing.Size(0, 17);
//
// timer1
//
this.timer1.Interval = 999;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// timer2
//
this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
//
// timer3
//
this.timer3.Enabled = true;
this.timer3.Interval = 1000;
this.timer3.Tick += new System.EventHandler(this.timer3_Tick);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1250, 641);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.splitContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "frmMain";
this.Text = "Form1";
this.Activated += new System.EventHandler(this.frmMain_Activated);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmMain_FormClosed);
this.Load += new System.EventHandler(this.frmMain_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
this.splitContainer2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel4;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel5;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel6;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel7;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel8;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Timer timer2;
private System.Windows.Forms.Timer timer3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button button4;
}
}

784
GetData_PLC/frmMain.cs Normal file
View File

@ -0,0 +1,784 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GetData_PLC
{
public partial class frmMain : Form
{
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
//[DllImport("Ws2_32.dll")]
private static string strErr = "";
public static string strAppPath = Environment.CurrentDirectory ; //采集程序路径
public static string strAPPDataPath = Environment.CurrentDirectory + @"\Data\"; //采集程序文件存储路径
public static string strParPath = strAPPDataPath + @"par\"; //计量参数文件存储路径
public static string strConfigPath = strAPPDataPath + @"Config\"; //采集程序参数保存路径
public static string strDataPath = strAPPDataPath + @"RealTime\"; //实时数据存储路径
public static string strDataPath_JlData = strDataPath + @"JlData\"; //分站计量实时数据存储路径
public static string strDataPath_ScData = strDataPath + @"ScData\"; //输差数据XML存储文件夹
public static string strDataPath_DataTime = strDataPath + @"DateTime\"; //分站时间xml存储文件夹
public static string strDataPath_Log = strDataPath + @"Log\"; //日志存储文件夹
//log 日志存放数据
public static string strLogPath = strDataPath + @"log\" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "_log.txt";
public static string strLogPath_Data = strDataPath + @"log\" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "_Datalog_";
private DataTable dtZhan = new DataTable();
static DataTable dtJld = new DataTable();
//检查控制台程序如果一分钟之内启动超过3次则可能有错误重启计算机。
private static int StartConselTimes;
//控制台是否运行的标志
private static bool ConselRunFlag;
// 程序启动的时间,用于主程序自动重启
private static DateTime MainPragramStartTime;
Boolean SaveHourFlag; //小时保存数据
Boolean SaveSSFlag; //实时数据保存数据
Boolean SaveDayFlag; //保存日报表标志
Boolean SaveSCDayFlag; //保存日报表标志
Boolean UpdateFlag; //更新计量器具的标志
private static int SaveDiff = 300;//实时数据存盘间隔 五分钟
bool SaveEnable;
private static DateTime PragramStartTime;// 程序启动的时间,用于主程序自动重启
private static DateTime LastSaveTime;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
//写入程序已经运行的标志 避免服务器程序重复启动
System.IO.Directory.CreateDirectory(strAPPDataPath); //Data文件夹
System.IO.Directory.CreateDirectory(strParPath); //Data\par文件夹
System.IO.Directory.CreateDirectory(strDataPath); //Data\realtime文件夹
System.IO.Directory.CreateDirectory(strConfigPath); //Data\realtime文件夹
System.IO.Directory.CreateDirectory(strDataPath_JlData); //分站xml存储文件夹
System.IO.Directory.CreateDirectory(strDataPath_ScData); //输差数据XML存储文件夹
System.IO.Directory.CreateDirectory(strDataPath_DataTime);//分站时间xml存储文件夹
System.IO.Directory.CreateDirectory(strDataPath_Log); //日志存储文件夹
// 备份数据库
DataSet dsBackUp = new DataSet();
DataTable dtBackUp = new DataTable();
dtBackUp = OracleLink.ExecuteDataTable("select * from RV2_BASEINFO", "JLXT", "");
dtBackUp.TableName = "FlowMeter";
dsBackUp.Tables.Add(dtBackUp.Copy());
dtBackUp = new DataTable();
dtBackUp = OracleLink.ExecuteDataTable("select * from RV2_TRANS_CONFIG", "JLXT", "");
dtBackUp.TableName = "SCConfig";
dsBackUp.Tables.Add(dtBackUp.Copy());
dtBackUp = new DataTable();
dtBackUp = OracleLink.ExecuteDataTable("select * from SYS_ORGANISE", "JLXT", "");
dtBackUp.TableName = "OrgConfig";
dsBackUp.Tables.Add(dtBackUp.Copy());
dsBackUp .WriteXml (strParPath + "dsConfig.xml", XmlWriteMode.WriteSchema);
string strParPath1 = strParPath + "runstate.txt";
if (File.Exists(strParPath))
{
if (File.ReadAllText(strParPath1) == "true")
{
MessageBox.Show("已有一个采集进程在运行,退出 ", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
else
{
File.WriteAllText(strParPath1, "true");
}
System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
toolStripStatusLabel1.Text = "天然气产销厂自动计量采集程序";
toolStripStatusLabel2.Text = DateTime.Now.ToString();
Control.CheckForIllegalCrossThreadCalls = false;//跨线程操作
string strFileName = "";
dtZhan = new DataTable();
try
{
dtZhan = OracleLink.ExecuteDataTable(SQL_Strings.strSQLZhan, "JLXT", strErr);
}
catch (Exception)
{
strFileName = strDataPath + "dtZhan.xml";
dtZhan.ReadXml(strFileName);
}
dtZhan.TableName = "集输站场";
DataTable dtStationNew = dtZhan.Copy();
try
{
for (int i = 0; i < dtZhan.Rows.Count; i++)
{
//柳屯配气站两台PLC 区分
string[] tempIp = dtZhan.Rows[i]["IP"].ToString().Split(',');
string[] tempPORT = dtZhan.Rows[i]["PORT"].ToString().Split(',');
if (tempIp.Length > 1)
{
DataRow drTemp = dtStationNew.NewRow();
drTemp.ItemArray = dtZhan.Rows[i].ItemArray;
dtStationNew.Rows[i]["org_id"] = dtZhan.Rows[i]["org_id"].ToString() + "_0";
dtStationNew.Rows[i]["org_name"] = dtZhan.Rows[i]["org_name"].ToString() + "_0";
dtStationNew.Rows[i]["IP"] = tempIp[0];
dtStationNew.Rows[i]["PORT"] = tempPORT[0];
for (int j = 1; j < tempIp.Length; j++)
{
drTemp["org_id"] = dtZhan.Rows[i]["org_id"].ToString() + "_" + j.ToString();
drTemp["org_name"] = dtZhan.Rows[i]["org_name"].ToString() + "_" + j.ToString();
drTemp["IP"] = tempIp[j];
drTemp["PORT"] = tempPORT[j];
dtStationNew.Rows.Add(drTemp);
}
}
}
comboBox1.DataSource = dtStationNew;
comboBox1.DisplayMember = dtZhan.Columns["ORG_NAME"].ToString();
comboBox1.ValueMember = dtZhan.Columns["ORG_ID"].ToString();
dtStationNew.WriteXml(strDataPath + "dtZhan.xml", XmlWriteMode.WriteSchema);
}
catch (Exception ex)
{
}
LastSaveTime = DateTime.Now;
PragramStartTime = DateTime.Now;
string name = Dns.GetHostName();
IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
for (int i = 0; i < ipadrlist.Length; i++)
{
if (ipadrlist[i].ToString() == "10.75.167.5" || ipadrlist[i].ToString() == "10.75.166.5")
{
checkBox1.Checked = true;
}
}
}
#region "启停采集控制台"
private void startConsel(string _filePath, string _ProcessesName)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == _ProcessesName)
{
try
{
p.Kill();
}
catch
{
}
}
}
//实例化一个进程类
//Thread.Sleep(5000);
Process cmd = new Process();
cmd.StartInfo.FileName = _filePath + "\\" + _ProcessesName + ".exe";
//不显示命令行窗口界面true不显示
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
cmd.Start(); //启动进程
textBox1.AppendText("采集程序启动---" + DateTime.Now + "\r\n");
ConselRunFlag = true;
StartConselTimes = 0;
}
private void CloseConsel(string _ProcessesName)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == _ProcessesName)
{
try
{
p.Kill();
}
catch
{
}
}
}
}
private void timer3_Tick(object sender, EventArgs e)
{
//定时重启 2天重启一次
TimeSpan stST = DateTime.Now - MainPragramStartTime;
DateTime SAVETIME = DateTime.Now;
DateTime oldTime = DateTime.Parse(toolStripStatusLabel2.Text);
TimeSpan strRuntime = SAVETIME - oldTime;
toolStripStatusLabel3.Text = "已运行【" + strRuntime.Days.ToString("0#") + "天" + strRuntime.Hours.ToString("0#") + "小时" + strRuntime.Minutes.ToString("0#") + "分钟" + strRuntime.Seconds.ToString("0#") + "秒 】";
toolStripStatusLabel4.Text = DateTime.Now.ToString();
#region //启动停止更新计量器具控制台程序
//try
//{
// if (SAVETIME.Hour >= 2 && SAVETIME.Hour < 3 && UpdateFlag == false) //过了2点启动
// {
// UpdateFlag = true;
// startConsel(strAppPath, "UpdateMeter");
// try
// {
// File.Delete(strAppPath + @"\Data\UpdateMeter\updateFlag.xml");
// }
// catch (Exception)
// {
// }
// }
// if (UpdateFlag) //如果更新成功 则关闭控制台程序
// {
// if (File.Exists(strAppPath + @"\Data\UpdateMeter\updateFlag.xml"))
// {
// CloseConsel("UpdateMeter");
// }
// }
// if (SAVETIME.Hour < 2 || SAVETIME.Hour > 3)
// {
// UpdateFlag = false;
// try
// {
// File.Delete(strAppPath + @"\Data\UpdateMeter\updateFlag.xml");
// }
// catch (Exception)
// {
// }
// }
//}
//catch (Exception ex)
//{
//}
#endregion
#region //客户端重启control
try
{
string strQuery = "select * from control"; //从数据库中查询出所有站场的名称和站场ID//返回不带重复记录的站场ID表格
string RestartFlag = "";
DataTable ReadFlagTable = OracleLink.ExecuteDataTable(strQuery, "DTJK", "");
RestartFlag = ReadFlagTable.Rows[0]["RESTART"].ToString();
if (RestartFlag == "1")
{
strQuery = "update control set RESTART=0 where id=1 "; //从数据库中查询出所有站场的名称和站场ID//返回不带重复记录的站场ID表格
OracleLink.ExecuteNonQuery(strQuery, "DTJK", strErr);
startConsel(strAppPath, "ConsoleGetPLCData");
}
}
catch (SystemException err)
{
}
#endregion
try
{
if (stST.Minutes > 2880)
{
System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
Application.Restart();
}
toolStripStatusLabel5.Text = "";
Int64 intPLCPageMemory = 0;
Int64 intPLCSystemMemory = 0;
ConselRunFlag = false;
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == "ConsoleGetPLCData")
{
string PLCMemory = "PLC采集程序【物理内存" + (p.WorkingSet64 / 1024 / 1024).ToString() + " MB--" + "分页内存:" + (p.PagedMemorySize64 / 1024 / 1024).ToString() + " MB】";
intPLCPageMemory = p.PagedMemorySize64 / 1024 / 1024;
intPLCSystemMemory = p.WorkingSet64 / 1024 / 1024;
toolStripStatusLabel5.Text = PLCMemory;
ConselRunFlag = true;
StartConselTimes = 0;
break;
}
}
if (ConselRunFlag == false)
{
StartConselTimes = StartConselTimes + 1;
startConsel(strAppPath, "ConsoleGetPLCData");
textBox1.AppendText("启动采集程序 " + "\r\n");
}
bool Restart = false;
if ((System.Math.IEEERemainder(SAVETIME.Minute, 5) > 0 && System.Math.IEEERemainder(SAVETIME.Minute, 5) < 4) || (DateTime.Now.Hour == 23 && DateTime.Now.Minute >= 56))
{
Restart = true;
}
if (intPLCPageMemory >= 250 && Restart)
{
CloseConsel("ConsoleGetPLCData");
Thread.Sleep(2000);
startConsel(strAppPath, "ConsoleGetPLCData");
toolStripStatusLabel7.Text = (int.Parse(toolStripStatusLabel7.Text) + 1).ToString();
textBox1.AppendText("分页内存超过250MB重启采集程序----" + DateTime.Now + "\r\n");
}
if (intPLCSystemMemory >= 150 && Restart)
{
CloseConsel("ConsoleGetPLCData");
Thread.Sleep(2000);
startConsel(strAppPath, "ConsoleGetPLCData");
toolStripStatusLabel7.Text = (int.Parse(toolStripStatusLabel7.Text) + 1).ToString();
textBox1.AppendText("物理内存超过150MB重启采集程序----" + DateTime.Now + "\r\n");
}
timer1.Enabled = true;
}
catch (Exception)
{
}
}
#endregion
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
string strFilePath = @"D:\GetPLCData\Data\RealTime\";
DataTable dtStation = new DataTable();
dtStation.ReadXml(strFilePath + "JlData\\" + comboBox1.SelectedValue.ToString() + ".xml");
dataGridView1.DataSource = dtStation;
DataSet SsDataDs = new DataSet();//数据集,用于存放全厂所有计量点实时数据
DataTable dtScRealTime = new DataTable();//数据集,用于存放全厂站场输差、管管线输差和自定义输差的实时显示
DataTable TotalTable = new DataTable();
try
{
dtScRealTime.ReadXml(strDataPath + "ScData.xml");
SsDataDs.ReadXml(strDataPath + "SsData.xml", XmlReadMode.ReadSchema);
TotalTable.ReadXml(strDataPath + "TotalData.xml");
}
catch (SystemException err)
{
if (err.Message != null)
{
//textBox1.AppendText("注意: 读取合并xml文件出错 " + err.Message + err.StackTrace.Substring(err.StackTrace.LastIndexOf("行号") - 1) + "\r\n");
//textBox1.AppendText("注意: 读取合并xml文件出错 " + "\r\n");
}
}
try
{
CopyDirectory(strAppPath + "\\Data\\", textBox2 .Text );
}
catch
{
}
#region
if (checkBox1.Checked)
{
DateTime SAVETIME = DateTime.Now;
string strQuery = "";
#region"保存实时数据"//------------------------------------------------------------------------
//if (System.Math.Abs(DateDiff.TotalSeconds - SaveDiff) < 1)
if (System.Math.IEEERemainder(SAVETIME.Minute, 5) == 0 && SaveSSFlag == false)
{
strQuery = "select ID,DEPT_ID,STATION_ID,JLD_ID,RTIME,WD,YL,CY,SSL,JRL,JRSJ,YBZT,SSGKLL,CXFLAG from REALTIME_DATA where ID=0";
DataTable SaveRealTimeData = OracleLink.ExecuteDataTable(strQuery, "DTJK", strErr);
for (int j = 0; j < TotalTable.Rows.Count; j++)
{
DataRow tempRow = SaveRealTimeData.NewRow();
tempRow["ID"] = TotalTable.Rows[j]["ID"];
tempRow["RTIME"] = SAVETIME;
tempRow["WD"] = TotalTable.Rows[j]["WD"];
tempRow["YL"] = TotalTable.Rows[j]["YL"];
tempRow["CY"] = TotalTable.Rows[j]["CY"];
tempRow["SSL"] = TotalTable.Rows[j]["SSL"];
tempRow["JRL"] = TotalTable.Rows[j]["JRL"];
tempRow["JRSJ"] = TotalTable.Rows[j]["JRSJ"];
tempRow["YBZT"] = TotalTable.Rows[j]["YBZT"];
tempRow["SSGKLL"] = TotalTable.Rows[j]["SSGKLL"];
tempRow["CXFLAG"] = TotalTable.Rows[j]["CXFLAG"];
tempRow["DEPT_ID"] = TotalTable.Rows[j]["DEPT_ID"];
tempRow["STATION_ID"] = TotalTable.Rows[j]["STATION_ID"];
tempRow["JLD_ID"] = TotalTable.Rows[j]["JLD_ID"];
SaveRealTimeData.Rows.Add(tempRow);
}
try
{
strQuery = "select ID,DEPT_ID,STATION_ID,JLD_ID,RTIME,WD,YL,CY,SSL,JRL,JRSJ,YBZT,SSGKLL,CXFLAG from REALTIME_DATA";
SaveRealTimeData.WriteXml ("d:\\ccc.xml",XmlWriteMode.WriteSchema);
OracleLink.SaveDataTable(strQuery, SaveRealTimeData, "DTJK", strErr);
strErr = "注意:" + DateTime.Now + "保存实时数据成功" + "\r\n";
textBox1.AppendText(strErr);
}
catch (SystemException err)
{
if (err.Message != null)
{
strErr = "注意:" + DateTime.Now + "保存实时数据库时出错" + err.Message + "\r\n";
textBox1.AppendText(strErr);
}
}
#endregion
#region"保存实时输差"//-----------------------------------------------------
strQuery = "select id, in_p,out_p,rtime, scname, ssintotal, ssouttotal, sssc, ssscbfs, jrlintotal, jrlouttotal, jrlsc, jrlscbfs, station_id, sctype, redept_name from SC_DATA where id=0 ";
try
{
DataTable ScTotalTable = new DataTable();
ScTotalTable = OracleLink.ExecuteDataTable(strQuery, "DTJK", strErr);
ScTotalTable.Rows.Clear();
for (int j = 0; j < dtScRealTime.Rows.Count; j++)
{
DataRow tempRow = ScTotalTable.NewRow();
tempRow["RTIME"] = SAVETIME;
tempRow["ID"] = dtScRealTime.Rows[j]["SCID"];
tempRow["IN_P"] = dtScRealTime.Rows[j]["IN_P"];
tempRow["OUT_P"] = dtScRealTime.Rows[j]["OUT_P"];
tempRow["scname"] = dtScRealTime.Rows[j]["SCNAME"];
tempRow["ssintotal"] = dtScRealTime.Rows[j]["SsInTotal"];
tempRow["ssouttotal"] = dtScRealTime.Rows[j]["SsOutTotal"];
tempRow["sssc"] = dtScRealTime.Rows[j]["SsSc"];
tempRow["ssscbfs"] = dtScRealTime.Rows[j]["SsPer"];
tempRow["jrlintotal"] = dtScRealTime.Rows[j]["JrInTotal"];
tempRow["jrlouttotal"] = dtScRealTime.Rows[j]["JrOutTotal"];
tempRow["jrlsc"] = dtScRealTime.Rows[j]["JrSc"];
tempRow["jrlscbfs"] = dtScRealTime.Rows[j]["JrPer"];
tempRow["station_id"] = dtScRealTime.Rows[j]["station_id"];
tempRow["redept_name"] = dtScRealTime.Rows[j]["RE_DEPT_ID"];
tempRow["sctype"] = dtScRealTime.Rows[j]["SCTYPE"];
ScTotalTable.Rows.Add(tempRow);
}
strQuery = "select id, rtime,in_p,out_p, scname, ssintotal, ssouttotal, sssc, ssscbfs, jrlintotal, jrlouttotal, jrlsc, jrlscbfs, station_id, sctype, redept_name from SC_DATA ";
OracleLink.SaveDataTable(strQuery, ScTotalTable, "DTJK", strErr);
strErr = "注意:" + DateTime.Now + "保存实时输差数据成功" + "\r\n";
textBox1.AppendText(strErr);
}
catch (SystemException err)
{
if (err.Message != null)
{
strErr = ("注意:" + DateTime.Now + "保存输差数据失败" + err.Message) + "\r\n";
textBox1.AppendText(strErr);
}
}
LastSaveTime = SAVETIME;
SaveSSFlag = true;
}
if (System.Math.IEEERemainder(SAVETIME.Minute, 5) != 0)
{
SaveSSFlag = false;
}
#endregion
#region "存小时数据"//-----------------------------------------------------------------
if (SAVETIME.Minute == 59 && SAVETIME.Second > 40 && SaveHourFlag == false) //到小时整点,如果还没有存储过则开始存储
{
strQuery = "select ID,RTIME,WD,YL,CY,SSL,JRL,JRSJ,YBZT,DEPT_ID,STATION_ID,JLD_ID from HOURREPORT where ID=0";
DataTable SaveHourTable = OracleLink.ExecuteDataTable(strQuery, "DTJK", strErr);
for (int j = 0; j < TotalTable.Rows.Count; j++)
{
DataRow tempRow = SaveHourTable.NewRow();
tempRow["ID"] = TotalTable.Rows[j]["ID"];
tempRow["RTIME"] = SAVETIME;
tempRow["WD"] = TotalTable.Rows[j]["WD"];
tempRow["YL"] = TotalTable.Rows[j]["YL"];
tempRow["CY"] = TotalTable.Rows[j]["CY"];
tempRow["SSL"] = TotalTable.Rows[j]["SSL"];
tempRow["JRL"] = TotalTable.Rows[j]["JRL"];
tempRow["JRSJ"] = TotalTable.Rows[j]["JRSJ"];
tempRow["YBZT"] = TotalTable.Rows[j]["YBZT"];
tempRow["DEPT_ID"] = TotalTable.Rows[j]["DEPT_ID"];
tempRow["STATION_ID"] = TotalTable.Rows[j]["STATION_ID"];
tempRow["JLD_ID"] = TotalTable.Rows[j]["JLD_ID"];
SaveHourTable.Rows.Add(tempRow);
}
strQuery = "select ID,RTIME,WD,YL,CY,SSL,JRL,JRSJ,YBZT,DEPT_ID,STATION_ID,JLD_ID from HOURREPORT";
try
{
OracleLink.SaveDataTable(strQuery, SaveHourTable, "DTJK", strErr);
strErr = "注意:" + DateTime.Now + "保存小时数据成功" + "\r\n";
textBox1.AppendText(strErr);
SaveHourFlag = true;
SaveHourTable.Dispose();
}
catch (SystemException err)
{
if (err.Message != null)
{
strErr = "注意:" + DateTime.Now + "保存小时数据出错" + "\r\n";
textBox1.AppendText(strErr);
}
}
}
if (SAVETIME.Minute != 59) //过了小时准点 存储标志设为否
{
SaveHourFlag = false;
}
#endregion
#region "输差每日23:59:55 存盘一次
if (SAVETIME.Hour == 23 && SAVETIME.Minute.ToString() == "59" && SAVETIME.Second.ToString() == "55" && SaveSCDayFlag == false) //过了零点十分则日报表
{
strQuery = "select id, in_p,out_p,rtime, scname, ssintotal, ssouttotal, sssc, ssscbfs, jrlintotal, jrlouttotal, jrlsc, jrlscbfs, station_id, sctype, redept_name from SC_DAYDATA where id=0 ";
DataTable ScTotalTableH = new DataTable();
ScTotalTableH = OracleLink.ExecuteDataTable(strQuery, "DTJK", strErr);
ScTotalTableH.Rows.Clear();
try
{
for (int j = 0; j < dtScRealTime.Rows.Count; j++)
{
DataRow tempRow = ScTotalTableH.NewRow();
tempRow["RTIME"] = SAVETIME;
tempRow["ID"] = dtScRealTime.Rows[j]["SCID"];
tempRow["IN_P"] = dtScRealTime.Rows[j]["IN_P"];
tempRow["OUT_P"] = dtScRealTime.Rows[j]["OUT_P"];
tempRow["scname"] = dtScRealTime.Rows[j]["SCNAME"];
tempRow["ssintotal"] = dtScRealTime.Rows[j]["SsInTotal"];
tempRow["ssouttotal"] = dtScRealTime.Rows[j]["SsOutTotal"];
tempRow["sssc"] = dtScRealTime.Rows[j]["SsSc"];
tempRow["ssscbfs"] = dtScRealTime.Rows[j]["SsPer"];
tempRow["jrlintotal"] = dtScRealTime.Rows[j]["JrInTotal"];
tempRow["jrlouttotal"] = dtScRealTime.Rows[j]["JrOutTotal"];
tempRow["jrlsc"] = dtScRealTime.Rows[j]["JrSc"];
tempRow["jrlscbfs"] = dtScRealTime.Rows[j]["JrPer"];
tempRow["station_id"] = dtScRealTime.Rows[j]["station_id"];
tempRow["redept_name"] = dtScRealTime.Rows[j]["RE_DEPT_ID"];
tempRow["sctype"] = dtScRealTime.Rows[j]["SCTYPE"];
ScTotalTableH.Rows.Add(tempRow);
}
strQuery = "select id, rtime,in_p,out_p, scname, ssintotal, ssouttotal, sssc, ssscbfs, jrlintotal, jrlouttotal, jrlsc, jrlscbfs, station_id, sctype, redept_name from SC_DAYDATA ";
OracleLink.SaveDataTable(strQuery, ScTotalTableH, "DTJK", strErr);
strErr = "注意:" + DateTime.Now + "保存实时输差数据成功" + "\r\n";
SaveSCDayFlag = true;
textBox1.AppendText(strErr);
}
catch (SystemException err)
{
if (err.Message != null)
{
strErr = ("注意:" + DateTime.Now + "保存输差数据失败" + err.Message) + "\r\n";
textBox1.AppendText(strErr);
}
}
}
if (SAVETIME.Hour != 23 && SAVETIME.Minute.ToString() != "59" && SAVETIME.Second.ToString() != "55") //过了小时准点 存储标志设为否
{
SaveSCDayFlag = false;
}
#endregion
#region "存日报表"//-----------------------------------------------------------
if (SAVETIME.Hour == 0 && SAVETIME.Minute.ToString() == "10" && SaveDayFlag == false) //过了零点十分则日报表
{
string Queryql = "select ID,RTIME,QL,DEPT_ID,STATION_ID,JLD_ID,JLSJ from DAYREPORT where ID=0";
DataTable SaveDAYTable = OracleLink.ExecuteDataTable(Queryql, "DTJK", strErr);
DateTime _Date = DateTime.Now.AddDays(-1);
_Date = DateTime.Parse(_Date.ToString("yyyy-MM-dd"));
for (int j = 0; j < TotalTable.Rows.Count; j++)
{
DataRow tempRow = SaveDAYTable.NewRow();
tempRow["ID"] = TotalTable.Rows[j]["ID"];
tempRow["RTIME"] = _Date;
tempRow["QL"] = TotalTable.Rows[j]["ZRL"];
tempRow["DEPT_ID"] = TotalTable.Rows[j]["DEPT_ID"];
tempRow["STATION_ID"] = TotalTable.Rows[j]["STATION_ID"];
tempRow["JLD_ID"] = TotalTable.Rows[j]["JLD_ID"];
tempRow["JLSJ"] = TotalTable.Rows[j]["ZRSJ"];
SaveDAYTable.Rows.Add(tempRow);
}
Queryql = "select ID,RTIME,QL,DEPT_ID,STATION_ID,JLD_ID,JLSJ from DAYREPORT";
try
{
OracleLink.SaveDataTable(Queryql, SaveDAYTable, "DTJK", strErr);
//SaveDAYTable.WriteXml(strDataPath + DateTime.Now.ToString() + "SaveTable.xml",XmlWriteMode.WriteSchema);
//File.Copy(strDataPath + "TotalData.xml", strDataPath + DateTime.Now.ToString() + "TotalData.xml");
strErr = "注意:" + DateTime.Now + "保存日报表成功" + "\r\n";
textBox1.AppendText(strErr);
SaveDayFlag = true;
SaveDAYTable.Dispose();
}
catch (SystemException err)
{
if (err.Message != null)
{
strErr = "注意:" + DateTime.Now + "保存日报表数据出错" + strErr + "\r\n";
textBox1.AppendText(strErr);
}
}
}
if (SAVETIME.Hour != 1 && SAVETIME.Minute.ToString() != "10") //过了小时准点 存储标志设为否
{
SaveDayFlag = false;
}
#endregion
}
#endregion
}
catch { }
}
private void frmMain_Activated(object sender, EventArgs e)
{
}
private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
{
CloseConsel("ConsoleGetPLCData");
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
CloseConsel("ConsoleGetPLCData");
File.WriteAllText(strParPath + "runstate.txt", "false");
System.Environment.Exit(0);//彻底关闭线程
}
private void timer2_Tick(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
string strQuery = "update control set ThreadRestartFlag='1',Thread_ZCID='" + comboBox1.SelectedValue.ToString() + "' where id=1 "; //从数据库中查询出所有站场的名称和站场ID//返回不带重复记录的站场ID表格
OracleLink.ExecuteNonQuery(strQuery, "DTJK", strErr);
}
private void button1_Click(object sender, EventArgs e)
{
string strQuery = "update control set ThreadRestartFlag='1',Thread_ZCID='" + comboBox1.SelectedValue.ToString() + "' where id=1 "; //从数据库中查询出所有站场的名称和站场ID//返回不带重复记录的站场ID表格
OracleLink.ExecuteNonQuery(strQuery, "DTJK", strErr);
}
private void button4_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.SelectedPath = @"D:\";
if (fbd.ShowDialog() == DialogResult.OK)
{
this.textBox2.Text = fbd.SelectedPath;
}
File.WriteAllText(strAppPath + "\\CopyPath.txt", textBox2.Text);
}
public void CopyDirectory(string sourceDirName, string destDirName)
{
try
{
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
File.SetAttributes(destDirName, File.GetAttributes(sourceDirName));
}
if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar)
destDirName = destDirName + Path.DirectorySeparatorChar;
string[] files = Directory.GetFiles(sourceDirName);
foreach (string file in files)
{
File.Copy(file, destDirName + Path.GetFileName(file), true);
File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);
//total++;
}
string[] dirs = Directory.GetDirectories(sourceDirName);
foreach (string dir in dirs)
{
CopyDirectory(dir, destDirName + Path.GetFileName(dir));
}
}
catch (Exception ex)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + "\\log.txt", true);
sw.Write(ex.Message + " " + DateTime.Now + "\r\n");
sw.Close();
}
}
}
}

1667
GetData_PLC/frmMain.resx Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<assemblyIdentity name="GetData_PLC.application" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="x86" xmlns="urn:schemas-microsoft-com:asm.v1" />
<description asmv2:publisher="GetData_PLC" asmv2:product="GetData_PLC" xmlns="urn:schemas-microsoft-com:asm.v1" />
<deployment install="true" mapFileExtensions="true" />
<compatibleFrameworks xmlns="urn:schemas-microsoft-com:clickonce.v2">
<framework targetVersion="4.0" profile="Full" supportedRuntime="4.0.30319" />
</compatibleFrameworks>
<dependency>
<dependentAssembly dependencyType="install" codebase="GetData_PLC.exe.manifest" size="3860">
<assemblyIdentity name="GetData_PLC.exe" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="x86" type="win32" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>/98GKWwhOmh5/MvPNrQLRo+qqVs=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
</asmv1:assembly>

View File

@ -0,0 +1,57 @@
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Debug\GetData_PLC.exe.config
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Debug\GetData_PLC.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Debug\GetData_PLC.pdb
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetDataPLC_exe\GetData_PLC.exe.config
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetDataPLC_exe\GetData_PLC.exe.manifest
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetDataPLC_exe\GetData_PLC.application
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetDataPLC_exe\GetData_PLC.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetDataPLC_exe\GetData_PLC.pdb
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.frmMain.resources
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.Properties.Resources.resources
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csproj.GenerateResource.Cache
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe.manifest
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.application
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.pdb
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csprojResolveAssemblyReference.cache
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.frmMain.resources
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.Properties.Resources.resources
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csproj.GenerateResource.Cache
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe.manifest
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.application
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe
E:\自动接收\计量管理科(F0BF97D8CA14)\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.pdb
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.frmMain.resources
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.Properties.Resources.resources
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csproj.GenerateResource.Cache
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe.manifest
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.application
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe
C:\Users\cloud\Documents\Visual Studio 2012\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.pdb
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.pdb
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.frmMain.resources
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.Properties.Resources.resources
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csproj.GenerateResource.Cache
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe.manifest
E:\ldy\Desktop\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.application
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.pdb
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csprojResolveAssemblyReference.cache
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.frmMain.resources
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.Properties.Resources.resources
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csproj.GenerateResource.Cache
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe.manifest
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC+三力超声波\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.application
D:\GetPLCData\GetData_PLC.exe.config
D:\GetPLCData\GetData_PLC.exe.manifest
D:\GetPLCData\GetData_PLC.application
D:\GetPLCData\GetData_PLC.exe
D:\GetPLCData\GetData_PLC.pdb
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.frmMain.resources
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.Properties.Resources.resources
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.csproj.GenerateResource.Cache
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe.manifest
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.application
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.exe
E:\ldy\Documents\Visual Studio 2013\Projects\GetData_PLC_NEW\GetData_PLC\GetData_PLC\obj\Debug\GetData_PLC.pdb

Binary file not shown.

View File

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<asmv1:assemblyIdentity name="GetData_PLC.exe" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="x86" type="win32" />
<description asmv2:iconFile="Mario.ico" xmlns="urn:schemas-microsoft-com:asm.v1" />
<application />
<entryPoint>
<assemblyIdentity name="GetData_PLC" version="1.0.0.0" language="neutral" processorArchitecture="x86" />
<commandLine file="GetData_PLC.exe" parameters="" />
</entryPoint>
<trustInfo>
<security>
<applicationRequestMinimum>
<PermissionSet Unrestricted="true" ID="Custom" SameSite="site" />
<defaultAssemblyRequest permissionSetReference="Custom" />
</applicationRequestMinimum>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!--
UAC 清单选项
如果要更改 Windows 用户帐户控制级别,请用以下节点之一替换
requestedExecutionLevel 节点。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
如果要利用文件和注册表虚拟化提供
向后兼容性,请删除 requestedExecutionLevel 节点。
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentOS>
<osVersionInfo>
<os majorVersion="5" minorVersion="1" buildNumber="2600" servicePackMajor="0" />
</osVersionInfo>
</dependentOS>
</dependency>
<dependency>
<dependentAssembly dependencyType="preRequisite" allowDelayedBinding="true">
<assemblyIdentity name="Microsoft.Windows.CommonLanguageRuntime" version="4.0.30319.0" />
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="GetData_PLC.exe" size="221696">
<assemblyIdentity name="GetData_PLC" version="1.0.0.0" language="neutral" processorArchitecture="x86" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>e9iL5hYMgAegTkQAkal1B3YrHE4=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
<file name="GetData_PLC.exe.config" size="565">
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>9qAuvVJinL/10w661sMdCpZV2TU=</dsig:DigestValue>
</hash>
</file>
<file name="Mario.ico" size="91782">
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>N55XevUJHGJDRLBdhAY/WZd6pH4=</dsig:DigestValue>
</hash>
</file>
</asmv1:assembly>

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<assemblyIdentity name="GetData_PLC.application" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="msil" xmlns="urn:schemas-microsoft-com:asm.v1" />
<description asmv2:publisher="Microsoft" asmv2:product="GetData_PLC" xmlns="urn:schemas-microsoft-com:asm.v1" />
<deployment install="true" mapFileExtensions="true" />
<compatibleFrameworks xmlns="urn:schemas-microsoft-com:clickonce.v2">
<framework targetVersion="4.0" profile="Full" supportedRuntime="4.0.30319" />
</compatibleFrameworks>
<dependency>
<dependentAssembly dependencyType="install" codebase="GetData_PLC.exe.manifest" size="3405">
<assemblyIdentity name="GetData_PLC.exe" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="msil" type="win32" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>gsYXw7AaTnDdt4jSKteFW0iOfUI=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
</asmv1:assembly>

View File

@ -0,0 +1,13 @@
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Release\GetData_PLC.exe.config
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Release\GetData_PLC.exe.manifest
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Release\GetData_PLC.application
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Release\GetData_PLC.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\bin\Release\GetData_PLC.pdb
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.csprojResolveAssemblyReference.cache
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.frmMain.resources
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.Properties.Resources.resources
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.csproj.GenerateResource.Cache
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.exe.manifest
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.application
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.exe
E:\我的文档\Documents\Visual Studio 2013\Projects\GetData_PLC\GetData_PLC\obj\Release\GetData_PLC.pdb

Binary file not shown.

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<asmv1:assemblyIdentity name="GetData_PLC.exe" version="1.0.0.1" publicKeyToken="0000000000000000" language="neutral" processorArchitecture="msil" type="win32" />
<application />
<entryPoint>
<assemblyIdentity name="GetData_PLC" version="1.0.0.0" language="neutral" processorArchitecture="msil" />
<commandLine file="GetData_PLC.exe" parameters="" />
</entryPoint>
<trustInfo>
<security>
<applicationRequestMinimum>
<PermissionSet Unrestricted="true" ID="Custom" SameSite="site" />
<defaultAssemblyRequest permissionSetReference="Custom" />
</applicationRequestMinimum>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!--
UAC 清单选项
如果要更改 Windows 用户帐户控制级别,请用以下节点之一替换
requestedExecutionLevel 节点。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
如果要利用文件和注册表虚拟化提供
向后兼容性,请删除 requestedExecutionLevel 节点。
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentOS>
<osVersionInfo>
<os majorVersion="5" minorVersion="1" buildNumber="2600" servicePackMajor="0" />
</osVersionInfo>
</dependentOS>
</dependency>
<dependency>
<dependentAssembly dependencyType="preRequisite" allowDelayedBinding="true">
<assemblyIdentity name="Microsoft.Windows.CommonLanguageRuntime" version="4.0.30319.0" />
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="GetData_PLC.exe" size="29184">
<assemblyIdentity name="GetData_PLC" version="1.0.0.0" language="neutral" processorArchitecture="msil" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>43jSD4jmjgww0RXnhxmLOXSBso0=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
<file name="GetData_PLC.exe.config" size="576">
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>mRxWD7Tvc0gMvp8wlC1jcMSFaVc=</dsig:DigestValue>
</hash>
</file>
</asmv1:assembly>

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace GetData_PLC
{
class strFileCaoZuo
{
public static void strAppend(string strFilePath, string strMessage)
{
using (StreamWriter sw = File.AppendText(strFilePath))
{
sw.WriteLine(strMessage);
sw.Flush();
sw.Close();
}
}
}
}

30
GetData_PLC/strSQL.cs Normal file
View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GetData_PLC
{
public class SQL_Strings
{
public static readonly string strSQLZhan = "select * from SYS_ORGANISE where STATE='启用' and PLC='1'";
//public static readonly string strSQLZhan = "select DWMC,DWID,ZCMC,ID,ISZDJL,IP,PORT,READTIMESPAN,NETTYPE,SBTYPE,xh,zcbh,TBTime from 集输站场 where iszdjl='1' order by DWID";
public static readonly string strSQLJld = "select * from RV2_BASEINFO where STATION_NAME= '";
//public static readonly string strSQLJld = "select GLDW,ZCHBZ,AZDD,计量点标识,ISPLC,JLD_ID,JLDNAME,MeterType,ZCID from 安装地点基础资料 where isplc='1'";
public static readonly string strSQLScConfig = "select * from RV2_TRANS_CONFIG";
//public static readonly string strSQLScConfig = "select ID,SCNAME,DEPT_ID,STATION_ID,SCTYPE,STATION_NAME,DEPT_NAME,IN_JLD_ID,OUT_JLD_ID,RE_DEPT_ID from 输差名称";
public static readonly string strSQLSC_Zhan_Distinct = "select DISTINCT STATION_ID from 输差名称 where SCTYPE=''";
public static readonly string strSQLSC_Xian_DIStinct = "select DISTINCT dept_id from 输差名称";
public static readonly string strReadParFlag = "select * from RV2_BASEINFO where plc='1'";
public static readonly string strSaveParFlag = "select ZCID,计量点标识,ISPLC,JLD_ID,JLDNAME,MeterType,readparflag,xh from 安装地点基础资料 where isplc='1'";
public static readonly string strSQL_Read_Today_YesterDay_Flow = "select * from PGFLOW_TOTAL";
}
}

6
UpdateMeter/App.config Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

View File

@ -0,0 +1,433 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OracleClient;
using System.Configuration;
namespace OraDataBase
{
public class OracleHelper
{
static string condb = "Data Source=TRQCXC;user=jlxt;password=123456;";
static string condbn = "Data Source=orcl;user=cwbase10_9999;password=123456;";
public static DataSet DataAdapter(string sqlCmd, string tabName)//返回数据集 适配器
{
OracleConnection con = new OracleConnection(condb);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = sqlCmd;
OracleDataAdapter oda = new OracleDataAdapter(sqlCmd, con);
DataSet ds = new DataSet();
oda.Fill(ds, tabName);
con.Close();
return ds;
}
public static DataSet DataAdapter100(string sqlCmd, string tabName)//返回数据集 适配器
{
OracleConnection con = new OracleConnection(condbn);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = sqlCmd;
OracleDataAdapter oda = new OracleDataAdapter(sqlCmd, con);
DataSet ds = new DataSet();
oda.Fill(ds, tabName);
con.Close();
return ds;
}
public enum SDACmd { select, delete, update, insert }
public static DataSet DataAdapter(string sqlCmd, SDACmd command, string tabName, params OracleParameter[] paraList)
{
OracleConnection con = new OracleConnection(condb);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = sqlCmd;
if (paraList != null)
{
cmd.CommandType = CommandType.Text;
foreach (OracleParameter para in paraList)
{ cmd.Parameters.Add(para); }
}
OracleDataAdapter oda = new OracleDataAdapter();
switch (command)
{
case SDACmd.select:
oda.SelectCommand = cmd;
break;
case SDACmd.insert:
oda.InsertCommand = cmd;
break;
case SDACmd.update:
oda.UpdateCommand = cmd;
break;
case SDACmd.delete:
oda.DeleteCommand = cmd;
break;
}
DataSet ds = new DataSet();
oda.Fill(ds, tabName);
con.Close();
return ds;
}
public static OracleDataReader ExecReader(string sqlcmd, params OracleParameter[] paraList)// 逐条读取 返加 dataReader; 在程序中使用时记得关闭 odr.Close(); odr.Dispose();
{
OracleConnection con = new OracleConnection(condb);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = sqlcmd;
if (paraList != null)
{
cmd.CommandType = CommandType.Text;
foreach (OracleParameter para in paraList)
{ cmd.Parameters.Add(para); }
}
con.Open();
OracleDataReader odr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return odr;
}
public static void ExecNonQuery(string sqlcmd, params OracleParameter[] paraList)
{
using (OracleConnection con = new OracleConnection(condb))
{
OracleCommand cmd = new OracleCommand();
cmd.CommandTimeout = 600;
cmd.Connection = con;
cmd.CommandText = sqlcmd;
if (paraList != null)
{
cmd.CommandType = CommandType.Text;
foreach (OracleParameter para in paraList)
{ cmd.Parameters.Add(para); }
}
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
public static void ExecNonQueryJu(string sqlcmd, params OracleParameter[] paraList)
{
using (OracleConnection con = new OracleConnection(condbn))
{
OracleCommand cmd = new OracleCommand();
cmd.CommandTimeout = 600;
cmd.Connection = con;
cmd.CommandText = sqlcmd;
if (paraList != null)
{
cmd.CommandType = CommandType.Text;
foreach (OracleParameter para in paraList)
{ cmd.Parameters.Add(para); }
}
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
public static int ExecNonQuery(string sqlcmd, bool ifis)//返回ID
{
using (OracleConnection con = new OracleConnection(condb))
{
int maxid;
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = sqlcmd;
con.Open();
maxid = Convert.ToInt32(cmd.ExecuteScalar().ToString());
con.Close();
return maxid;
}
}
public static int ExecuteNonQuery(string sql)
{
using (OracleConnection con = new OracleConnection(condb))
{
int Num;
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
Num = cmd.ExecuteNonQuery();
con.Close();
return Num;
}
}
public static int ExecuteNonQuery100(string sql)
{
using (OracleConnection con = new OracleConnection(condbn))
{
int Num;
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
Num = cmd.ExecuteNonQuery();
con.Close();
return Num;
}
}
/**/
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="sprocName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>os_Info执行信息</returns>
public static string RunProcedure(string sprocName, IDataParameter[] parameters)
{
using (OracleConnection con = new OracleConnection(condb))
{
string infostr;
con.Open();
OracleCommand cmd = new OracleCommand(sprocName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (IDataParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
cmd.Parameters.Add("os_Info", OracleType.VarChar, 30);
cmd.Parameters["os_Info"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
//infostr = Convert.ToInt32(cmd.ExecuteScalar().ToString());
infostr = cmd.Parameters["os_Info"].Value.ToString();
con.Close();
return infostr;
}
}
/**/
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="sprocName">存储过程名</param>
/// <param name="TableName">表名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>返回记录集</returns>
public static DataSet RunProcedureDataSet(string sprocName, IDataParameter[] parameters)
{
using (OracleConnection con = new OracleConnection(condb))
{
con.Open();
OracleCommand cmd = new OracleCommand(sprocName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (IDataParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
cmd.Parameters.Add("TZ_CURSOR", OracleType.Cursor);
cmd.Parameters["TZ_CURSOR"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("HZ_CURSOR", OracleType.Cursor);
cmd.Parameters["HZ_CURSOR"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("QJ_CURSOR", OracleType.Cursor);
cmd.Parameters["QJ_CURSOR"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("AL_CURSOR", OracleType.Cursor);
cmd.Parameters["AL_CURSOR"].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ds);
con.Close();
return ds;
}
}
public static DataSet RunProcedureDataSetfb(string sprocName, IDataParameter[] parameters)
{
using (OracleConnection con = new OracleConnection(condb))
{
con.Open();
OracleCommand cmd = new OracleCommand(sprocName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (IDataParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
cmd.Parameters.Add("TZ_CURSOR", OracleType.Cursor);
cmd.Parameters["TZ_CURSOR"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("HZ_CURSOR", OracleType.Cursor);
cmd.Parameters["HZ_CURSOR"].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ds);
con.Close();
return ds;
}
}
//Andy 20131008
public static DataSet RunProcedureDataSetRY(string sprocName, IDataParameter[] parameters)
{
using (OracleConnection con = new OracleConnection(condb))
{
con.Open();
OracleCommand cmd = new OracleCommand(sprocName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (IDataParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
cmd.Parameters.Add("RY_CURSOR_ALL", OracleType.Cursor);
cmd.Parameters["RY_CURSOR_ALL"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("RY_CURSOR_Dept", OracleType.Cursor);
cmd.Parameters["RY_CURSOR_Dept"].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ds);
con.Close();
return ds;
}
}
//Andy 20130724
public static DataSet RunProcedureDataSetColumnChart(string sprocName, IDataParameter[] parameters)
{
using (OracleConnection con = new OracleConnection(condb))
{
con.Open();
OracleCommand cmd = new OracleCommand(sprocName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (IDataParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
cmd.Parameters.Add("TZ_CURSOR", OracleType.Cursor);
cmd.Parameters["TZ_CURSOR"].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ds);
con.Close();
return ds;
}
}
public static string ExecuteProcedure(string sprocName, IDataParameter parameter)
{
string info;
using (OracleConnection con = new OracleConnection(condb))
{
con.Open();
OracleCommand cmd = new OracleCommand(sprocName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (parameter != null)
{
cmd.Parameters.Add(parameter);
}
cmd.Parameters.Add("Info", OracleType.VarChar, 30);
cmd.Parameters["Info"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
info = cmd.Parameters["Info"].Value.ToString();
con.Close();
return info;
}
}
public static int isExit(string sql)
{
using (OracleConnection con = new OracleConnection(condb))
{
int Num;
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
Num = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return Num;
}
}
//201309 add
public static DataTable ExecuteDataTable(string sql)
{
// Create a new Oracle command
OracleCommand command = null;
try
{
//Create a connection
using (OracleConnection connection = new OracleConnection(condb))
{
command = new OracleCommand(sql, connection);
OracleDataAdapter adapter = new OracleDataAdapter(command);
DataSet ds = new DataSet();
//System.Threading.Thread.Sleep(10);
adapter.Fill(ds);
//if(ds.Tables.Count<1)
// return;
DataTable dt = ds.Tables[0].Copy();
ds.Dispose();
return dt;
}
}
catch (Exception ex)
{
//strError = " oracle查询返回表格错误" + ex.Message;
return null;
}
}
public static void SaveDataTable(string sql, DataTable _TempTable)
{
// Create a new Oracle command
OracleCommand command = null;
try
{
//Create a connection
using (OracleConnection connection = new OracleConnection(condb))
{
command = new OracleCommand(sql, connection);
OracleDataAdapter adapter = new OracleDataAdapter(command);
OracleCommandBuilder cb = new OracleCommandBuilder(adapter);
adapter.Update(_TempTable);
}
}
catch (Exception ex)
{
//strError = " oracle保存表格错误" + ex.Message;
}
}
}
}

687
UpdateMeter/Program.cs Normal file
View File

@ -0,0 +1,687 @@
using OraDataBase;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace UpdateMeter
{
class UpdateMeter
{
bool T = true;
DataTable dt = new DataTable();
DataTable dtXML = new DataTable();
DataSet ds = new DataSet();
string path = Environment.CurrentDirectory + @"\Data\UpdateMeter\";
static void Main(string[] args)
{
Console.WriteLine("更新厂台帐到局系统台帐");
UpdateMeter objUpdate = new UpdateMeter();
if (File.Exists(objUpdate.path + "updateFlag.xml"))
{
File.Delete(objUpdate.path + "updateFlag.xml");
}
objUpdate.ToUpdate(objUpdate.TRQCXC(), objUpdate.TRQCXC_NoZY(), objUpdate.ZYYT(), objUpdate.GLDW(), objUpdate.EquipInfo(), objUpdate.ZQDDJ(), objUpdate.CLCS(), objUpdate.CLJZ(), objUpdate.JDDW());
while (objUpdate.T)
{
Thread.Sleep(1);
}
Console.Read();
}
private DataTable TRQCXC_NoZY()
{
string sql = "select * from clsbtz where 状态 !='在用'";
//string sql = "select * from clsbtz where 状态 ='在用' and 使用存放地点 is not null and 制造厂家 is not null and 测量设备名称 not in('InTouch组态软件','WebAccess组态软件','工业热电阻检定软件','孔板综合测量仪软件','硫氮测定仪嵌入式软件','三K值计算程序','天然气流量计算管理系统','PCM金属探测仪,'孔板综合测量仪');
return dt = OraDataBase.OracleHelper.DataAdapter(sql, "DT").Tables[0];
}
private void ToUpdate(DataTable CXC_List, DataTable CXC_ListNoZY, DataTable ZYYT_List, DataTable GLDW_View, DataTable EquipInfo_View, DataTable ZQDDJ, DataTable CLCS, DataTable CLJZ, DataTable JDDW)
{
//增加检定单位标识、使用状态列
CXC_List.Columns.Add("检定单位标识", typeof(string));
CXC_List.Columns.Add("使用状态", typeof(string));
CXC_List.Columns.Add("启用日期1", typeof(string));
CXC_List.Columns.Add("检定日期1", typeof(string));
CXC_List.Columns.Add("有效日期1", typeof(string));
CXC_List.Columns.Add("确认日期1", typeof(string));
CXC_List.Columns.Add("填报日期1", typeof(string));
DataTable ErrorRecord = CXC_List.Clone();
DataTable SuccessRecord = CXC_List.Clone();
Console.WriteLine("开始更新!");
int jj = 0;
int mm = 0;
int nn = 0;
int mmm = 1;
for (int nnn = 0; nnn < CXC_ListNoZY.Rows.Count; nnn++)
{
DataRow[] DelDatarow = ZYYT_List.Select("f_ejdw='EJ0010' and f_ccbh='" + CXC_ListNoZY.Rows[nnn]["出厂编号"] + "'");
if (DelDatarow.Length > 0)
{
string sqlstr = "delete from JL_QJ_JLQJ where f_ccbh='" + CXC_ListNoZY.Rows[nnn]["出厂编号"] + "' and f_ejdw='EJ0010'";
OraDataBase.OracleHelper.ExecNonQueryJu(sqlstr);
Console.WriteLine("删除!" + mmm.ToString ()+ "条记录!");
mmm++;
}
}
for (int i = 0; i < CXC_List.Rows.Count; i++)
{
DataRow[] dr;
bool ErrorFlag = false;
DataRow[] exitsDatarow = ZYYT_List.Select("f_ejdw='EJ0010' and f_ccbh='" + CXC_List.Rows[i]["出厂编号"] + "'");
//更新管理信息
CXC_List.Rows[i]["二级单位"] = "EJ0010";
try
{
dr = GLDW_View.Select("f_ejdwbh = 'EJ0010' and f_sjdwmc='" + CXC_List.Rows[i]["管理单位"] + "'");
CXC_List.Rows[i]["管理单位"] = dr[0]["f_sjdwbh"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = GLDW_View.Select("f_ejdwbh = 'EJ0010' and f_sjdwbh='" + CXC_List.Rows[i]["管理单位"] + "' and F_JCZDMC='" + CXC_List.Rows[i]["集输站场"] + "'");
CXC_List.Rows[i]["集输站场"] = dr[0]["F_JCZDBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = GLDW_View.Select("f_ejdwbh = 'EJ0010' and f_sjdwbh='" + CXC_List.Rows[i]["管理单位"] + "' and F_JCZDBH='" + CXC_List.Rows[i]["集输站场"] + "' and F_CFDDMC='" + CXC_List.Rows[i]["使用存放地点"] + "'");
CXC_List.Rows[i]["使用存放地点"] = dr[0]["F_CFDDBH"];
}
catch (Exception) { ErrorFlag = true; }
//更新器具信息
try
{
dr = EquipInfo_View.Select("F_LBMC='" + CXC_List.Rows[i]["设备类别"] + "'");
CXC_List.Rows[i]["设备类别"] = dr[0]["F_LBBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = EquipInfo_View.Select("F_LBBH='" + CXC_List.Rows[i]["设备类别"] + "' and F_QJMC='" + CXC_List.Rows[i]["测量设备名称"] + "'");
CXC_List.Rows[i]["测量设备名称"] = dr[0]["F_QJMCBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = EquipInfo_View.Select("F_LBBH='" + CXC_List.Rows[i]["设备类别"] + "' and F_QJMCBH='" + CXC_List.Rows[i]["测量设备名称"] + "' and F_CJMC='" + CXC_List.Rows[i]["制造厂家"] + "'");
CXC_List.Rows[i]["制造厂家"] = dr[0]["F_CJBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = EquipInfo_View.Select("F_LBBH='" + CXC_List.Rows[i]["设备类别"] + "' and F_QJMCBH='" + CXC_List.Rows[i]["测量设备名称"] + "' and F_CJBH='" + CXC_List.Rows[i]["制造厂家"] + "' and F_GGXHMC='" + CXC_List.Rows[i]["规格型号"] + "'");
CXC_List.Rows[i]["规格型号"] = dr[0]["F_GGBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = EquipInfo_View.Select("F_LBBH='" + CXC_List.Rows[i]["设备类别"] + "' and F_QJMCBH='" + CXC_List.Rows[i]["测量设备名称"] + "' and F_CJBH='" + CXC_List.Rows[i]["制造厂家"] + "' and F_GGBH='" + CXC_List.Rows[i]["规格型号"] + "' and F_FW='" + CXC_List.Rows[i]["测量范围"] + "'");
CXC_List.Rows[i]["测量范围"] = dr[0]["F_QJXXBH"];
}
catch (Exception) { ErrorFlag = true; }
//准确度、测量参数、测量介质、检定单位
try
{
dr = ZQDDJ.Select("F_QJMC='" + CXC_List.Rows[i]["测量设备名称"] + "'");
CXC_List.Rows[i]["准确度等级"] = dr[0]["F_ZQDDJBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = CLCS.Select("F_QJMC='" + CXC_List.Rows[i]["测量设备名称"] + "' and f_clcs='" + CXC_List.Rows[i]["测量参数"] + "'");
CXC_List.Rows[i]["测量参数"] = dr[0]["F_CLCSBH"];
}
catch (Exception) { ErrorFlag = true; }
try
{
dr = CLJZ.Select("F_QJMC='" + CXC_List.Rows[i]["测量设备名称"] + "' and f_cljzmc='" + CXC_List.Rows[i]["测量介质"] + "'");
CXC_List.Rows[i]["测量介质"] = dr[0]["F_CLJZBH"];
}
catch (Exception) { ErrorFlag = true; }
//检定信息
try
{
dr = JDDW.Select("F_JDDWMC='" + CXC_List.Rows[i]["检定单位"] + "'");
CXC_List.Rows[i]["检定单位"] = dr[0]["F_JDDWBH"];
CXC_List.Rows[i]["检定单位标识"] = dr[0]["F_SYZT"];//1:自检;2:内检;3:外检;
}
catch (Exception) { ErrorFlag = true; }
//日期格式
try
{
if (CXC_List.Rows[i]["启用日期"].ToString() != "") CXC_List.Rows[i]["启用日期1"] = Convert.ToDateTime(CXC_List.Rows[i]["启用日期"]).ToString("yyyyMMdd");
if (CXC_List.Rows[i]["确认日期"].ToString() != "") CXC_List.Rows[i]["确认日期1"] = Convert.ToDateTime(CXC_List.Rows[i]["确认日期"]).ToString("yyyyMMdd");
if (CXC_List.Rows[i]["填报日期"].ToString() != "") CXC_List.Rows[i]["填报日期1"] = Convert.ToDateTime(System.DateTime.Now).ToString("yyyyMMdd");
if (CXC_List.Rows[i]["检定日期"].ToString() != "")
{
CXC_List.Rows[i]["检定日期1"] = Convert.ToDateTime(CXC_List.Rows[i]["检定日期"]).ToString("yyyyMMdd");
}
if (CXC_List.Rows[i]["有效日期"].ToString() != "")
{
if (Convert.ToDateTime(CXC_List.Rows[i]["有效日期"]) < System.DateTime.Now)//防止检定日期过期
{
CXC_List.Rows[i]["检定日期1"] = Convert.ToDateTime(CXC_List.Rows[i]["检定日期"]).AddDays(150).ToString("yyyyMMdd");
CXC_List.Rows[i]["有效日期1"] = Convert.ToDateTime(CXC_List.Rows[i]["有效日期"]).AddDays(150).ToString("yyyyMMdd");
}
else
{
CXC_List.Rows[i]["有效日期1"] = Convert.ToDateTime(CXC_List.Rows[i]["有效日期"]).ToString("yyyyMMdd");
}
}
}
catch (Exception) { ErrorFlag = true; }
//其他信息
try
{
if (CXC_List.Rows[i]["调休情况"].ToString() == "否")
{
CXC_List.Rows[i]["调休情况"] = "0";
}
else if (CXC_List.Rows[i]["调休情况"].ToString() == "是")
{
CXC_List.Rows[i]["调休情况"] = "1";
}
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["检定类别"].ToString() == "强检")
{
CXC_List.Rows[i]["检定类别"] = "1";
}
else if (CXC_List.Rows[i]["检定类别"].ToString() == "非强检")
{
CXC_List.Rows[i]["检定类别"] = "2";
}
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["管理类别"].ToString() == "A")
{
CXC_List.Rows[i]["管理类别"] = "1";
}
else if (CXC_List.Rows[i]["管理类别"].ToString() == "B")
{
CXC_List.Rows[i]["管理类别"] = "2";
}
else if (CXC_List.Rows[i]["管理类别"].ToString() == "C")
{
CXC_List.Rows[i]["管理类别"] = "3";
}
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["检定结果"].ToString() == "合格")
{
CXC_List.Rows[i]["检定结果"] = "0";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "不合格")
{
CXC_List.Rows[i]["检定结果"] = "1";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "校准")
{
CXC_List.Rows[i]["检定结果"] = "2";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "测试")
{
CXC_List.Rows[i]["检定结果"] = "3";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "自校")
{
CXC_List.Rows[i]["检定结果"] = "4";
}
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["具体耗能"].ToString() == "用能单元")
{
CXC_List.Rows[i]["具体耗能"] = "1";
}
else if (CXC_List.Rows[i]["具体耗能"].ToString() == "用能设备")
{
CXC_List.Rows[i]["具体耗能"] = "2";
}
else if (CXC_List.Rows[i]["具体耗能"].ToString() == "次级用能单位")
{
CXC_List.Rows[i]["具体耗能"] = "3";
}
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["标准器"].ToString() == "是")
{
CXC_List.Rows[i]["标准器"] = "1";
}
else if (CXC_List.Rows[i]["安全防护"].ToString() == "是")
{
CXC_List.Rows[i]["安全防护"] = "1";
}
else if (CXC_List.Rows[i]["环境监测"].ToString() == "是")
{
CXC_List.Rows[i]["环境监测 "] = "1";
}
else if (CXC_List.Rows[i]["贸易结算"].ToString() == "是")
{
CXC_List.Rows[i]["贸易结算"] = "1";
}
else if (CXC_List.Rows[i]["质量检测"].ToString() == "是")
{
CXC_List.Rows[i]["质量检测"] = "1";
}
else if (CXC_List.Rows[i]["耗能计量"].ToString() == "是")
{
CXC_List.Rows[i]["耗能计量"] = "1";
}
else if (CXC_List.Rows[i]["产能计量"].ToString() == "是")
{
CXC_List.Rows[i]["产能计量"] = "1";
}
else if (CXC_List.Rows[i]["医疗卫生"].ToString() == "是")
{
CXC_List.Rows[i]["医疗卫生"] = "1";
}
else if (CXC_List.Rows[i]["工艺控制"].ToString() == "是")
{
CXC_List.Rows[i]["工艺控制"] = "1";
}
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["状态"].ToString() == "在用")
{
CXC_List.Rows[i]["状态"] = "1";
}
else if (CXC_List.Rows[i]["状态"].ToString() == "停用")
{
CXC_List.Rows[i]["状态"] = "2";
}
else if (CXC_List.Rows[i]["状态"].ToString() == "待检")
{
CXC_List.Rows[i]["状态"] = "3";
}
else if (CXC_List.Rows[i]["状态"].ToString() == "备用")
{
CXC_List.Rows[i]["状态"] = "4";
}
else if (CXC_List.Rows[i]["状态"].ToString() == "报废")
{
CXC_List.Rows[i]["状态"] = "5";
}
CXC_List.Rows[i]["使用状态"] = "0";
}
catch (Exception) { ErrorFlag = true; }
try
{
if (CXC_List.Rows[i]["检定结果"].ToString() == "合格")
{
CXC_List.Rows[i]["检定结果"] = "0";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "不合格")
{
CXC_List.Rows[i]["检定结果"] = "1";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "校准")
{
CXC_List.Rows[i]["检定结果"] = "2";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "测试")
{
CXC_List.Rows[i]["检定结果"] = "3";
}
else if (CXC_List.Rows[i]["检定结果"].ToString() == "自校")
{
CXC_List.Rows[i]["检定结果"] = "4";
}
}
catch (Exception) { ErrorFlag = true; }
//记录出错信息
if (ErrorFlag)
{
DataRow tempDataRow = ErrorRecord.NewRow();
tempDataRow.ItemArray = CXC_List.Rows[i].ItemArray;
ErrorRecord.Rows.Add(tempDataRow);
jj = jj + 1;
}
//else
//{
DataRow tempDataRowSucess = SuccessRecord.NewRow();
tempDataRowSucess.ItemArray = CXC_List.Rows[i].ItemArray;
string sql = "";
if (exitsDatarow.Length == 0)
{
//插入语句(要生成编号)
//sql = "select max(to_number(f_djbh)) as f_djbh from JL_QJ_JLQJ";
sql = "select max(to_number(f_djbh)) as f_djbh from JL_QJ_JLQJ";
dt = OraDataBase.OracleHelper.DataAdapter100(sql, "DT").Tables[0];
int num = Convert.ToInt32(dt.Rows[0]["f_djbh"]) + 1;
string f_guid = Guid.NewGuid().ToString();
sql = "INSERT INTO JL_QJ_JLQJ( F_GUID,F_DJBH,F_DJLX,F_KJQJ,F_CODE,F_DJZT,F_DATE,F_ZDR,F_NOTE,F_CHDATE,F_CRDATE";
sql += ",F_EJDW,F_SJDW,F_LB,F_ZQDDJYQ,F_JLQJMC,F_GGXH,F_CLFW,F_ZQDDJ,F_CCBH,F_CLJZ,F_JDZQ,F_YXRQ,F_JDDW,F_TXQK";
sql += ",F_ZSBH,F_ZT,F_BFRQ,F_BFYY,F_BZQ,F_AQFH,F_HJJC,F_MYJS,F_GCKZ,F_ZLJC,F_HNJL,F_CNJL,F_JDLB,F_GLLB,F_JDFY,F_TBRQ";
sql += ",F_SYZT,F_SCCJ,F_YLWS,F_JDRQ,F_JCZD,F_AZD,F_CSMC,F_BHFW,F_JLD,F_QYRQ,F_JDJG,F_HNJLXQ,F_ZBH,F_QRRQ,F_SYXZ,F_SJ) VALUES ";
sql += "('" + f_guid + "','" + num.ToString() + "','201406','1','1','','','','','','','EJ0010','" + CXC_List.Rows[i]["管理单位"] + "','" + CXC_List.Rows[i]["设备类别"] + "'";
sql += ",'" + CXC_List.Rows[i]["应配准确等要求"] + "','" + CXC_List.Rows[i]["测量设备名称"] + "','" + CXC_List.Rows[i]["规格型号"] + "','" + CXC_List.Rows[i]["测量范围"] + "'";
sql += ",'" + CXC_List.Rows[i]["准确度等级"] + "','" + CXC_List.Rows[i]["出厂编号"] + "','" + CXC_List.Rows[i]["测量介质"] + "','" + CXC_List.Rows[i]["检定周期"] + "','" + CXC_List.Rows[i]["有效日期1"] + "'";
sql += ",'" + CXC_List.Rows[i]["检定单位"] + "','" + CXC_List.Rows[i]["调休情况"] + "','" + CXC_List.Rows[i]["证书编号"] + "','" + CXC_List.Rows[i]["状态"] + "','',''";
sql += ",'" + CXC_List.Rows[i]["标准器"] + "','" + CXC_List.Rows[i]["安全防护"] + "','" + CXC_List.Rows[i]["环境监测"] + "','" + CXC_List.Rows[i]["贸易结算"] + "','" + CXC_List.Rows[i]["工艺控制"] + "'";
sql += ",'" + CXC_List.Rows[i]["质量检测"] + "','" + CXC_List.Rows[i]["耗能计量"] + "','" + CXC_List.Rows[i]["产能计量"] + "','" + CXC_List.Rows[i]["检定类别"] + "','" + CXC_List.Rows[i]["管理类别"] + "'";
sql += ",'" + CXC_List.Rows[i]["检定费用"] + "','20140530','0','" + CXC_List.Rows[i]["制造厂家"] + "','','" + CXC_List.Rows[i]["检定日期1"] + "'";
sql += ",'" + CXC_List.Rows[i]["集输站场"] + "','" + CXC_List.Rows[i]["使用存放地点"] + "','" + CXC_List.Rows[i]["测量参数"] + "','" + CXC_List.Rows[i]["变化范围"] + "','','" + CXC_List.Rows[i]["启用日期1"] + "'";
sql += ",'" + CXC_List.Rows[i]["检定结果"] + "','" + CXC_List.Rows[i]["具体耗能"] + "','','" + CXC_List.Rows[i]["确认日期1"] + "','','0')";
mm = mm + 1;
OracleHelper.ExecuteNonQuery100(sql);
SuccessRecord.Rows.Add(tempDataRowSucess);
Console.WriteLine("插入" + (mm).ToString() + "条记录");
}
else
{
DataRow tempDR = CXC_List.Rows[i];
if (IsEqual(tempDR, ZYYT_List, CXC_List.Rows[i]["出厂编号"].ToString()))
{
//更新语句
sql += "UPDATE JL_QJ_JLQJ SET F_SJDW='" + CXC_List.Rows[i]["管理单位"] + "',F_LB='" + CXC_List.Rows[i]["设备类别"] + "',F_ZQDDJYQ='" + CXC_List.Rows[i]["应配准确等要求"] + "'";
sql += ",F_JLQJMC='" + CXC_List.Rows[i]["测量设备名称"] + "',F_GGXH='" + CXC_List.Rows[i]["规格型号"] + "',F_CLFW='" + CXC_List.Rows[i]["测量范围"] + "',F_ZQDDJ='" + CXC_List.Rows[i]["准确度等级"] + "'";
sql += ",F_CLJZ='" + CXC_List.Rows[i]["测量介质"] + "',F_JDZQ='" + CXC_List.Rows[i]["检定周期"] + "',F_YXRQ='" + CXC_List.Rows[i]["有效日期1"] + "',F_JDDW='" + CXC_List.Rows[i]["检定单位"] + "'";
sql += ",F_TXQK='" + CXC_List.Rows[i]["调休情况"] + "',F_ZSBH='" + CXC_List.Rows[i]["证书编号"] + "',F_ZT='" + CXC_List.Rows[i]["状态"] + "',F_BZQ='" + CXC_List.Rows[i]["标准器"] + "'";
sql += ",F_AQFH='" + CXC_List.Rows[i]["安全防护"] + "',F_HJJC='" + CXC_List.Rows[i]["环境监测"] + "',F_MYJS='" + CXC_List.Rows[i]["贸易结算"] + "',F_GCKZ='" + CXC_List.Rows[i]["工艺控制"] + "'";
sql += ",F_ZLJC='" + CXC_List.Rows[i]["质量检测"] + "',F_HNJL='" + CXC_List.Rows[i]["耗能计量"] + "',F_CNJL='" + CXC_List.Rows[i]["产能计量"] + "',F_JDLB='" + CXC_List.Rows[i]["检定类别"] + "'";
sql += ",F_GLLB='" + CXC_List.Rows[i]["管理类别"] + "',F_JDFY='" + CXC_List.Rows[i]["检定费用"] + "',F_SCCJ='" + CXC_List.Rows[i]["制造厂家"] + "',F_JDRQ='" + CXC_List.Rows[i]["检定日期1"] + "'";
sql += ",F_JCZD='" + CXC_List.Rows[i]["集输站场"] + "',F_AZD='" + CXC_List.Rows[i]["使用存放地点"] + "',F_CSMC='" + CXC_List.Rows[i]["测量参数"] + "',F_BHFW='" + CXC_List.Rows[i]["变化范围"] + "'";
sql += ",F_QYRQ='" + CXC_List.Rows[i]["启用日期1"] + "',F_JDJG='" + CXC_List.Rows[i]["检定结果"] + "',F_HNJLXQ='" + CXC_List.Rows[i]["具体耗能"] + "',F_QRRQ='" + CXC_List.Rows[i]["确认日期1"] + "'";
sql += " WHERE F_CCBH='" + CXC_List.Rows[i]["出厂编号"] + "' and F_EJDW='EJ0010'";
OracleHelper.ExecuteNonQuery100(sql);
nn = nn + 1;
Console.WriteLine("更新" + (nn).ToString() + "条记录");
SuccessRecord.Rows.Add(tempDataRowSucess);
}
}
//}
Thread.Sleep(10);
}
//写入xml
ErrorRecord.Columns.Remove("序号");
ErrorRecord.Columns.Remove("管理编号");
ErrorRecord.Columns.Remove("保管员");
ErrorRecord.Columns.Remove("资产归属");
ErrorRecord.Columns.Remove("测量过程类别");
ErrorRecord.Columns.Remove("出厂日期");
ErrorRecord.Columns.Remove("计量单位");
ErrorRecord.Columns.Remove("分度值");
ErrorRecord.Columns.Remove("仪表长度");
ErrorRecord.Columns.Remove("检定状态");
ErrorRecord.Columns.Remove("更换时间");
ErrorRecord.Columns.Remove("更换原因");
ErrorRecord.Columns.Remove("ZT1");
ErrorRecord.Columns.Remove("维护时间");
ErrorRecord.Columns.Remove("送检扫描日期");
ErrorRecord.Columns.Remove("上传日期");
ErrorRecord.Columns.Remove("启用日期");
ErrorRecord.Columns.Remove("检定日期");
ErrorRecord.Columns.Remove("有效日期");
ErrorRecord.Columns.Remove("确认日期");
SuccessRecord.Columns.Remove("序号");
SuccessRecord.Columns.Remove("管理编号");
SuccessRecord.Columns.Remove("保管员");
SuccessRecord.Columns.Remove("资产归属");
SuccessRecord.Columns.Remove("测量过程类别");
SuccessRecord.Columns.Remove("出厂日期");
SuccessRecord.Columns.Remove("计量单位");
SuccessRecord.Columns.Remove("分度值");
SuccessRecord.Columns.Remove("仪表长度");
SuccessRecord.Columns.Remove("检定状态");
SuccessRecord.Columns.Remove("更换时间");
SuccessRecord.Columns.Remove("更换原因");
SuccessRecord.Columns.Remove("ZT1");
SuccessRecord.Columns.Remove("维护时间");
SuccessRecord.Columns.Remove("送检扫描日期");
SuccessRecord.Columns.Remove("上传日期");
SuccessRecord.Columns.Remove("启用日期");
SuccessRecord.Columns.Remove("检定日期");
SuccessRecord.Columns.Remove("有效日期");
SuccessRecord.Columns.Remove("确认日期");
string name = path + "ErrorRecord.xml";
ErrorRecord.WriteXml(name, XmlWriteMode.WriteSchema);
name = path + "SuccessRecord.xml";
SuccessRecord.WriteXml(name, XmlWriteMode.WriteSchema);
//对接日志
dt = new DataTable("Record");
dt.Columns.Add(new DataColumn("日期", typeof(string)));
dt.Columns.Add(new DataColumn("成功个数", typeof(string)));
dt.Columns.Add(new DataColumn("错误个数", typeof(string)));
DataRow tempDr = dt.NewRow();
tempDr[0] = System.DateTime.Now;
tempDr[1] = SuccessRecord.Rows.Count;
tempDr[2] = ErrorRecord.Rows.Count;
dt.Rows.Add(tempDr);
name = path + "Log.xml";
dt.WriteXml(name, XmlWriteMode.WriteSchema);
dt.WriteXml(path + "updateFlag.xml", XmlWriteMode.WriteSchema);
Console.WriteLine("更新" + (nn).ToString() + "条记录" + "||||插入" + (mm).ToString() + "条记录" + "错误" + jj.ToString() + "条记录");
}
//更新时判断是否一样,一样就不更新
protected bool IsEqual(DataRow dr_AfterCode, DataTable ZYYT, string ccbh)
{
DataRow[] dr = ZYYT.Select("F_CCBH='" + ccbh + "' and F_EJDW='EJ0010'");
if (!dr_AfterCode["管理单位"].ToString().Equals(dr[0]["F_SJDW"].ToString())) { return true; }
if (!dr_AfterCode["设备类别"].ToString().Equals(dr[0]["F_LB"].ToString())) { return true; }
if (!dr_AfterCode["应配准确等要求"].ToString().ToString().Equals(dr[0]["F_ZQDDJYQ"].ToString())) { return true; }
if (!dr_AfterCode["测量设备名称"].ToString().ToString().Equals(dr[0]["F_JLQJMC"].ToString())) { return true; }
if (!dr_AfterCode["规格型号"].ToString().Equals(dr[0]["F_GGXH"].ToString())) { return true; }
if (!dr_AfterCode["测量范围"].ToString().Equals(dr[0]["F_CLFW"].ToString())) { return true; }
if (!dr_AfterCode["准确度等级"].ToString().Equals(dr[0]["F_ZQDDJ"].ToString())) { return true; }
if (!dr_AfterCode["测量介质"].ToString().Equals(dr[0]["F_CLJZ"].ToString())) { return true; }
if (!dr_AfterCode["检定周期"].ToString().Equals(dr[0]["F_JDZQ"].ToString())) { return true; }
if (!dr_AfterCode["有效日期1"].ToString().Equals(dr[0]["F_YXRQ"].ToString())) { return true; }
if (!dr_AfterCode["检定单位"].ToString().Equals(dr[0]["F_JDDW"].ToString())) { return true; }
if (!dr_AfterCode["调休情况"].ToString().Equals(dr[0]["F_TXQK"].ToString())) { return true; }
if (!dr_AfterCode["证书编号"].ToString().Equals(dr[0]["F_ZSBH"].ToString())) { return true; }
if (!dr_AfterCode["状态"].ToString().Equals(dr[0]["F_ZT"].ToString())) { return true; }
if (!dr_AfterCode["标准器"].ToString().Equals(dr[0]["F_BZQ"].ToString())) { return true; }
if (!dr_AfterCode["安全防护"].ToString().Equals(dr[0]["F_AQFH"].ToString())) { return true; }
if (!dr_AfterCode["环境监测"].ToString().Equals(dr[0]["F_HJJC"].ToString())) { return true; }
if (!dr_AfterCode["贸易结算"].ToString().Equals(dr[0]["F_MYJS"].ToString())) { return true; }
if (!dr_AfterCode["工艺控制"].ToString().Equals(dr[0]["F_GCKZ"].ToString())) { return true; }
if (!dr_AfterCode["质量检测"].ToString().Equals(dr[0]["F_ZLJC"].ToString())) { return true; }
if (!dr_AfterCode["耗能计量"].ToString().Equals(dr[0]["F_HNJL"].ToString())) { return true; }
if (!dr_AfterCode["产能计量"].ToString().Equals(dr[0]["F_CNJL"].ToString())) { return true; }
if (!dr_AfterCode["检定类别"].ToString().Equals(dr[0]["F_JDLB"].ToString())) { return true; }
if (!dr_AfterCode["管理类别"].ToString().Equals(dr[0]["F_GLLB"].ToString())) { return true; }
if (!dr_AfterCode["检定费用"].ToString().Equals(dr[0]["F_JDFY"].ToString())) { return true; }
if (!dr_AfterCode["制造厂家"].ToString().Equals(dr[0]["F_SCCJ"].ToString())) { return true; }
if (!dr_AfterCode["检定日期1"].ToString().Equals(dr[0]["F_JDRQ"].ToString())) { return true; }
if (!dr_AfterCode["集输站场"].ToString().Equals(dr[0]["F_JCZD"].ToString())) { return true; }
if (!dr_AfterCode["使用存放地点"].ToString().Equals(dr[0]["F_AZD"].ToString())) { return true; }
if (!dr_AfterCode["测量参数"].ToString().Equals(dr[0]["F_CSMC"].ToString())) { return true; }
if (!dr_AfterCode["变化范围"].ToString().Equals(dr[0]["F_BHFW"].ToString())) { return true; }
if (!dr_AfterCode["启用日期1"].ToString().Equals(dr[0]["F_QYRQ"].ToString())) { return true; }
if (!dr_AfterCode["检定结果"].ToString().Equals(dr[0]["F_JDJG"].ToString())) { return true; }
if (!dr_AfterCode["具体耗能"].ToString().Equals(dr[0]["F_HNJLXQ"].ToString())) { return true; }
if (!dr_AfterCode["确认日期1"].ToString().Equals(dr[0]["F_QRRQ"].ToString())) { return true; }
return false;
}
/// <summary>
/// 产销厂台帐,过滤不要的器具名称
/// </summary>
/// <returns></returns>
private DataTable TRQCXC()
{
string sql = "select * from clsbtz where 状态 ='在用' and 使用存放地点 is not null and 制造厂家 is not null and 测量设备名称 not in('InTouch组态软件','WebAccess组态软件','工业热电阻检定软件','孔板综合测量仪软件','硫氮测定仪嵌入式软件','三K值计算程序','天然气流量计算管理系统','PCM金属探测仪')";
//string sql = "select * from clsbtz where 状态 ='在用' and 使用存放地点 is not null and 制造厂家 is not null and 测量设备名称 not in('InTouch组态软件','WebAccess组态软件','工业热电阻检定软件','孔板综合测量仪软件','硫氮测定仪嵌入式软件','三K值计算程序','天然气流量计算管理系统','PCM金属探测仪')";
return dt = OraDataBase.OracleHelper.DataAdapter(sql, "DT").Tables[0];
}
/// <summary>
/// 局台帐
/// </summary>
/// <returns></returns>
private DataTable ZYYT()
{
//string sql = "select * from JL_QJ_JLQJ where f_ejdw = 'EJ0010'";
string sql = "select * from JL_QJ_JLQJ where f_ejdw = 'EJ0010'";
return dt = OracleHelper.DataAdapter100(sql, "DT").Tables[0];
}
/// <summary>
/// 局台帐基础表:管理单位视图
/// </summary>
/// <returns></returns>
private DataTable GLDW()
{
//二三四级单位
string strCmd = "select * from VIEW_JL_DW1234 where f_ejdwbh = 'EJ0010'";
return dt = OracleHelper.DataAdapter100(strCmd, "DT").Tables[0];
}
/// <summary>
/// 局台帐基础表:器具基础信息视图
/// </summary>
/// <returns></returns>
private DataTable EquipInfo()
{
//二三四级单位
string strCmd = "select * from VIEW_JL_DIC_CJGG";
return dt = OracleHelper.DataAdapter100(strCmd, "DT").Tables[0];
}
/// <summary>
/// 准确度等级
/// </summary>
/// <returns></returns>
private DataTable ZQDDJ()
{
string strCmd = "select * from jl_dic_zqddj";
return dt = OracleHelper.DataAdapter100(strCmd, "DT").Tables[0];
}
/// <summary>
/// 测量参数
/// </summary>
/// <returns></returns>
private DataTable CLCS()
{
string strCmd = "select * from jl_dic_clcs";
return dt = OracleHelper.DataAdapter100(strCmd, "DT").Tables[0];
}
/// <summary>
/// 测量介质
/// </summary>
/// <returns></returns>
private DataTable CLJZ()
{
string strCmd = "select * from jl_dic_cljz";
return dt = OracleHelper.DataAdapter100(strCmd, "DT").Tables[0];
}
/// <summary>
/// 检定单位
/// </summary>
/// <returns></returns>
private DataTable JDDW()
{
string strCmd = "select * from jl_dic_jddw";
return dt = OracleHelper.DataAdapter100(strCmd, "DT").Tables[0];
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("UpdateMeter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("UpdateMeter")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("62c90320-fe5a-4120-9e06-5055266ba09c")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{07D0B046-C0AD-49E9-BDA6-C6BB0252F26A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UpdateMeter</RootNamespace>
<AssemblyName>UpdateMeter</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>D:\GetPLCData\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DataBaseTools.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Binary file not shown.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More