项目名称:winFormYaoceUpload 2023
using common; using DBUtility; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
namespace winFormYaoceUpload {
public partial class Form1 : Form
{
DB db = new DB(); //默认数据库是 地面水监测
BindingCase bindingCase;
bool needAsk = true;
public Form1()
{
InitializeComponent();
}
//从地面水监测库读取
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = db.getConection();
bindingCase=db.bindDataSourceToGrid("select * from 基础信息表1", dataGridView1,con);
}
private void btnSave_Click(object sender, EventArgs e)
{
db.SaveGrid(bindingCase);
MessageBox.Show("保存完成");
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
public static void HandleRunningInstance(Process instance)
{
//Make sure the window is not minimized or maximized
// ShowWindowAsync (instance.MainWindowHandle , WS_SHOWNORMAL);
//Set the real intance to foreground window
SetForegroundWindow(instance.MainWindowHandle);
}
private void Form1_Load(object sender, EventArgs e)
{
Process instance = RunningInstance();
if (instance != null)
{
MessageBox.Show("程序已经运行!", "系统提示");
//There is another instance of this process.
HandleRunningInstance(instance);
needAsk = false;
Close();
return;
}
try
{
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
var key = "yaoceUpload_" + path.GetHashCode();
rk2.SetValue(key, path);
rk2.Close();
rk.Close();
//MessageBox.Show("开机启动设置成功@" + key);
}
catch { }
UIControlSaveConfigHelper.LoadConfig(this);
dgLog.AutoGenerateColumns = false;
//创建日志表
var sql = "select * from sysobjects where name='SyncLog'";
if (DB.ExecuteQuery(sql).Rows.Count==0)
{
DB.ExecuteNoneQuery(@"CREATE TABLE [dbo].[SyncLog](
[time] [datetime] NULL,
[tableName] [varchar](50) NULL,
[newCount] [int] NULL,
[flag] [bit] NULL,
Msg [nvarchar](100) NULL,
lastID int NULL
) ON [PRIMARY]");
}
timer1.Enabled = true;
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
timer1.Stop();
try
{
DB.ExecuteNoneQuery("delete from 基础信息表");
int r = DB.ExecuteNoneQuery(@"insert into 基础信息表 select '00000000008' as 矿井名称,* from dmsw.dbo.zck ");
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag) values(getDate(),'基础信息表',{r},1)");
}
catch (System.Exception ex)
{
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,Msg) values(getDate(),'基础信息表',null,0,{ex.Message.Substring(0, 100)})");
}
try
{
DB.ExecuteNoneQuery("delete from 钻孔位置表");
int r = DB.ExecuteNoneQuery(@"insert into 钻孔位置表 select * from 钻孔位置表1 ");
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag) values(getDate(),'钻孔位置表',{r},1)");
}
catch (System.Exception ex)
{
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,Msg) values(getDate(),'钻孔位置表',null,0,{ex.Message.Substring(0, 100)})");
}
//各表的数据
#region 按增量同步 (这个项目不需要增量同步,只要最新的数据),所以停用
try
{
var dtAllTable = DB.ExecuteQuery("select * from 基础信息表1");
var mapping = DB.ExecuteQuery("select * from mapping").Select();
foreach (DataRow dr in dtAllTable.Rows)
{
try
{
var map = mapping.Where(x => x["T2"].ToString() == dr["钻孔名称"].ToString()).SingleOrDefault();
if (map != null)
{
string realName = map["T2"].ToString(); //整理后的钻孔名
string holeName = "钻孔" + map["T1"].ToString(); //之前的钻孔名
if (realName == "BK4_1_2")
{
var a = 1;
}
var sqlLastRec = $"select top 1 * from SyncLog where tableName='{realName}' order by time desc";
var dtLastRec = DB.ExecuteQuery(sqlLastRec);
DataTable dt;
if (dtLastRec.Rows.Count > 0)
{
int lastID = Convert.ToInt32(dtLastRec.Rows[0]["lastID"]);
dt = DB.ExecuteQuery($@"select '00000000008' as 矿井名称,'{realName}' as 钻孔名称,* from Dmsw.dbo.{holeName} where 序号>{lastID}");
}
else //第一次导入,只导现在往前一个小时的
{
dt = DB.ExecuteQuery($@"select '00000000008' as 矿井名称,'{realName}' as 钻孔名称,* from Dmsw.dbo.{holeName} where 时间>'{DateTime.Now.AddHours(-100).ToString()}'");
}
if (dt.Rows.Count == 0) continue;
var maxID = dt.Select().Max(x => x["序号"]);
DB.BulkCopy(dt, "钻孔数据表");
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,lastID) values(getDate(),'{realName}',{dt.Rows.Count},1,{maxID})");
}
}
catch (System.Exception ex)
{
var msg = ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message;
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,Msg) values(getDate(),'钻孔数据表',null,0,{msg})");
}
}
}
catch (System.Exception ex)
{
var msg = ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message;
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,Msg) values(getDate(),'钻孔数据表',null,0,{msg})");
}
#endregion
#region 每个传感器的最新数据
if (false)
{
try
{
DB.ExecuteNoneQuery("delete from 钻孔数据表");
var dtAllTable = DB.ExecuteQuery("select * from 基础信息表1");
var mapping = DB.ExecuteQuery("select * from mapping").Select();
foreach (DataRow dr in dtAllTable.Rows)
{
try
{
var map = mapping.Where(x => x["T2"].ToString() == dr["钻孔名称"].ToString()).SingleOrDefault();
if (map != null)
{
string realName = map["T2"].ToString(); //整理后的钻孔名
string holeName = "钻孔" + map["T1"].ToString(); //之前的钻孔名
DataTable dt;
dt = DB.ExecuteQuery($@"select top 1 '00000000008' as 矿井名称,'{realName}' as 钻孔名称,* from Dmsw.dbo.{holeName} order by 序号 desc");
if (dt.Rows.Count == 0) continue;
var maxID = dt.Select().Max(x => x["序号"]);
DB.BulkCopy(dt, "钻孔数据表");
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,lastID) values(getDate(),'{realName}',{dt.Rows.Count},1,{maxID})");
}
}
catch (System.Exception ex)
{
var msg = ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message;
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,Msg) values(getDate(),'钻孔数据表',null,0,{msg})");
}
}
}
catch (System.Exception ex)
{
var msg = ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message;
DB.ExecuteNoneQuery($@"insert into SyncLog(time,tablename,newcount,flag,Msg) values(getDate(),'钻孔数据表',null,0,{msg})");
}
}
#endregion
//刷新日志
dgLog.DataSource = null;
dgLog.DataSource = DB.ExecuteQuery("select top 100 convert(char(20),time,120) as time,tableName,newCount,flag,lastID from syncLog order by time desc");
//太长了清空一下显示
}
finally
{
timer1.Interval = int.Parse(tbInterval.Text) * 1000 *60;
timer1.Start();
}
}
private void tbInterval_TextChanged(object sender, EventArgs e)
{
timer1.Interval = int.Parse(tbInterval.Text) * 1000 * 60;
UIControlSaveConfigHelper.SaveConfig(this);
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
notifyIcon1.Visible = false;
}
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.ShowInTaskbar = false;
notifyIcon1.Visible = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (needAsk)
{
if (MessageBox.Show("确定要退出吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
}
else
{
e.Cancel = true;
}
}
}
}
}