Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightCentralizedControlManagement
This commit is contained in:
commit
8c351c792c
73 files changed
+11632
-1
No files matched your search
@@ -0,0 +1,344 @@
|
||||
using DyeingComputer.UserClass;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Reflection.Emit;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Diagnostics;
|
||||
using TouchSocket.Core;
|
||||
using TouchSocket.Sockets;
|
||||
using DyeingComputer.ViewModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using ScottPlot.Colormaps;
|
||||
using static System.Windows.Forms.AxHost;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
||||
using Newtonsoft.Json;
|
||||
using static DyeingComputer.UserClass.SqliteHelper;
|
||||
using DyeingComputer.View;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{/// <summary>
|
||||
/// 异步TCP服务器
|
||||
/// </summary>
|
||||
public class AsyncTcpServer
|
||||
{
|
||||
//设置系统时间的API函数
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern bool SetLocalTime(ref SYSTEMTIME time);
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct SYSTEMTIME
|
||||
{
|
||||
public short year;
|
||||
public short month;
|
||||
public short dayOfWeek;
|
||||
public short day;
|
||||
public short hour;
|
||||
public short minute;
|
||||
public short second;
|
||||
public short milliseconds;
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置系统时间
|
||||
/// </summary>
|
||||
/// <param name="dt">需要设置的时间</param>
|
||||
/// <returns>返回系统时间设置状态,true为成功,false为失败</returns>
|
||||
private static bool SetLocalDateTime(DateTime dt)
|
||||
{
|
||||
SYSTEMTIME st;
|
||||
st.year = (short)dt.Year;
|
||||
st.month = (short)dt.Month;
|
||||
st.dayOfWeek = (short)dt.DayOfWeek;
|
||||
st.day = (short)dt.Day;
|
||||
st.hour = (short)dt.Hour;
|
||||
st.minute = (short)dt.Minute;
|
||||
st.second = (short)dt.Second;
|
||||
st.milliseconds = (short)dt.Millisecond;
|
||||
bool rt = SetLocalTime(ref st);
|
||||
return rt;
|
||||
}
|
||||
|
||||
public static async Task Main()
|
||||
{
|
||||
NetFwManger.AllowPort(7790,"TCP");//开放7790端口
|
||||
TcpService service = new TcpService();
|
||||
service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
|
||||
service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接
|
||||
service.Closing = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。
|
||||
service.Closed = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接
|
||||
service.Received = (client, e) =>
|
||||
{
|
||||
string SYSAPI = e.ByteBlock.Span.ToString(Encoding.ASCII).Substring(0,5);
|
||||
string DAT = e.ByteBlock.Span.ToString(Encoding.ASCII).Substring(5);
|
||||
string SYSDAT ="";// = e.ByteBlock.Span.ToString(Encoding.ASCII).Substring(5);
|
||||
string SYSKEY ="";
|
||||
if(DAT.Length>=16) SYSKEY = DAT.Substring(0,16);
|
||||
if (DAT.Length > 16) SYSDAT = DAT.Substring(16);
|
||||
//LogGing.LogSQLDATA("800", "TcpServer", "API:"+ SYSAPI);
|
||||
if (SYSAPI == "SC800")
|
||||
{
|
||||
Dictionary<string, object> Chart_new = new Dictionary<string, object>();//缓存函数
|
||||
Chart_new.Add("MACHINE", MainWindowViewModel.S01);
|
||||
Chart_new.Add("GROUP", MainWindowViewModel.S05);
|
||||
Chart_new.Add("SYSKEY", MainWindowViewModel.SYSKEY);
|
||||
Chart_new.Add("TIME", MainWindowViewModel.SYSTime);
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" + Chart_new.ToJsonString());
|
||||
}
|
||||
else if (SYSAPI == "SC810")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
try
|
||||
{
|
||||
Dictionary<string, object> WorkOrder_dat;
|
||||
WorkOrder_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(SYSDAT);
|
||||
//WorkOrder_dat.GetValue("WorkOrder");
|
||||
bool dat_w= SQLDATA.WorkOrder(
|
||||
WorkOrder_dat.GetValue("WorkOrder").ToString(),
|
||||
WorkOrder_dat.GetValue("ProcessName").ToString(),
|
||||
WorkOrder_dat.GetValue("StartTime").ToString(),
|
||||
WorkOrder_dat.GetValue("EndTime").ToString(),
|
||||
WorkOrder_dat.GetValue("Time").ToString(),
|
||||
WorkOrder_dat.GetValue("Remark").ToString(),
|
||||
WorkOrder_dat.GetValue("lock").ToString(),
|
||||
WorkOrder_dat.GetValue("State").ToString(),
|
||||
WorkOrder_dat.GetValue("ProcessID").ToString());
|
||||
if (!dat_w) { client.SendAsync("SC910"); }
|
||||
else { client.SendAsync("SC810"+SYSKEY+SYSDAT); }
|
||||
}
|
||||
catch
|
||||
{
|
||||
client.SendAsync("SC990");
|
||||
}
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//WorkOrder表信息检查写入
|
||||
else if (SYSAPI == "SC811")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
try
|
||||
{
|
||||
DataTable WorkOrder_dat;
|
||||
WorkOrder_dat = SerializeConvert.JsonDeserializeFromString<DataTable>(SYSDAT);
|
||||
bool dat_w = SQLDATA.WorkOderStep(WorkOrder_dat);
|
||||
if (!dat_w) { client.SendAsync("SC911"); }
|
||||
else { client.SendAsync("SC811" + SYSKEY + SYSDAT); }
|
||||
}
|
||||
catch
|
||||
{
|
||||
client.SendAsync("SC991");
|
||||
}
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//WorkOrderstep表信息检查写入
|
||||
else if (SYSAPI == "SC820")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (SYSDAT.Length == 21)
|
||||
{
|
||||
SYSDAT = SYSDAT.Substring(1, 19);
|
||||
DateTime dt;
|
||||
if (DateTime.TryParse(SYSDAT, out dt))
|
||||
SetLocalDateTime(dt);
|
||||
}
|
||||
client.SendAsync("[" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]");
|
||||
}
|
||||
catch { client.SendAsync("SC920"); }
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//设置系统时间
|
||||
else if (SYSAPI == "SC821")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
try
|
||||
{
|
||||
Dictionary<string, object> dat_821;
|
||||
dat_821 = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(SYSDAT);
|
||||
if (dat_821.GetValue("INSTRUCTION").ToString() == "START")
|
||||
{
|
||||
SQLDATA.TechnologicalProcess_START(dat_821.GetValue("ProgramID").ToString());
|
||||
}
|
||||
else if (dat_821.GetValue("INSTRUCTION").ToString() == "STOP")
|
||||
{
|
||||
MainWindowViewModel.WORK_RUN = 0;//停止
|
||||
MainWindowViewModel.DIDETime = 0;
|
||||
}
|
||||
else if (dat_821.GetValue("INSTRUCTION").ToString() == "PAUSE")
|
||||
{
|
||||
MainWindowViewModel.WORK_RUN = 1;//暂停
|
||||
}
|
||||
else if (dat_821.GetValue("INSTRUCTION").ToString() == "CONTINUE")
|
||||
{
|
||||
MainWindowViewModel.WORK_RUN = 2;//暂停
|
||||
}
|
||||
else if (dat_821.GetValue("INSTRUCTION").ToString() == "JUMP")
|
||||
{
|
||||
MainWindowViewModel.RUN_DATATABLE = TechnologicalProcessView.sql.Tables[0];//缓存表
|
||||
MainWindowViewModel.RUN_STEPID = Convert.ToInt16(dat_821.GetValue("ID").ToString());//插入步骤号
|
||||
MainWindowViewModel.STEP_START(dat_821.GetValue("Numder").ToString(), Convert.ToDouble(dat_821.GetValue("P1")),
|
||||
Convert.ToDouble(dat_821.GetValue("P2")), Convert.ToDouble(dat_821.GetValue("P3")),
|
||||
Convert.ToDouble(dat_821.GetValue("P4")), Convert.ToDouble(dat_821.GetValue("P5")));
|
||||
}
|
||||
client.SendAsync("SC821" + SYSKEY + SYSDAT);
|
||||
}
|
||||
catch { client.SendAsync("SC921"); }
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//启停跳步指令
|
||||
else if (SYSAPI == "SC830")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
Dictionary<string, object> Chart_new = new Dictionary<string, object>();//缓存函数
|
||||
Chart_new.Add("DYELOT", MainWindowViewModel.WorkNumder);
|
||||
Chart_new.Add("Time", MainWindowViewModel.SYSTime);
|
||||
Chart_new.Add("MST", MainWindowViewModel.TEMP_co);
|
||||
Chart_new.Add("MTT", MainWindowViewModel.Selet_dtm("1010"));
|
||||
Chart_new.Add("MTL", MainWindowViewModel.Selet_dtm("1015"));
|
||||
Chart_new.Add("MTH", MainWindowViewModel.Selet_dtm("1009"));
|
||||
Chart_new.Add("MUT", MainWindowViewModel.Selet_dtm("1011"));
|
||||
Chart_new.Add("STTA", MainWindowViewModel.Selet_dtm("1012"));
|
||||
Chart_new.Add("STLA", MainWindowViewModel.Selet_dtm("1017"));
|
||||
Chart_new.Add("STTB", MainWindowViewModel.Selet_dtm("1013"));
|
||||
Chart_new.Add("STLB", MainWindowViewModel.Selet_dtm("1018"));
|
||||
Chart_new.Add("STTC", MainWindowViewModel.Selet_dtm("1014"));
|
||||
Chart_new.Add("STLC", MainWindowViewModel.Selet_dtm("1019"));
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" + Chart_new.ToJsonString());
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//当前信息
|
||||
else if (SYSAPI == "SC831")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" +TechnologicalProcessView.sql.Tables[0].ToJsonString());
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//当前工作表
|
||||
else if (SYSAPI == "SC832")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" + MainWindowViewModel.SYSlog);
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//当前细节信息
|
||||
else if (SYSAPI == "SC851")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" + MainWindowViewModel.dt_d.ToJsonString());//数字开关信息
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//数字开关表
|
||||
else if (SYSAPI == "SC852")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" + MainWindowViewModel.dt_a.ToJsonString());//寄存器信息
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//寄存器表
|
||||
else if (SYSAPI == "SC853")
|
||||
{
|
||||
if (SYSKEY == MainWindowViewModel.SYSKEY)
|
||||
{
|
||||
client.SendAsync("[" + MainWindowViewModel.S01 + "]" + MainWindowViewModel.dt_m.ToJsonString());//缓存信息
|
||||
}
|
||||
else { client.SendAsync("SC999"); }
|
||||
}//缓存表
|
||||
|
||||
return EasyTask.CompletedTask;
|
||||
};
|
||||
|
||||
await service.SetupAsync(new TouchSocketConfig()//载入配置
|
||||
.SetListenIPHosts(new IPHost[] { new IPHost("tcp://127.0.0.1:7789"), new IPHost(7790) })//同时监听两个地址
|
||||
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
|
||||
{
|
||||
//a.AddConsoleLogger();//添加一个控制台日志注入(注意:在maui中控制台日志不可用)
|
||||
})
|
||||
.ConfigurePlugins(a =>
|
||||
{
|
||||
//a.Add<DifferentProtocolPlugin>();
|
||||
})
|
||||
);
|
||||
await service.StartAsync();//启动
|
||||
|
||||
LogGing.LogGingDATA("800SREVER:START");
|
||||
}
|
||||
}
|
||||
|
||||
class MyTcpService : TcpService<MyTcpSessionClient>
|
||||
{
|
||||
protected override MyTcpSessionClient NewClient()
|
||||
{
|
||||
return new MyTcpSessionClient();
|
||||
}
|
||||
}
|
||||
|
||||
class MyTcpSessionClient : TcpSessionClient
|
||||
{
|
||||
internal void SetDataHandlingAdapter(SingleStreamDataHandlingAdapter adapter)
|
||||
{
|
||||
base.SetAdapter(adapter);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 此插件实现,按照不同端口,使用不同适配器。
|
||||
/// <list type="bullet">
|
||||
/// <item>7789端口:使用"**"结尾的数据</item>
|
||||
/// <item>7790端口:使用"##"结尾的数据</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal class DifferentProtocolPlugin : PluginBase, ITcpConnectingPlugin, ITcpReceivedPlugin
|
||||
{
|
||||
public async Task OnTcpConnecting(ITcpSession client, ConnectingEventArgs e)
|
||||
{
|
||||
if (client is MyTcpSessionClient sessionClient)
|
||||
{
|
||||
if (sessionClient.ServicePort == 7789)
|
||||
{
|
||||
sessionClient.SetDataHandlingAdapter(new TerminatorPackageAdapter("**"));
|
||||
}
|
||||
else
|
||||
{
|
||||
sessionClient.SetDataHandlingAdapter(new TerminatorPackageAdapter("##"));
|
||||
}
|
||||
}
|
||||
|
||||
await e.InvokeNext();
|
||||
}
|
||||
|
||||
public async Task OnTcpReceived(ITcpSession client, ReceivedDataEventArgs e)
|
||||
{
|
||||
//如果是自定义适配器,此处解析时,可以判断e.RequestInfo的类型
|
||||
|
||||
if (client is ITcpSessionClient sessionClient)
|
||||
{
|
||||
sessionClient.Logger.Info($"{sessionClient.GetIPPort()}收到数据,服务器端口:{sessionClient.ServicePort},数据:{e.ByteBlock}");
|
||||
}
|
||||
|
||||
await e.InvokeNext();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// CRC校验
|
||||
/// </summary>
|
||||
public class CRCcheck16
|
||||
{
|
||||
|
||||
#region CRC16
|
||||
public static byte[] CRC16(byte[] data)
|
||||
{
|
||||
int len = data.Length;
|
||||
if (len > 0)
|
||||
{
|
||||
ushort crc = 0xFFFF;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
crc = (ushort)(crc ^ (data[i]));
|
||||
for (int j = 0; j < 8; j++)
|
||||
{
|
||||
crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
|
||||
}
|
||||
}
|
||||
byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
|
||||
byte lo = (byte)(crc & 0x00FF); //低位置
|
||||
|
||||
return new byte[] { hi, lo };
|
||||
}
|
||||
return new byte[] { 0, 0 };
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ToCRC16
|
||||
public static string ToCRC16(string content)
|
||||
{
|
||||
return ToCRC16(content, Encoding.UTF8);
|
||||
}
|
||||
|
||||
public static string ToCRC16(string content, bool isReverse)
|
||||
{
|
||||
return ToCRC16(content, Encoding.UTF8, isReverse);
|
||||
}
|
||||
|
||||
public static string ToCRC16(string content, Encoding encoding)
|
||||
{
|
||||
return ByteToString(CRC16(encoding.GetBytes(content)), true);
|
||||
}
|
||||
|
||||
public static string ToCRC16(string content, Encoding encoding, bool isReverse)
|
||||
{
|
||||
return ByteToString(CRC16(encoding.GetBytes(content)), isReverse);
|
||||
}
|
||||
|
||||
public static string ToCRC16(byte[] data)
|
||||
{
|
||||
return ByteToString(CRC16(data), true);
|
||||
}
|
||||
|
||||
public static string ToCRC16(byte[] data, bool isReverse)
|
||||
{
|
||||
return ByteToString(CRC16(data), isReverse);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ToModbusCRC16
|
||||
public static string ToModbusCRC16(string s)
|
||||
{
|
||||
return ToModbusCRC16(s, true);
|
||||
}
|
||||
|
||||
public static string ToModbusCRC16(string s, bool isReverse)
|
||||
{
|
||||
return ByteToString(CRC16(StringToHexByte(s)), isReverse);
|
||||
}
|
||||
|
||||
public static string ToModbusCRC16(byte[] data)
|
||||
{
|
||||
return ToModbusCRC16(data, true);
|
||||
}
|
||||
|
||||
public static string ToModbusCRC16(byte[] data, bool isReverse)
|
||||
{
|
||||
return ByteToString(CRC16(data), isReverse);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ByteToString
|
||||
public static string ByteToString(byte[] arr, bool isReverse)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte hi = arr[0], lo = arr[1];
|
||||
return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0');
|
||||
}
|
||||
catch (Exception ex) { throw (ex); }
|
||||
}
|
||||
|
||||
public static string ByteToString(byte[] arr)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ByteToString(arr, true);
|
||||
}
|
||||
catch (Exception ex) { throw (ex); }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region StringToHexString
|
||||
public static string StringToHexString(string str)
|
||||
{
|
||||
StringBuilder s = new StringBuilder();
|
||||
foreach (short c in str.ToCharArray())
|
||||
{
|
||||
s.Append(c.ToString("X4"));
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region StringToHexByte
|
||||
private static string ConvertChinese(string str)
|
||||
{
|
||||
StringBuilder s = new StringBuilder();
|
||||
foreach (short c in str.ToCharArray())
|
||||
{
|
||||
if (c <= 0 || c >= 127)
|
||||
{
|
||||
s.Append(c.ToString("X4"));
|
||||
}
|
||||
else
|
||||
{
|
||||
s.Append((char)c);
|
||||
}
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
private static string FilterChinese(string str)
|
||||
{
|
||||
StringBuilder s = new StringBuilder();
|
||||
foreach (short c in str.ToCharArray())
|
||||
{
|
||||
if (c > 0 && c < 127)
|
||||
{
|
||||
s.Append((char)c);
|
||||
}
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 字符串转16进制字符数组
|
||||
/// </summary>
|
||||
/// <param name="hex"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] StringToHexByte(string str)
|
||||
{
|
||||
return StringToHexByte(str, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 字符串转16进制字符数组
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="isFilterChinese">是否过滤掉中文字符</param>
|
||||
/// <returns></returns>
|
||||
public static byte[] StringToHexByte(string str, bool isFilterChinese)
|
||||
{
|
||||
string hex = isFilterChinese ? FilterChinese(str) : ConvertChinese(str);
|
||||
|
||||
//清除所有空格
|
||||
hex = hex.Replace(" ", "");
|
||||
//若字符个数为奇数,补一个0
|
||||
hex += hex.Length % 2 != 0 ? "0" : "";
|
||||
|
||||
byte[] result = new byte[hex.Length / 2];
|
||||
for (int i = 0, c = result.Length; i < c; i++)
|
||||
{
|
||||
result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
using Microsoft.Win32;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Markup;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
internal class CSV
|
||||
{
|
||||
/// <summary>
|
||||
/// 将DataTable中数据写入到CSV文件中
|
||||
/// </summary>
|
||||
/// <param name="dt">提供保存数据的DataTable</param>
|
||||
/// <param name="strFormat">CSV的文件路径</param>
|
||||
public static void SaveCSV(DataTable dt,string strFormat)
|
||||
{
|
||||
FileInfo fi = new FileInfo(strFormat);
|
||||
if (!fi.Directory.Exists)
|
||||
{
|
||||
fi.Directory.Create();
|
||||
}
|
||||
FileStream fs = new FileStream(strFormat, System.IO.FileMode.Create, System.IO.FileAccess.Write);
|
||||
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
|
||||
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
|
||||
string data = "";
|
||||
//写出列名称
|
||||
for (int i = 0; i < dt.Columns.Count; i++)
|
||||
{
|
||||
data += dt.Columns[i].ColumnName.ToString();
|
||||
if (i < dt.Columns.Count - 1)
|
||||
{
|
||||
data += ",";
|
||||
}
|
||||
}
|
||||
sw.WriteLine(data);
|
||||
//写出各行数据
|
||||
for (int i = 0; i < dt.Rows.Count; i++)
|
||||
{
|
||||
data = "";
|
||||
for (int j = 0; j < dt.Columns.Count; j++)
|
||||
{
|
||||
string str = dt.Rows[i][j].ToString();
|
||||
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
|
||||
if (str.Contains(',') || str.Contains('"')
|
||||
|| str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
|
||||
{
|
||||
str = string.Format("\"{0}\"", str);
|
||||
}
|
||||
|
||||
data += str;
|
||||
if (j < dt.Columns.Count - 1)
|
||||
{
|
||||
data += ",";
|
||||
}
|
||||
}
|
||||
sw.WriteLine(data);
|
||||
}
|
||||
sw.Close(); fs.Close();
|
||||
}
|
||||
|
||||
#region CSV文件读取
|
||||
/// <summary>
|
||||
/// 将CSV文件的数据读取到DataTable中
|
||||
/// </summary>
|
||||
/// <param name="fileName">CSV文件路径</param>
|
||||
/// <returns>返回读取了CSV数据的DataTable</returns>
|
||||
public static DataTable OpenCSV(string filePath)//从csv读取数据返回table
|
||||
{
|
||||
System.Text.Encoding encoding = GetType(filePath); //Encoding.ASCII;//
|
||||
DataTable dt = new DataTable();
|
||||
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
|
||||
System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);
|
||||
|
||||
//记录每次读取的一行记录
|
||||
string strLine = "";
|
||||
//记录每行记录中的各字段内容
|
||||
string[] aryLine = null;
|
||||
string[] tableHead = null;
|
||||
//标示列数
|
||||
int columnCount = 0;
|
||||
//标示是否是读取的第一行
|
||||
bool IsFirst = true;
|
||||
//逐行读取CSV中的数据
|
||||
int readCol = 0;
|
||||
while ((strLine = sr.ReadLine()) != null)
|
||||
{
|
||||
if (readCol > 0)
|
||||
{
|
||||
if (IsFirst == true)
|
||||
{
|
||||
tableHead = strLine.Split(',');
|
||||
IsFirst = false;
|
||||
columnCount = tableHead.Length;
|
||||
//创建列
|
||||
for (int i = 0; i < columnCount; i++)
|
||||
{
|
||||
DataColumn dc = new DataColumn(tableHead[i]);
|
||||
dt.Columns.Add(dc);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
aryLine = strLine.Split(',');
|
||||
DataRow dr = dt.NewRow();
|
||||
for (int j = 0; j < columnCount; j++)
|
||||
{
|
||||
dr[j] = aryLine[j];
|
||||
}
|
||||
dt.Rows.Add(dr);
|
||||
}
|
||||
}
|
||||
readCol++;
|
||||
}
|
||||
if (aryLine != null && aryLine.Length > 0)
|
||||
{
|
||||
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
|
||||
}
|
||||
|
||||
sr.Close();
|
||||
fs.Close();
|
||||
return dt;
|
||||
}
|
||||
/// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型
|
||||
/// <param name="FILE_NAME">文件路径</param>
|
||||
/// <returns>文件的编码类型</returns>
|
||||
|
||||
public static System.Text.Encoding GetType(string FILE_NAME)
|
||||
{
|
||||
System.IO.FileStream fs = new System.IO.FileStream(FILE_NAME, System.IO.FileMode.Open,
|
||||
System.IO.FileAccess.Read);
|
||||
System.Text.Encoding r = GetType(fs);
|
||||
fs.Close();
|
||||
return r;
|
||||
}
|
||||
|
||||
/// 通过给定的文件流,判断文件的编码类型
|
||||
/// <param name="fs">文件流</param>
|
||||
/// <returns>文件的编码类型</returns>
|
||||
public static System.Text.Encoding GetType(System.IO.FileStream fs)
|
||||
{
|
||||
byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
|
||||
byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
|
||||
byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
|
||||
System.Text.Encoding reVal = System.Text.Encoding.Default;
|
||||
|
||||
System.IO.BinaryReader r = new System.IO.BinaryReader(fs, System.Text.Encoding.Default);
|
||||
int i;
|
||||
int.TryParse(fs.Length.ToString(), out i);
|
||||
byte[] ss = r.ReadBytes(i);
|
||||
if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
|
||||
{
|
||||
reVal = System.Text.Encoding.UTF8;
|
||||
}
|
||||
else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
|
||||
{
|
||||
reVal = System.Text.Encoding.BigEndianUnicode;
|
||||
}
|
||||
else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
|
||||
{
|
||||
reVal = System.Text.Encoding.Unicode;
|
||||
}
|
||||
r.Close();
|
||||
return reVal;
|
||||
}
|
||||
|
||||
/// 判断是否是不带 BOM 的 UTF8 格式
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
private static bool IsUTF8Bytes(byte[] data)
|
||||
{
|
||||
int charByteCounter = 1; //计算当前正分析的字符应还有的字节数
|
||||
byte curByte; //当前分析的字节.
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
curByte = data[i];
|
||||
if (charByteCounter == 1)
|
||||
{
|
||||
if (curByte >= 0x80)
|
||||
{
|
||||
//判断当前
|
||||
while (((curByte <<= 1) & 0x80) != 0)
|
||||
{
|
||||
charByteCounter++;
|
||||
}
|
||||
//标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
|
||||
if (charByteCounter == 1 || charByteCounter > 6)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//若是UTF-8 此时第一位必须为1
|
||||
if ((curByte & 0xC0) != 0x80)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
charByteCounter--;
|
||||
}
|
||||
}
|
||||
if (charByteCounter > 1)
|
||||
{
|
||||
throw new Exception("非预期的byte格式");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用using代替lock操作的对象,可指定写入和读取锁定模式
|
||||
/// </summary>
|
||||
public sealed class ClsLock
|
||||
{
|
||||
#region 内部类
|
||||
|
||||
/// <summary>
|
||||
/// 利用IDisposable的using语法糖方便的释放锁定操作内部类
|
||||
/// </summary>
|
||||
private struct Lock : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// 读写锁对象
|
||||
/// </summary>
|
||||
private readonly ReaderWriterLockSlim _Lock;
|
||||
/// <summary>
|
||||
/// 是否为写入模式
|
||||
/// </summary>
|
||||
private bool _IsWrite;
|
||||
/// <summary>
|
||||
/// 利用IDisposable的using语法糖方便的释放锁定操作构造函数
|
||||
/// </summary>
|
||||
/// <param name="rwl">读写锁</param>
|
||||
/// <param name="isWrite">写入模式为true,读取模式为false</param>
|
||||
public Lock(ReaderWriterLockSlim rwl, bool isWrite)
|
||||
{
|
||||
_Lock = rwl;
|
||||
_IsWrite = isWrite;
|
||||
}
|
||||
/// <summary>
|
||||
/// 释放对象时退出指定锁定模式
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_IsWrite)
|
||||
{
|
||||
if (_Lock.IsWriteLockHeld)
|
||||
{
|
||||
_Lock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_Lock.IsReadLockHeld)
|
||||
{
|
||||
_Lock.ExitReadLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 空的可释放对象,免去了调用时需要判断是否为null的问题内部类
|
||||
/// </summary>
|
||||
private class Disposable : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// 空的可释放对象
|
||||
/// </summary>
|
||||
public static readonly Disposable Empty = new Disposable();
|
||||
/// <summary>
|
||||
/// 空的释放方法
|
||||
/// </summary>
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 读写锁
|
||||
/// </summary>
|
||||
private readonly ReaderWriterLockSlim _LockSlim = new ReaderWriterLockSlim();
|
||||
/// <summary>
|
||||
/// 使用using代替lock操作的对象,可指定写入和读取锁定模式构造函数
|
||||
/// </summary>
|
||||
public ClsLock()
|
||||
{
|
||||
Enabled = true;
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否启用,当该值为false时,Read()和Write()方法将返回 Disposable.Empty
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 进入读取锁定模式,该模式下允许多个读操作同时进行,
|
||||
/// 退出读锁请将返回对象释放,建议使用using语块,
|
||||
/// Enabled为false时,返回Disposable.Empty,
|
||||
/// 在读取或写入锁定模式下重复执行,返回Disposable.Empty;
|
||||
/// </summary>
|
||||
public IDisposable Read()
|
||||
{
|
||||
if (Enabled == false || _LockSlim.IsReadLockHeld || _LockSlim.IsWriteLockHeld)
|
||||
{
|
||||
return Disposable.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
_LockSlim.EnterReadLock();
|
||||
return new Lock(_LockSlim, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 进入写入锁定模式,该模式下只允许同时执行一个读操作,
|
||||
/// 退出读锁请将返回对象释放,建议使用using语块,
|
||||
/// Enabled为false时,返回Disposable.Empty,
|
||||
/// 在写入锁定模式下重复执行,返回Disposable.Empty
|
||||
/// </summary>
|
||||
/// <exception cref="NotImplementedException">读取模式下不能进入写入锁定状态</exception>
|
||||
public IDisposable Write()
|
||||
{
|
||||
if (Enabled == false || _LockSlim.IsWriteLockHeld)
|
||||
{
|
||||
return Disposable.Empty;
|
||||
}
|
||||
else if (_LockSlim.IsReadLockHeld)
|
||||
{
|
||||
throw new NotImplementedException("读取模式下不能进入写入锁定状态");
|
||||
}
|
||||
else
|
||||
{
|
||||
_LockSlim.EnterWriteLock();
|
||||
return new Lock(_LockSlim, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// 实时更新datagrid
|
||||
/// 调用示例:DataGridHelper.SetRealTimeCommit(Grid, true); Grid为对象控件名
|
||||
/// </summary>
|
||||
public static class DataGridHelper
|
||||
{
|
||||
public static void SetRealTimeCommit(DataGrid dataGrid, bool isRealTime)
|
||||
{
|
||||
dataGrid.SetValue(RealTimeCommitProperty, isRealTime);
|
||||
}
|
||||
|
||||
public static bool GetRealTimeCommit(DataGrid dataGrid)
|
||||
{
|
||||
return (bool)dataGrid.GetValue(RealTimeCommitProperty);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty RealTimeCommitProperty =
|
||||
DependencyProperty.RegisterAttached("RealTimeCommit", typeof(bool),
|
||||
typeof(DataGridHelper),
|
||||
new PropertyMetadata(false, RealTimeCommitCallBack));
|
||||
|
||||
private static void RealTimeCommitCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var dg = d as DataGrid;
|
||||
if (dg == null)
|
||||
return;
|
||||
EventHandler<DataGridCellEditEndingEventArgs> ceHandler = delegate (object xx, DataGridCellEditEndingEventArgs yy)
|
||||
{
|
||||
var flag = GetRealTimeCommit(dg);
|
||||
if (!flag)
|
||||
return;
|
||||
var cellContent = yy.Column.GetCellContent(yy.Row);
|
||||
if (cellContent != null && cellContent.BindingGroup != null)
|
||||
cellContent.BindingGroup.CommitEdit();
|
||||
};
|
||||
dg.CellEditEnding += ceHandler;
|
||||
RoutedEventHandler eh = null;
|
||||
eh = (xx, yy) =>
|
||||
{
|
||||
dg.Unloaded -= eh;
|
||||
dg.CellEditEnding -= ceHandler;
|
||||
};
|
||||
dg.Unloaded += eh;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data;
|
||||
using System.Reflection;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
internal class DataTableToObservableCollection //数据表到可观察集合
|
||||
{
|
||||
public ObservableCollection<T> ToObservableCollection<T>(DataTable dt) where T : class, new()
|
||||
{
|
||||
Type t = typeof(T);
|
||||
PropertyInfo[] propertys = t.GetProperties();
|
||||
ObservableCollection<T> lst = new ObservableCollection<T>();
|
||||
string typeName = string.Empty;
|
||||
foreach (DataRow dr in dt.Rows)
|
||||
{
|
||||
T entity = new T();
|
||||
foreach (PropertyInfo pi in propertys)
|
||||
{
|
||||
typeName = pi.Name;
|
||||
if (dt.Columns.Contains(typeName))
|
||||
{
|
||||
if (!pi.CanWrite) continue;
|
||||
object value = dr[typeName];
|
||||
if (value == DBNull.Value) continue;
|
||||
if (pi.PropertyType == typeof(string))
|
||||
{
|
||||
pi.SetValue(entity, value.ToString(), null);
|
||||
}
|
||||
else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
|
||||
{
|
||||
pi.SetValue(entity, int.Parse(value.ToString()), null);
|
||||
}
|
||||
else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
|
||||
{
|
||||
pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
|
||||
}
|
||||
else if (pi.PropertyType == typeof(float))
|
||||
{
|
||||
pi.SetValue(entity, float.Parse(value.ToString()), null);
|
||||
}
|
||||
else if (pi.PropertyType == typeof(double))
|
||||
{
|
||||
pi.SetValue(entity, double.Parse(value.ToString()), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
pi.SetValue(entity, value, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
lst.Add(entity);
|
||||
}
|
||||
return lst;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Management;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取硬件SN
|
||||
/// </summary>
|
||||
internal class HardwareSN
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取cpuid
|
||||
/// </summary>
|
||||
public static string GetCPUSerialNumber()
|
||||
{
|
||||
try
|
||||
{
|
||||
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
|
||||
string cpuSerialNumber = "";
|
||||
foreach (ManagementObject mo in searcher.Get())
|
||||
{
|
||||
cpuSerialNumber = mo["ProcessorId"].ToString().Trim();
|
||||
break;
|
||||
}
|
||||
return cpuSerialNumber;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取主板id
|
||||
/// </summary>
|
||||
public static string GetBIOSSerialNumber()
|
||||
{
|
||||
try
|
||||
{
|
||||
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");
|
||||
string biosSerialNumber = "";
|
||||
foreach (ManagementObject mo in searcher.Get())
|
||||
{
|
||||
biosSerialNumber = mo.GetPropertyValue("SerialNumber").ToString().Trim();
|
||||
break;
|
||||
}
|
||||
return biosSerialNumber;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取硬盘id
|
||||
/// </summary>
|
||||
public static string GetHardDiskSerialNumber()
|
||||
{
|
||||
try
|
||||
{
|
||||
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
|
||||
string hardDiskSerialNumber = "";
|
||||
foreach (ManagementObject mo in searcher.Get())
|
||||
{
|
||||
hardDiskSerialNumber = mo["SerialNumber"].ToString().Trim();
|
||||
break;
|
||||
}
|
||||
return hardDiskSerialNumber;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取网卡id
|
||||
/// </summary>
|
||||
public static string GetNetCardMACAddress()
|
||||
{
|
||||
try
|
||||
{
|
||||
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))");
|
||||
string netCardMACAddress = "";
|
||||
foreach (ManagementObject mo in searcher.Get())
|
||||
{
|
||||
netCardMACAddress = mo["MACAddress"].ToString().Trim();
|
||||
break;
|
||||
}
|
||||
return netCardMACAddress;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
internal class IniFile
|
||||
{
|
||||
public class IniFiles
|
||||
{
|
||||
public string path;
|
||||
[DllImport("kernel32")] //返回0表示失败,非0为成功
|
||||
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
|
||||
[DllImport("kernel32")] //返回取得字符串缓冲区的长度
|
||||
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
|
||||
/// <summary>
|
||||
/// 保存ini文件的路径
|
||||
/// 调用示例:var ini = IniFiles("C:\file.ini");
|
||||
/// </summary>
|
||||
/// <param name="INIPath"></param>
|
||||
public IniFiles(string iniPath)
|
||||
{
|
||||
this.path = iniPath;
|
||||
}
|
||||
/// <summary>
|
||||
/// 写Ini文件
|
||||
/// 调用示例:ini.IniWritevalue("Server","name","localhost");
|
||||
/// </summary>
|
||||
/// <param name="Section">[缓冲区]</param>
|
||||
/// <param name="Key">键</param>
|
||||
/// <param name="value">值</param>
|
||||
public void IniWritevalue(string Section, string Key, string value)
|
||||
{
|
||||
WritePrivateProfileString(Section, Key, value, this.path);
|
||||
}
|
||||
/// <summary>
|
||||
/// 读Ini文件
|
||||
/// 调用示例:ini.IniWritevalue("Server","name");
|
||||
/// </summary>
|
||||
/// <param name="Section">[缓冲区]</param>
|
||||
/// <param name="Key">键</param>
|
||||
/// <returns>值</returns>
|
||||
public string IniReadvalue(string Section, string Key)
|
||||
{
|
||||
StringBuilder temp = new StringBuilder(255);
|
||||
|
||||
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
|
||||
return temp.ToString();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Remoting.Metadata.W3cXsd2001;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
||||
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class Json
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class ProgramSteps_
|
||||
{
|
||||
public string Program { get; set; }
|
||||
public int Step { get; set; }
|
||||
public string StepID { get; set; }
|
||||
public string StepName { get; set; }
|
||||
public string ParameterName { get; set; }
|
||||
public double Parameter1 { get; set; }
|
||||
public double Parameter2 { get; set; }
|
||||
public double Parameter3 { get; set; }
|
||||
public double Parameter4 { get; set; }
|
||||
public double Parameter5 { get; set; }
|
||||
public double Parameter6 { get; set; }
|
||||
public double Parameter7 { get; set; }
|
||||
public double Parameter8 { get; set; }
|
||||
public double Parameter9 { get; set; }
|
||||
public double Parameter10 { get; set; }
|
||||
public string Remark { get; set; }
|
||||
}
|
||||
public class WorkorderSteps_
|
||||
{
|
||||
public string Program { get; set; }
|
||||
public int Step { get; set; }
|
||||
public string StepID { get; set; }
|
||||
public string StepName { get; set; }
|
||||
public string ParameterName { get; set; }
|
||||
public double Parameter1 { get; set; }
|
||||
public double Parameter2 { get; set; }
|
||||
public double Parameter3 { get; set; }
|
||||
public double Parameter4 { get; set; }
|
||||
public double Parameter5 { get; set; }
|
||||
public string Remark { get; set; }
|
||||
}
|
||||
public class WorkOrder_
|
||||
{
|
||||
public string WorkOrder { get; set; }
|
||||
public string ProcessName { get; set; }
|
||||
public DateTime StartTime { get; set; }
|
||||
public DateTime EndTime { get; set; }
|
||||
public DateTime Time { get; set; }
|
||||
public string Remark { get; set; }
|
||||
public string ProcessID { get; set; }
|
||||
public int State { get; set; }
|
||||
public int lock_ { get; set; }
|
||||
}
|
||||
public class RUN_
|
||||
{
|
||||
public string Program { get; set; }
|
||||
public int Step { get; set; }
|
||||
public string StepID { get; set; }
|
||||
public string StepName { get; set; }
|
||||
public string ParameterName { get; set; }
|
||||
public double Parameter1 { get; set; }
|
||||
public double Parameter2 { get; set; }
|
||||
public double Parameter3 { get; set; }
|
||||
public double Parameter4 { get; set; }
|
||||
public double Parameter5 { get; set; }
|
||||
public double Parameter6 { get; set; }
|
||||
public double Parameter7 { get; set; }
|
||||
public double Parameter8 { get; set; }
|
||||
public double Parameter9 { get; set; }
|
||||
public double Parameter10 { get; set; }
|
||||
public string Remark { get; set; }
|
||||
public int Run { get; set; }
|
||||
public string Ryelot { get; set; }
|
||||
}
|
||||
public class DyelotHistory_
|
||||
{
|
||||
public DateTime TIME { get; set;}
|
||||
public string WorkOrder { get; set; }
|
||||
public string Dyelot { get; set; }
|
||||
public int Tank { get; set; }
|
||||
public int Step { get; set; }
|
||||
public int State { get; set; }
|
||||
public int Redye { get; set; }
|
||||
public int Type { get; set; }
|
||||
public string Machine { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Text;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public static class LogDataRead
|
||||
{
|
||||
private const int MaxCount = 1000;
|
||||
private static int Count = 0;
|
||||
private static RichTextBox textControl;
|
||||
private static InlineCollection inlines;
|
||||
|
||||
//设置主控件
|
||||
public static void SetTextControl(RichTextBox _textBox)
|
||||
{
|
||||
textControl = _textBox;
|
||||
Paragraph graph = new Paragraph();
|
||||
inlines = graph.Inlines;
|
||||
textControl.Document.Blocks.Add(graph);
|
||||
}
|
||||
|
||||
//输出黑色消息
|
||||
public static void Info(string format, params object[] args)
|
||||
{
|
||||
AppendText(Brushes.Black, format, args);
|
||||
}
|
||||
|
||||
//输出绿色消息
|
||||
public static void Suc(string format, params object[] args)
|
||||
{
|
||||
AppendText(Brushes.DarkGreen, format, args);
|
||||
}
|
||||
|
||||
//输出黄色消息
|
||||
public static void Warning(string format, params object[] args)
|
||||
{
|
||||
AppendText(Brushes.DarkOrange, format, args);
|
||||
}
|
||||
|
||||
//输出红色消息
|
||||
public static void Error(string format, params object[] args)
|
||||
{
|
||||
AppendText(Brushes.Red, format, args);
|
||||
}
|
||||
|
||||
//清除日志
|
||||
public static void Clear()
|
||||
{
|
||||
Count = 0;
|
||||
inlines.Clear();
|
||||
textControl.ScrollToEnd();
|
||||
}
|
||||
|
||||
private static void AppendText(Brush color, string format, params object[] args)
|
||||
{
|
||||
textControl.BeginChange();
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.Append("[");
|
||||
builder.Append(Count++);
|
||||
builder.Append("] : ");
|
||||
builder.Append(string.Format(format, (object[])args));
|
||||
builder.Append("\n");
|
||||
string str = builder.ToString();
|
||||
inlines.Add(new Run(str) { Foreground = color });
|
||||
if (inlines.Count > MaxCount)
|
||||
{
|
||||
inlines.Remove(inlines.FirstInline);
|
||||
}
|
||||
textControl.ScrollToEnd();
|
||||
textControl.EndChange();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using DyeingComputer.ViewModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using static DyeingComputer.UserClass.SqliteHelper;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class LogGing
|
||||
{
|
||||
private static SQLiteHelper SQLiteHelpers = null; //定义数据库
|
||||
private readonly static string DBAddress = Environment.CurrentDirectory + "\\DataBase\\800COMPUTER.db"; //数据库路径
|
||||
public static bool sqld=false;
|
||||
public static void LogGingDATA(string dat)
|
||||
{
|
||||
string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录
|
||||
string logPath = "" + System.Environment.CurrentDirectory + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//日志文件
|
||||
string Log_time = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]:";
|
||||
|
||||
if (Directory.Exists(logpath))//检查日志路径
|
||||
{
|
||||
if (!File.Exists(logPath))//检查日志文件并写入启动日志
|
||||
{
|
||||
FileStream fs = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
|
||||
StreamWriter wr = new StreamWriter(fs);//创建文件
|
||||
wr.WriteLine(Log_time + dat);
|
||||
wr.Close();
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
FileStream fs = new FileStream(logPath, FileMode.Append, FileAccess.Write);
|
||||
StreamWriter wr = new StreamWriter(fs);//创建文件
|
||||
wr.WriteLine(Log_time + dat);
|
||||
wr.Close();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
|
||||
directoryInfo.Create();//创建日志路径
|
||||
}
|
||||
}
|
||||
public static void LogSQLDATA(string NAME, string api, string dat)
|
||||
{
|
||||
if (!sqld)
|
||||
{
|
||||
sqld = true;
|
||||
SQLiteHelpers = new SQLiteHelper(DBAddress); //数据库连接路径
|
||||
string Log_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
Dictionary<string, object> logsql = new Dictionary<string, object>();
|
||||
// 添加元素
|
||||
logsql.Add("NAME", NAME);
|
||||
logsql.Add("API", api);
|
||||
logsql.Add("MESSAGE", dat);
|
||||
logsql.Add("TIME", Log_time);
|
||||
SQLiteHelpers.Open(); //打开数据库
|
||||
SQLiteHelpers.InsertData("SERVER", logsql);//行插入
|
||||
SQLiteHelpers.Close(); //关闭连接
|
||||
sqld = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// MD5加密
|
||||
/// </summary>
|
||||
internal class MD5check
|
||||
{
|
||||
/// <summary>
|
||||
/// 16位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt16(string password)
|
||||
{
|
||||
var md5 = new MD5CryptoServiceProvider();
|
||||
string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
|
||||
t2 = t2.Replace("-", "");
|
||||
return t2;
|
||||
}
|
||||
/// <summary>
|
||||
/// 32位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt32(string password)
|
||||
{
|
||||
string cl = password;
|
||||
string pwd = "";
|
||||
MD5 md5 = MD5.Create(); //实例化一个md5对像
|
||||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
|
||||
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
|
||||
for (int i = 0; i < s.Length; i++)
|
||||
{
|
||||
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
|
||||
pwd = pwd + s[i].ToString("X");
|
||||
}
|
||||
return pwd;
|
||||
}
|
||||
/// <summary>
|
||||
/// 64位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt64(string password)
|
||||
{
|
||||
string cl = password;
|
||||
//string pwd = "";
|
||||
MD5 md5 = MD5.Create(); //实例化一个md5对像
|
||||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
|
||||
return Convert.ToBase64String(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using NetFwTypeLib;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class NetFwManger
|
||||
{
|
||||
private static string GetName(int port, string protocol)
|
||||
{
|
||||
return "800-port-" + protocol + "-" + port;
|
||||
}
|
||||
|
||||
public static void AllowPort(int port, string protocol)
|
||||
{
|
||||
|
||||
DelPort(port, protocol);
|
||||
//创建一个INetFwRule对象
|
||||
Type type = Type.GetTypeFromProgID("HNetCfg.FwRule");
|
||||
INetFwRule rule = (INetFwRule)Activator.CreateInstance(type);
|
||||
|
||||
//设置规则的属性
|
||||
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; //允许连接
|
||||
rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; //入站规则
|
||||
rule.Enabled = true; //启用规则
|
||||
rule.InterfaceTypes = "All"; //适用于所有网络接口
|
||||
rule.Name = GetName(port, protocol); //规则名称
|
||||
if (protocol.ToLower() == "tcp")
|
||||
{
|
||||
rule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; //TCP协议
|
||||
}
|
||||
else
|
||||
{
|
||||
rule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; //UDP协议
|
||||
}
|
||||
|
||||
rule.LocalPorts = "" + port; //本地端口号
|
||||
|
||||
//获取FirewallPolicy对象
|
||||
Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
|
||||
INetFwPolicy2 policy = (INetFwPolicy2)Activator.CreateInstance(policyType);
|
||||
|
||||
//将规则添加到防火墙策略中
|
||||
policy.Rules.Add(rule);
|
||||
}
|
||||
|
||||
public static void DelPort(int port, string protocol)
|
||||
{
|
||||
//获取FirewallPolicy对象
|
||||
Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
|
||||
INetFwPolicy2 policy = (INetFwPolicy2)Activator.CreateInstance(policyType);
|
||||
|
||||
//获取现有的规则集合
|
||||
INetFwRules rules = policy.Rules;
|
||||
|
||||
//查找名称的规则并删除它
|
||||
foreach (INetFwRule rule in rules)
|
||||
{
|
||||
if (rule.Name == GetName(port, protocol))
|
||||
{
|
||||
rules.Remove(rule.Name);
|
||||
Console.WriteLine(@"Firewall rule deleted successfully.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// DataGrid中只能输入数字的列
|
||||
/// </summary>
|
||||
/// local:DataGridNumericColumn Binding = "{Binding NumericProperty}"
|
||||
///
|
||||
public class NumericTextColumn : DataGridTextColumn
|
||||
{
|
||||
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
|
||||
{
|
||||
var edit = editingElement as TextBox;
|
||||
edit.PreviewTextInput += Edit_PreviewTextInput;
|
||||
DataObject.AddPastingHandler(edit, OnPaste);
|
||||
//限制输入法切换,可避免中文输入添加到列中
|
||||
InputMethod.SetIsInputMethodEnabled(edit, false);
|
||||
return base.PrepareCellForEdit(editingElement, editingEventArgs);
|
||||
}
|
||||
|
||||
private void OnPaste(object sender, DataObjectPastingEventArgs e)
|
||||
{
|
||||
var data = e.SourceDataObject.GetData(DataFormats.Text);
|
||||
if (!IsDataValid(data)) e.CancelCommand();
|
||||
}
|
||||
|
||||
private void Edit_PreviewTextInput(object sender, TextCompositionEventArgs e)
|
||||
{
|
||||
e.Handled = !IsDataValid(e.Text);
|
||||
}
|
||||
|
||||
bool IsDataValid(object data)
|
||||
{
|
||||
try
|
||||
{
|
||||
Convert.ToInt32(data);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class PID
|
||||
{
|
||||
private double Ts; // Sample period in seconds
|
||||
private double K; // Rollup parameter
|
||||
private double b0, b1, b2; // Rollup parameters
|
||||
private double a0, a1, a2; // Rollup parameters
|
||||
private double y0 = 0; // Current output
|
||||
private double y1 = 0; // Output one iteration old
|
||||
private double y2 = 0; // Output two iterations old
|
||||
private double e0 = 0; // Current error
|
||||
private double e1 = 0; // Error one iteration old
|
||||
private double e2 = 0; // Error two iterations old
|
||||
|
||||
#region 构造函数
|
||||
/// <summary>
|
||||
/// PID构造器
|
||||
/// </summary>
|
||||
/// <param name="Kp">比例增益</param>
|
||||
/// <param name="Ki">积分增益</param>
|
||||
/// <param name="Kd">微分增益</param>
|
||||
/// <param name="N">微分滤波系数</param>
|
||||
/// <param name="OutputUpperLimit">控制器输出上限</param>
|
||||
/// <param name="OutputLowerLimit">控制器输出下限</param>
|
||||
public PID(double Kp, double Ki, double Kd, double N, double OutputUpperLimit, double OutputLowerLimit)
|
||||
{
|
||||
this.Kp = Kp;
|
||||
this.Ki = Ki;
|
||||
this.Kd = Kd;
|
||||
this.N = N;
|
||||
this.OutputUpperLimit = OutputUpperLimit;
|
||||
this.OutputLowerLimit = OutputLowerLimit;
|
||||
}
|
||||
|
||||
public PID()
|
||||
{
|
||||
this.Kp = 0.5;
|
||||
this.Ki = 0.1;
|
||||
this.Kd = 0.2;
|
||||
this.N = 1;
|
||||
this.OutputUpperLimit = 65530;
|
||||
this.OutputLowerLimit = 0;
|
||||
}
|
||||
#endregion
|
||||
/// <summary>
|
||||
/// PID迭代器,在每个采样周期调用此函数以获取当前控制器输出。
|
||||
/// 设定点和过程值应使用相同的单位。
|
||||
/// </summary>
|
||||
/// <param name="setPoint">设定目标值</param>
|
||||
/// <param name="processValue">当前实际值</param>
|
||||
/// <param name="ts">自上次迭代以来的时间跨度,对第一次调用使用默认采样周期</param>
|
||||
/// <returns>Current Controller Output</returns>
|
||||
public double PID_iterate(double setPoint, double processValue, TimeSpan ts)
|
||||
{
|
||||
// Ensure the timespan is not too small or zero.
|
||||
Ts = (ts.TotalSeconds >= TsMin) ? ts.TotalSeconds : TsMin;
|
||||
|
||||
// Calculate rollup parameters
|
||||
K = 2 / Ts;
|
||||
b0 = Math.Pow(K, 2) * Kp + K * Ki + Ki * N + K * Kp * N + Math.Pow(K, 2) * Kd * N;
|
||||
b1 = 2 * Ki * N - 2 * Math.Pow(K, 2) * Kp - 2 * Math.Pow(K, 2) * Kd * N;
|
||||
b2 = Math.Pow(K, 2) * Kp - K * Ki + Ki * N - K * Kp * N + Math.Pow(K, 2) * Kd * N;
|
||||
a0 = Math.Pow(K, 2) + N * K;
|
||||
a1 = -2 * Math.Pow(K, 2);
|
||||
a2 = Math.Pow(K, 2) - K * N;
|
||||
|
||||
// Age errors and output history
|
||||
e2 = e1; // Age errors one iteration
|
||||
e1 = e0; // Age errors one iteration
|
||||
e0 = setPoint - processValue; // Compute new error
|
||||
y2 = y1; // Age outputs one iteration
|
||||
y1 = y0; // Age outputs one iteration
|
||||
y0 = -a1 / a0 * y1 - a2 / a0 * y2 + b0 / a0 * e0 + b1 / a0 * e1 + b2 / a0 * e2; // Calculate current output
|
||||
|
||||
// Clamp output if needed
|
||||
if (y0 > OutputUpperLimit)
|
||||
{
|
||||
y0 = OutputUpperLimit;
|
||||
}
|
||||
else if (y0 < OutputLowerLimit)
|
||||
{
|
||||
y0 = OutputLowerLimit;
|
||||
}
|
||||
|
||||
return y0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重置控制器历史记录,有效重置控制器。
|
||||
/// </summary>
|
||||
public void ResetController()
|
||||
{
|
||||
e2 = 0;
|
||||
e1 = 0;
|
||||
e0 = 0;
|
||||
y2 = 0;
|
||||
y1 = 0;
|
||||
y0 = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 比例增益,如果此参数发生剧烈变化,请考虑重置控制器。
|
||||
/// </summary>
|
||||
public double Kp { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 积分增益,如果此参数发生剧烈变化,请考虑重置控制器。
|
||||
/// </summary>
|
||||
public double Ki { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 微分增益,如果此参数发生剧烈变化,请考虑重置控制器。
|
||||
/// </summary>
|
||||
public double Kd { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///微分滤波系数。
|
||||
/// N越小,过滤效果越好
|
||||
/// N越大,过滤效果越差
|
||||
/// 如果此参数发生剧烈变化,请考虑重置控制器。
|
||||
/// </summary>
|
||||
public double N { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 避免除以零的最小允许采样周期!
|
||||
/// Ts值可能会在第一次迭代时被错误地设置为过低的值或零。
|
||||
/// TsMin默认设置为1毫秒。
|
||||
/// </summary>
|
||||
public double TsMin { get; set; } = 0.001;
|
||||
|
||||
/// <summary>
|
||||
/// 控制器的输出上限。
|
||||
/// 是一个比输出下限大的数值。
|
||||
/// </summary>
|
||||
public double OutputUpperLimit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 控制器的输出下限。
|
||||
/// 是一个比输出上限小的数值。
|
||||
/// </summary>
|
||||
public double OutputLowerLimit { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
internal class PressKey
|
||||
{
|
||||
/// <summary>
|
||||
/// 键盘模拟
|
||||
/// </summary>
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
|
||||
public static void PressKeys(Keys key, bool up)
|
||||
{
|
||||
const int KEYEVENTF_EXTENDEDKEY = 0x1;
|
||||
const int KEYEVENTF_KEYUP = 0x2;
|
||||
if (up)
|
||||
{
|
||||
keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
|
||||
}
|
||||
else
|
||||
{
|
||||
keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using DyeingComputer.View;
|
||||
using DyeingComputer.ViewModel;
|
||||
using ScottPlot.Colormaps;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Documents;
|
||||
using System.Xml.Linq;
|
||||
using static DyeingComputer.UserClass.SqliteHelper;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class SQLDATA
|
||||
{
|
||||
private static SQLiteHelper SQLiteHelpers = null; //定义数据库
|
||||
private readonly static string DBAddress = Environment.CurrentDirectory + "\\DataBase\\800COMPUTER.db"; //数据库路径
|
||||
//WorkOrder表检查写入
|
||||
public static bool WorkOrder(string WorkOrder, string ProcessName,string StartTime, string EndTime, string Time, string Remark,string lock_,string state,string ProcessID)
|
||||
{
|
||||
SQLiteHelpers = new SQLiteHelper(DBAddress); //数据库连接路径
|
||||
SQLiteHelpers.Open(); //打开数据库
|
||||
object i = SQLiteHelpers.ExecuteScalar("select * from WorkOrder where WorkOrder = "+ WorkOrder,null);
|
||||
if (i!=null)
|
||||
{
|
||||
SQLiteHelpers.Close();
|
||||
return false;
|
||||
}
|
||||
Dictionary<string, object> WorkOrder_new = new Dictionary<string, object>();//缓存函数
|
||||
WorkOrder_new.Add("WorkOrder", WorkOrder);
|
||||
WorkOrder_new.Add("ProcessName", ProcessName);
|
||||
WorkOrder_new.Add("StartTime", StartTime);
|
||||
WorkOrder_new.Add("EndTime", EndTime);
|
||||
WorkOrder_new.Add("Time", Time);
|
||||
WorkOrder_new.Add("Remark", Remark);
|
||||
WorkOrder_new.Add("lock", Convert.ToInt16(lock_));
|
||||
WorkOrder_new.Add("state", Convert.ToInt16(state));
|
||||
WorkOrder_new.Add("ProcessID", ProcessID);
|
||||
SQLiteHelpers.InsertData("WorkOrder", WorkOrder_new);
|
||||
SQLiteHelpers.Close();
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool WorkOderStep(DataTable WorkOrderStep_)
|
||||
{
|
||||
SQLiteHelpers = new SQLiteHelper(DBAddress); //数据库连接路径
|
||||
SQLiteHelpers.Open(); //打开数据库
|
||||
DataTable data_t = WorkOrderStep_.Clone();
|
||||
int a = WorkOrderStep_.Rows.Count;
|
||||
if (a < 1)
|
||||
{
|
||||
SQLiteHelpers.Close();
|
||||
return false;
|
||||
}
|
||||
string Program = WorkOrderStep_.Rows[0][0].ToString();
|
||||
object n = SQLiteHelpers.ExecuteScalar("select * from WorkorderSteps where Program = " + Program, null);
|
||||
if (n != null)//如id存在着返回错误状态
|
||||
{
|
||||
SQLiteHelpers.Close();
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < a; i++)
|
||||
{
|
||||
data_t.Clear();//清空
|
||||
DataRow dr = data_t.NewRow();
|
||||
dr.ItemArray = WorkOrderStep_.Rows[i].ItemArray;
|
||||
data_t.Rows.InsertAt(dr, 0);
|
||||
SQLiteHelpers.InsertData("WorkorderSteps", SQLiteHelpers.DataTableToDictionary(data_t));//行插入
|
||||
}
|
||||
SQLiteHelpers.Close(); //关闭连接
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void TechnologicalProcess_START(string workName)
|
||||
{
|
||||
SQLiteHelpers = new SQLiteHelper(DBAddress); //数据库连接路径
|
||||
SQLiteHelpers.Open(); //打开数据库
|
||||
int r = 0;
|
||||
string sql_script = "select * from WorkorderSteps where ProgramID = '" + workName + "'";
|
||||
if (TechnologicalProcessView.sql != null) TechnologicalProcessView.sql.Clear(); //清空缓存
|
||||
TechnologicalProcessView.sql = SQLiteHelpers.ExecuteDataSet(sql_script, null); //读取表写入缓存
|
||||
TechnologicalProcessView.Program_Name = SQLiteHelpers.ExecuteScalar("select ProgramName from Workorder where ProgramID = '" + workName + "'", null).ToString();
|
||||
|
||||
SQLiteHelpers.Delete("RUN", null, null); //删除run信息
|
||||
DataTable data_t = new DataTable();
|
||||
data_t = TechnologicalProcessView.sql.Tables[0].Clone();
|
||||
data_t.Columns.Add("DYELOT", typeof(string)); //添加列
|
||||
int a = TechnologicalProcessView.sql.Tables[0].Rows.Count;
|
||||
for (int i = 0; i < a; i++)
|
||||
{
|
||||
data_t.Clear();//清空
|
||||
DataRow dt = TechnologicalProcessView.sql.Tables[0].Rows[i];//行转
|
||||
DataRow dr = data_t.NewRow();
|
||||
dr.ItemArray = dt.ItemArray;
|
||||
dr.BeginEdit(); //添加订单号
|
||||
dr["DYELOT"] = MainWindowViewModel.WorkNumder;
|
||||
dr.EndEdit();
|
||||
data_t.Rows.InsertAt(dr, 0); //行转换
|
||||
|
||||
r = SQLiteHelpers.InsertData("RUN", SQLiteHelpers.DataTableToDictionary(data_t));//行插入
|
||||
}
|
||||
//数据插入
|
||||
MainWindowViewModel.WorkNumder = SQLiteHelpers.ExecuteDataSet("select WorkOrder from Workorder where ProgramID = '" + workName + "'", null);;
|
||||
TechnologicalProcessView.workName = workName;
|
||||
MainWindowViewModel.SYS_REDYE = 0;
|
||||
MainWindowViewModel.ViewID = 1;
|
||||
|
||||
SQLiteHelpers.Close(); //关闭连接
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,686 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Data.Common;
|
||||
using System.Windows.Media.Animation;
|
||||
using System.Data.SQLite;
|
||||
using System.Windows.Shapes;
|
||||
using System.Drawing;
|
||||
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class SqliteHelper
|
||||
{
|
||||
|
||||
public class SQLiteHelper
|
||||
{
|
||||
#region 字段
|
||||
|
||||
/// <summary>
|
||||
/// 事务的基类
|
||||
/// </summary>
|
||||
private DbTransaction DBtrans;
|
||||
/// <summary>
|
||||
/// 使用静态变量字典解决多线程实例本类,实现一个数据库对应一个clslock
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, ClsLock> RWL = new Dictionary<string, ClsLock>();
|
||||
/// <summary>
|
||||
/// 数据库地址
|
||||
/// </summary>
|
||||
private readonly string mdataFile;
|
||||
/// <summary>
|
||||
/// 数据库密码
|
||||
/// </summary>
|
||||
private readonly string mPassWord;
|
||||
private readonly string LockName = null;
|
||||
/// <summary>
|
||||
/// 数据库连接定义
|
||||
/// </summary>
|
||||
private SQLiteConnection mConn;
|
||||
|
||||
#endregion
|
||||
|
||||
#region 构造函数
|
||||
|
||||
/// <summary>
|
||||
/// 根据数据库地址初始化
|
||||
/// </summary>
|
||||
/// <param name="dataFile">数据库地址</param>
|
||||
public SQLiteHelper(string dataFile)
|
||||
{
|
||||
this.mdataFile = dataFile ?? throw new ArgumentNullException("dataFile=null");
|
||||
//this.mdataFile = AppDomain.CurrentDomain.BaseDirectory + dataFile;
|
||||
this.mdataFile = dataFile;
|
||||
if (!RWL.ContainsKey(dataFile))
|
||||
{
|
||||
LockName = dataFile;
|
||||
RWL.Add(dataFile, new ClsLock());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用密码打开数据库
|
||||
/// </summary>
|
||||
/// <param name="dataFile">数据库地址</param>
|
||||
/// <param name="PassWord">数据库密码</param>
|
||||
public SQLiteHelper(string dataFile, string PassWord)
|
||||
{
|
||||
this.mdataFile = dataFile ?? throw new ArgumentNullException("dataFile is null");
|
||||
this.mPassWord = PassWord ?? throw new ArgumentNullException("PassWord is null");
|
||||
//this.mdataFile = AppDomain.CurrentDomain.BaseDirectory + dataFile;
|
||||
this.mdataFile = dataFile;
|
||||
if (!RWL.ContainsKey(dataFile))
|
||||
{
|
||||
LockName = dataFile;
|
||||
RWL.Add(dataFile, new ClsLock());
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 打开/关闭 数据库
|
||||
|
||||
/// <summary>
|
||||
/// 打开 SQLiteManager 使用的数据库连接
|
||||
/// </summary>
|
||||
public void Open()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mPassWord))
|
||||
{
|
||||
mConn = OpenConnection(this.mdataFile);
|
||||
}
|
||||
else
|
||||
{
|
||||
mConn = OpenConnection(this.mdataFile, mPassWord);
|
||||
}
|
||||
Console.WriteLine("The database was opened successfully");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭连接
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
if (this.mConn != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.mConn.Close();
|
||||
if (RWL.ContainsKey(LockName))
|
||||
{
|
||||
RWL.Remove(LockName);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.WriteLine("Shutdown failed");
|
||||
}
|
||||
}
|
||||
Console.WriteLine("The database was shut down successfully");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 事务
|
||||
|
||||
/// <summary>
|
||||
/// 开始事务
|
||||
/// </summary>
|
||||
public void BeginTrain()
|
||||
{
|
||||
EnsureConnection();
|
||||
DBtrans = mConn.BeginTransaction();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 提交事务
|
||||
/// </summary>
|
||||
public void DBCommit()
|
||||
{
|
||||
try
|
||||
{
|
||||
DBtrans.Commit();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
DBtrans.Rollback();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 工具
|
||||
|
||||
/// <summary>
|
||||
/// 打开一个SQLite数据库文件,如果文件不存在,则创建(无密码)
|
||||
/// </summary>
|
||||
/// <param name="dataFile"></param>
|
||||
/// <returns>SQLiteConnection 类</returns>
|
||||
private SQLiteConnection OpenConnection(string dataFile)
|
||||
{
|
||||
if (dataFile == null)
|
||||
{
|
||||
throw new ArgumentNullException("dataFiledataFile=null");
|
||||
}
|
||||
if (!File.Exists(dataFile))
|
||||
{
|
||||
SQLiteConnection.CreateFile(dataFile);
|
||||
}
|
||||
SQLiteConnection conn = new SQLiteConnection();
|
||||
SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder
|
||||
{
|
||||
DataSource = dataFile
|
||||
};
|
||||
conn.ConnectionString = conStr.ToString();
|
||||
conn.Open();
|
||||
return conn;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 打开一个SQLite数据库文件,如果文件不存在,则创建(有密码)
|
||||
/// </summary>
|
||||
/// <param name="dataFile"></param>
|
||||
/// <param name="Password"></param>
|
||||
/// <returns>SQLiteConnection 类</returns>
|
||||
private SQLiteConnection OpenConnection(string dataFile, string Password)
|
||||
{
|
||||
if (dataFile == null)
|
||||
{
|
||||
throw new ArgumentNullException("dataFile=null");
|
||||
}
|
||||
if (!File.Exists(Convert.ToString(dataFile)))
|
||||
{
|
||||
SQLiteConnection.CreateFile(dataFile);
|
||||
}
|
||||
try
|
||||
{
|
||||
SQLiteConnection conn = new SQLiteConnection();
|
||||
SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder
|
||||
{
|
||||
DataSource = dataFile,
|
||||
Password = Password
|
||||
};
|
||||
conn.ConnectionString = conStr.ToString();
|
||||
conn.Open();
|
||||
return conn;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取 或 设置 SQLiteManager 使用的数据库连接
|
||||
/// </summary>
|
||||
public SQLiteConnection Connection
|
||||
{
|
||||
get
|
||||
{
|
||||
return mConn;
|
||||
}
|
||||
private set
|
||||
{
|
||||
mConn = value ?? throw new ArgumentNullException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 确保数据库是连接状态
|
||||
/// </summary>
|
||||
/// <exception cref="Exception"></exception>
|
||||
protected void EnsureConnection()
|
||||
{
|
||||
if (this.mConn == null)
|
||||
{
|
||||
throw new Exception("SQLiteManager.Connection=null");
|
||||
}
|
||||
if (mConn.State != ConnectionState.Open)
|
||||
{
|
||||
mConn.Open();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取数据库文件的路径
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string GetDataFile()
|
||||
{
|
||||
return this.mdataFile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断表 table 是否存在
|
||||
/// </summary>
|
||||
/// <param name="table"></param>
|
||||
/// <returns>存在返回true,否则返回false</returns>
|
||||
public bool TableExists(string table)
|
||||
{
|
||||
if (table == null)
|
||||
{
|
||||
throw new ArgumentNullException("table=null");
|
||||
}
|
||||
EnsureConnection();
|
||||
SQLiteDataReader reader = ExecuteReader("SELECT count(*) as c FROM sqlite_master WHERE type='table' AND name=@tableName ", new SQLiteParameter[] { new SQLiteParameter("tableName", table) });
|
||||
if (reader == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
reader.Read();
|
||||
int c = reader.GetInt32(0);
|
||||
reader.Close();
|
||||
reader.Dispose();
|
||||
//return false;
|
||||
return c == 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VACUUM 命令(通过复制主数据库中的内容到一个临时数据库文件,然后清空主数据库,并从副本中重新载入原始的数据库文件)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public bool Vacuum()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (SQLiteCommand Command = new SQLiteCommand("VACUUM", Connection))
|
||||
{
|
||||
Command.ExecuteNonQuery();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (System.Data.SQLite.SQLiteException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 执行SQL
|
||||
|
||||
/// <summary>
|
||||
/// 执行SQL, 并返回 SQLiteDataReader 对象结果
|
||||
/// </summary>
|
||||
/// <param name="sql"></param>
|
||||
/// <param name="paramArr">null 表示无参数</param>
|
||||
/// <returns></returns>
|
||||
public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] paramArr)
|
||||
{
|
||||
if (sql == null)
|
||||
{
|
||||
throw new ArgumentNullException("sql=null");
|
||||
}
|
||||
EnsureConnection();
|
||||
using (RWL[LockName].Read())
|
||||
{
|
||||
using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
try
|
||||
{
|
||||
SQLiteDataReader reader = cmd.ExecuteReader();
|
||||
cmd.Parameters.Clear();
|
||||
return reader;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行查询,并返回dataset对象
|
||||
/// </summary>
|
||||
/// <param name="sql">SQL查询语句</param>
|
||||
/// <param name="paramArr">参数数组</param>
|
||||
/// <returns></returns>
|
||||
public DataSet ExecuteDataSet(string sql, SQLiteParameter[] paramArr)
|
||||
{
|
||||
if (sql == null)
|
||||
{
|
||||
throw new ArgumentNullException("sql=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
using (RWL[LockName].Read())
|
||||
{
|
||||
using (SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
try
|
||||
{
|
||||
SQLiteDataAdapter da = new SQLiteDataAdapter();
|
||||
DataSet ds = new DataSet();
|
||||
da.SelectCommand = cmd;
|
||||
da.Fill(ds);
|
||||
cmd.Parameters.Clear();
|
||||
da.Dispose();
|
||||
return ds;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行SQL查询,并返回dataset对象。
|
||||
/// </summary>
|
||||
/// <param name="strTable">映射源表的名称</param>
|
||||
/// <param name="sql">SQL语句</param>
|
||||
/// <param name="paramArr">SQL参数数组</param>
|
||||
/// <returns></returns>
|
||||
public DataSet ExecuteDataSet(string strTable, string sql, SQLiteParameter[] paramArr)
|
||||
{
|
||||
if (sql == null)
|
||||
{
|
||||
throw new ArgumentNullException("sql=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
using (RWL[LockName].Read())
|
||||
{
|
||||
using (SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
try
|
||||
{
|
||||
SQLiteDataAdapter da = new SQLiteDataAdapter();
|
||||
DataSet ds = new DataSet();
|
||||
da.SelectCommand = cmd;
|
||||
da.Fill(ds, strTable);
|
||||
cmd.Parameters.Clear();
|
||||
da.Dispose();
|
||||
return ds;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行SQL,返回受影响的行数,可用于执行表创建语句,paramArr == null 表示无参数
|
||||
/// </summary>
|
||||
/// <param name="sql"></param>
|
||||
/// <returns></returns>
|
||||
public int ExecuteNonQuery(string sql, SQLiteParameter[] paramArr)
|
||||
{
|
||||
if (sql == null)
|
||||
{
|
||||
throw new ArgumentNullException("sql=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
using (RWL[LockName].Read())
|
||||
{
|
||||
try
|
||||
{
|
||||
using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
foreach (SQLiteParameter p in paramArr)
|
||||
{
|
||||
cmd.Parameters.Add(p);
|
||||
}
|
||||
}
|
||||
int c = cmd.ExecuteNonQuery();
|
||||
cmd.Parameters.Clear();
|
||||
return c;
|
||||
}
|
||||
}
|
||||
catch (SQLiteException)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行SQL,返回结果集第一行,如果结果集为空,那么返回空 List(List.Count=0),
|
||||
/// rowWrapper = null 时,使用 WrapRowToDictionary
|
||||
/// </summary>
|
||||
/// <param name="sql"></param>
|
||||
/// <param name="paramArr"></param>
|
||||
/// <returns></returns>
|
||||
public object ExecuteScalar(string sql, SQLiteParameter[] paramArr)
|
||||
{
|
||||
if (sql == null)
|
||||
{
|
||||
throw new ArgumentNullException("sql=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
using (RWL[LockName].Read())
|
||||
{
|
||||
using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
try
|
||||
{
|
||||
object reader = cmd.ExecuteScalar();
|
||||
cmd.Parameters.Clear();
|
||||
cmd.Dispose();
|
||||
return reader;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询一行记录,无结果时返回 null,conditionCol = null 时将忽略条件,直接执行 select * from table
|
||||
/// </summary>
|
||||
/// <param name="table">表名</param>
|
||||
/// <param name="conditionCol"></param>
|
||||
/// <param name="conditionVal"></param>
|
||||
/// <returns></returns>
|
||||
public object QueryOne(string table, string conditionCol, object conditionVal)
|
||||
{
|
||||
if (table == null)
|
||||
{
|
||||
throw new ArgumentNullException("table=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
string sql = "select * from " + table;
|
||||
if (conditionCol != null)
|
||||
{
|
||||
sql += " where " + conditionCol + "=@" + conditionCol;
|
||||
}
|
||||
object result = ExecuteScalar(sql, new SQLiteParameter[] { new SQLiteParameter(conditionCol, conditionVal) });
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 增 删 改
|
||||
|
||||
/// <summary>
|
||||
/// 执行 insert into 语句
|
||||
/// </summary>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public int InsertData(string table, Dictionary<string, object> entity)
|
||||
{
|
||||
if (table == null)
|
||||
{
|
||||
throw new ArgumentNullException("table=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
string sql = BuildInsert(table, entity);
|
||||
return this.ExecuteNonQuery(sql, BuildParamArray(entity));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行 update 语句,注意:如果 where = null,那么 whereParams 也为 null,
|
||||
/// </summary>
|
||||
/// <param name="table">表名</param>
|
||||
/// <param name="entity">要修改的列名和列名的值</param>
|
||||
/// <param name="where">查找符合条件的列</param>
|
||||
/// <param name="whereParams">where条件中参数的值</param>
|
||||
/// <returns></returns>
|
||||
public int Update(string table, Dictionary<string, object> entity, string where, SQLiteParameter[] whereParams)
|
||||
{
|
||||
if (table == null)
|
||||
{
|
||||
throw new ArgumentNullException("table=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
string sql = BuildUpdate(table, entity);
|
||||
SQLiteParameter[] parameter = BuildParamArray(entity);
|
||||
if (where != null)
|
||||
{
|
||||
sql += " where " + where;
|
||||
if (whereParams != null)
|
||||
{
|
||||
SQLiteParameter[] newArr = new SQLiteParameter[(parameter.Length + whereParams.Length)];
|
||||
Array.Copy(parameter, newArr, parameter.Length);
|
||||
Array.Copy(whereParams, 0, newArr, parameter.Length, whereParams.Length);
|
||||
parameter = newArr;
|
||||
}
|
||||
}
|
||||
return this.ExecuteNonQuery(sql, parameter);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行 delete from table 语句,where不必包含'where'关键字,where = null 时将忽略 whereParams
|
||||
/// </summary>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="where"></param>
|
||||
/// <param name="whereParams"></param>
|
||||
/// <returns></returns>
|
||||
public int Delete(string table, string where, SQLiteParameter[] whereParams)
|
||||
{
|
||||
if (table == null)
|
||||
{
|
||||
throw new ArgumentNullException("table=null");
|
||||
}
|
||||
this.EnsureConnection();
|
||||
string sql = "delete from " + table + " ";
|
||||
if (where != null)
|
||||
{
|
||||
sql += "where " + where;
|
||||
}
|
||||
return ExecuteNonQuery(sql, whereParams);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 Dictionary 类型数据 转换为 SQLiteParameter[] 类型
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
private SQLiteParameter[] BuildParamArray(Dictionary<string, object> entity)
|
||||
{
|
||||
List<SQLiteParameter> list = new List<SQLiteParameter>();
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
list.Add(new SQLiteParameter(key, entity[key]));
|
||||
}
|
||||
if (list.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 Dictionary 类型数据 转换为 插入数据 的 SQL语句
|
||||
/// </summary>
|
||||
/// <param name="table">表名</param>
|
||||
/// <param name="entity">字典</param>
|
||||
/// <returns></returns>
|
||||
private string BuildInsert(string table, Dictionary<string, object> entity)
|
||||
{
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.Append("insert into ").Append(table);
|
||||
buf.Append(" (");
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
buf.Append(key).Append(",");
|
||||
}
|
||||
buf.Remove(buf.Length - 1, 1); // 移除最后一个,
|
||||
buf.Append(") ");
|
||||
buf.Append("values(");
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
buf.Append("@").Append(key).Append(","); // 创建一个参数
|
||||
}
|
||||
buf.Remove(buf.Length - 1, 1);
|
||||
buf.Append(") ");
|
||||
|
||||
return buf.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 Dictionary 类型数据 转换为 修改数据 的 SQL语句
|
||||
/// </summary>
|
||||
/// <param name="table">表名</param>
|
||||
/// <param name="entity">字典</param>
|
||||
/// <returns></returns>
|
||||
private string BuildUpdate(string table, Dictionary<string, object> entity)
|
||||
{
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.Append("update ").Append(table).Append(" set ");
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
buf.Append(key).Append("=").Append("@").Append(key).Append(",");
|
||||
}
|
||||
buf.Remove(buf.Length - 1, 1);
|
||||
buf.Append(" ");
|
||||
return buf.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 DataTable 转换为 Dictionary 类型数据
|
||||
/// </summary>
|
||||
public Dictionary<string, object> DataTableToDictionary(DataTable dataTable)
|
||||
{
|
||||
Dictionary<string, object> result = new Dictionary<string, object>();
|
||||
if (dataTable != null)
|
||||
{
|
||||
foreach (DataRow dataRow in dataTable.Rows)
|
||||
{
|
||||
foreach (DataColumn dataColumn in dataTable.Columns)
|
||||
{
|
||||
result.Add(dataColumn.ColumnName, dataRow[dataColumn].ToString());
|
||||
//result = Console.WriteLine(dataRow[dataColumn].ToString());
|
||||
//result.Add(dataColumn.ColumnName, dataRow[dataColumn].ToString())(new RepeatDictionaryComparer());
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
result = null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
/// <summary>
|
||||
/// 字符串转数字
|
||||
/// </summary>
|
||||
internal class StrToInt
|
||||
{
|
||||
/// <summary>
|
||||
/// 十六进制字符串转十进制
|
||||
/// </summary>
|
||||
/// <param name="str">十六进制字符</param>
|
||||
/// <returns></returns>
|
||||
public static int To16Convert10(string str)
|
||||
{
|
||||
int res = 0;
|
||||
try
|
||||
{
|
||||
str = str.Trim().Replace(" ", ""); //移除空字符
|
||||
//方法1
|
||||
res = int.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier);
|
||||
//方法2
|
||||
//int r2 = System.Int32.Parse(str, System.Globalization.NumberStyles.HexNumber);
|
||||
//Console.WriteLine(r2);
|
||||
//方法3
|
||||
//int r3 = Convert.ToInt32(str, 16);
|
||||
//Console.WriteLine(r3);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
res = 0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace DyeingComputer.UserClass
|
||||
{
|
||||
public class get_local_ip_address
|
||||
{
|
||||
public static string getLocalIPAddressWithNetworkInterface(NetworkInterfaceType _type)//获取本机ip并以字符串方式返回
|
||||
{
|
||||
string output = "";
|
||||
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
|
||||
{
|
||||
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
output = ip.Address.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static string IP_Address()
|
||||
{
|
||||
string ip;
|
||||
|
||||
ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ethernet);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Wireless80211);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ppp);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Wwanpp);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.TokenRing);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Fddi);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.GenericModem);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.IPOverAtm);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Tunnel);
|
||||
if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Unknown);
|
||||
|
||||
if (ip == "") ip = "127.0.0.1";
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user