添加项目文件。
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using CsvHelper.Configuration.Attributes;
|
||||
|
||||
namespace JY.Inspection.Common
|
||||
{
|
||||
/// <summary>
|
||||
/// 报警表单数据
|
||||
/// </summary>
|
||||
public class AlarmForm
|
||||
{
|
||||
/// <summary>
|
||||
/// 报警地址
|
||||
/// </summary>
|
||||
[Name("寄存器地址")]
|
||||
public string PLCAdress { get; set; }
|
||||
/// <summary>
|
||||
/// 报警内容
|
||||
/// </summary>
|
||||
[Name("报警信息")]
|
||||
public string AlarmContent { get; set; }
|
||||
/// <summary>
|
||||
/// 报警代码
|
||||
/// </summary>
|
||||
[Name("故障代码")]
|
||||
public string AlarmCode { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection.Common
|
||||
{
|
||||
public static class ByteUtil
|
||||
{
|
||||
public static byte[] ByteReverse(this byte[] Arrbyte)
|
||||
{
|
||||
byte[] ArrByte = Arrbyte.Select((x, i) => new { x, i }).GroupBy(x => x.i / 2).SelectMany(x => new byte[] { x.Last().x, x.First().x }).ToArray();
|
||||
return ArrByte;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using CsvHelper;
|
||||
using JY.Utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
public class CSVHelper<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// 读取CSV文件
|
||||
/// </summary>
|
||||
/// <param name="fileName">csv文件名</param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ReadCSV(string fileName, string strSeparator = "\t")
|
||||
{
|
||||
if (!File.Exists(fileName)) return null;
|
||||
//Nuget获取CsvHelper
|
||||
using (var reader = new StreamReader(fileName))
|
||||
{
|
||||
var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
|
||||
{
|
||||
Mode = CsvMode.Escape,
|
||||
Escape = '\\',
|
||||
Delimiter = strSeparator//设置分隔符号
|
||||
};
|
||||
using (var csv = new CsvReader(reader, cfg))
|
||||
{
|
||||
var list = csv.GetRecords<T>().ToList();
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写入数据到csv文件
|
||||
/// </summary>
|
||||
/// <param name="filePath">所需存储文件夹路径(取系统所设定值,不带日期文件夹)</param>
|
||||
/// <param name="data">数据源</param>
|
||||
/// <param name="flag">1进站,2出站,3智能电表.csv,4预警</param>
|
||||
/// <returns></returns>
|
||||
public static bool WriteCSV(string filePath, List<T> data, int flag)
|
||||
{
|
||||
if (string.IsNullOrEmpty(filePath))
|
||||
{
|
||||
filePath = Application.StartupPath + "\\localData\\" + DateTime.Now.ToString("yyyyMMdd");
|
||||
}
|
||||
else
|
||||
{
|
||||
filePath = filePath + "\\" + DateTime.Now.ToString("yyyyMMdd");
|
||||
}
|
||||
if (!Directory.Exists(filePath))
|
||||
{
|
||||
Directory.CreateDirectory(filePath);
|
||||
}
|
||||
switch (flag)
|
||||
{
|
||||
case 1:
|
||||
filePath = filePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "进站.csv";
|
||||
break;
|
||||
case 2:
|
||||
filePath = filePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "出站.csv";
|
||||
break;
|
||||
case 3:
|
||||
filePath = filePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "智能电表.csv";
|
||||
break;
|
||||
default:
|
||||
filePath = filePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "报警.csv";
|
||||
break;
|
||||
}
|
||||
try
|
||||
{
|
||||
var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
cfg.HasHeaderRecord = false;//是否将第一行作为标题
|
||||
}
|
||||
using (var writer = new StreamWriter(filePath, true, Encoding.GetEncoding("GB2312")))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, cfg))
|
||||
{
|
||||
csv.WriteRecords(data);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Error(ex.ToString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection.Common
|
||||
{
|
||||
public class CollectionUtil
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成ushort List集合
|
||||
/// </summary>
|
||||
/// <param name="Num"></param>
|
||||
/// <returns></returns>
|
||||
public static List<short> GetListUShort(int Num)
|
||||
{
|
||||
List<short> list = new List<short>();
|
||||
for (int i = 0; i < Num; i++)
|
||||
{
|
||||
list.Add(1);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
/// <summary>
|
||||
/// 与客户端的 连接通信类(包含了一个 与客户端 通信的 套接字,和线程)
|
||||
/// </summary>
|
||||
public class ConnectionClient
|
||||
{
|
||||
Socket sokMsg;
|
||||
DGShowMsg dgShowMsg;//负责 向主窗体文本框显示消息的方法委托
|
||||
DGShowMsg dgRemoveConnection;// 负责 从主窗体 中移除 当前连接
|
||||
Thread threadMsg;
|
||||
|
||||
#region 构造函数
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="sokMsg">通信套接字</param>
|
||||
/// <param name="dgShowMsg">向主窗体文本框显示消息的方法委托</param>
|
||||
public ConnectionClient(Socket sokMsg, DGShowMsg dgShowMsg, DGShowMsg dgRemoveConnection)
|
||||
{
|
||||
this.sokMsg = sokMsg;
|
||||
this.dgShowMsg = dgShowMsg;
|
||||
this.dgRemoveConnection = dgRemoveConnection;
|
||||
|
||||
this.threadMsg = new Thread(RecMsg);
|
||||
this.threadMsg.IsBackground = true;
|
||||
this.threadMsg.Start();
|
||||
}
|
||||
#endregion
|
||||
|
||||
bool isRec = true;
|
||||
#region 02负责监听客户端发送来的消息
|
||||
void RecMsg()
|
||||
{
|
||||
while (isRec)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] arrMsg = new byte[1024 * 1024 * 2];
|
||||
//接收 对应 客户端发来的消息
|
||||
int length = sokMsg.Receive(arrMsg);
|
||||
//将接收到的消息数组里真实消息转成字符串
|
||||
string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg, 0, length);
|
||||
//通过委托 显示消息到 窗体的文本框
|
||||
dgShowMsg(strMsg);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
isRec = false;
|
||||
//从主窗体中 移除 下拉框中对应的客户端选择项,同时 移除 集合中对应的 ConnectionClient对象
|
||||
dgRemoveConnection(sokMsg.RemoteEndPoint.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 03向客户端发送消息
|
||||
/// <summary>
|
||||
/// 向客户端发送消息
|
||||
/// </summary>
|
||||
/// <param name="strMsg"></param>
|
||||
public void Send(string strMsg)
|
||||
{
|
||||
byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
|
||||
byte[] arrMsgFinal = new byte[arrMsg.Length + 1];
|
||||
|
||||
arrMsgFinal[0] = 0;//设置 数据标识位等于0,代表 发送的是 文字
|
||||
arrMsg.CopyTo(arrMsgFinal, 0);
|
||||
|
||||
sokMsg.Send(arrMsgFinal);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 04向客户端发送文件数据 +void SendFile(string strPath)
|
||||
/// <summary>
|
||||
/// 04向客户端发送文件数据
|
||||
/// </summary>
|
||||
/// <param name="strPath">文件路径</param>
|
||||
public void SendFile(string strPath)
|
||||
{
|
||||
//通过文件流 读取文件内容
|
||||
using (FileStream fs = new FileStream(strPath, FileMode.OpenOrCreate))
|
||||
{
|
||||
byte[] arrFile = new byte[1024 * 1024 * 2];
|
||||
//读取文件内容到字节数组,并 获得 实际文件大小
|
||||
int length = fs.Read(arrFile, 0, arrFile.Length);
|
||||
//定义一个 新数组,长度为文件实际长度 +1
|
||||
byte[] arrFileFina = new byte[length + 1];
|
||||
arrFileFina[0] = 1;//设置 数据标识位等于1,代表 发送的是文件
|
||||
//将 文件数据数组 复制到 新数组中,下标从1开始
|
||||
//arrFile.CopyTo(arrFileFina, 1);
|
||||
Buffer.BlockCopy(arrFile, 0, arrFileFina, 1, length);
|
||||
//发送文件数据
|
||||
sokMsg.Send(arrFileFina);//, 0, length + 1, SocketFlags.None);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 05向客户端发送闪屏
|
||||
/// <summary>
|
||||
/// 向客户端发送闪屏
|
||||
/// </summary>
|
||||
/// <param name="strMsg"></param>
|
||||
public void SendShake()
|
||||
{
|
||||
byte[] arrMsgFinal = new byte[1];
|
||||
arrMsgFinal[0] = 2;
|
||||
sokMsg.Send(arrMsgFinal);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 06关闭与客户端连接
|
||||
/// <summary>
|
||||
/// 关闭与客户端连接
|
||||
/// </summary>
|
||||
public void CloseConnection()
|
||||
{
|
||||
isRec = false;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
public delegate void DGShowMsg(string strMsg);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
/// <summary>
|
||||
/// 设置电脑时间
|
||||
/// </summary>
|
||||
public class DateTimeSynchronization
|
||||
{
|
||||
[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;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern bool SetLocalTime(ref Systemtime time);
|
||||
|
||||
private static uint swapEndian(ulong x)
|
||||
{
|
||||
return (uint)(((x & 0x000000ff) << 24) +
|
||||
((x & 0x0000ff00) << 8) +
|
||||
((x & 0x00ff0000) >> 8) +
|
||||
((x & 0xff000000) >> 24));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 手动设置系统时间
|
||||
/// </summary>
|
||||
/// <param name="dt">需要设置的时间</param>
|
||||
/// <returns>返回系统时间设置状态,true为成功,false为失败</returns>
|
||||
public 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;
|
||||
}
|
||||
|
||||
|
||||
private static IPAddress iPAddress = null;
|
||||
/// <summary>
|
||||
/// 从NTP获取时间更新本地时间
|
||||
/// </summary>
|
||||
/// <param name="host"></param>
|
||||
/// <param name="syncDateTime"></param>
|
||||
/// <param name="message"></param>
|
||||
/// <returns></returns>
|
||||
public static bool Synchronization(string host, out DateTime syncDateTime, out string message)
|
||||
{
|
||||
syncDateTime = DateTime.Now;
|
||||
try
|
||||
{
|
||||
message = "";
|
||||
if (iPAddress == null)
|
||||
{
|
||||
var iphostinfo = Dns.GetHostEntry(host);
|
||||
var ntpServer = iphostinfo.AddressList[0];
|
||||
iPAddress = ntpServer;
|
||||
}
|
||||
DateTime dtStart = DateTime.Now;
|
||||
//NTP消息大小摘要是16字节 (RFC 2030)
|
||||
byte[] ntpData = new byte[48];
|
||||
//设置跳跃指示器、版本号和模式值
|
||||
// LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
|
||||
ntpData[0] = 0x1B;
|
||||
IPAddress ip = iPAddress;
|
||||
// NTP服务给UDP分配的端口号是123
|
||||
IPEndPoint ipEndPoint = new IPEndPoint(ip, 123);
|
||||
// 使用UTP进行通讯
|
||||
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
socket.Connect(ipEndPoint);
|
||||
socket.ReceiveTimeout = 3000;
|
||||
socket.Send(ntpData);
|
||||
socket.Receive(ntpData);
|
||||
socket?.Close();
|
||||
socket?.Dispose();
|
||||
DateTime dtEnd = DateTime.Now;
|
||||
//传输时间戳字段偏移量,以64位时间戳格式,应答离开客户端服务器的时间
|
||||
const byte serverReplyTime = 40;
|
||||
// 获得秒的部分
|
||||
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
|
||||
//获取秒的部分
|
||||
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
|
||||
//由big-endian 到 little-endian的转换
|
||||
intPart = swapEndian(intPart);
|
||||
fractPart = swapEndian(fractPart);
|
||||
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
|
||||
// UTC时间
|
||||
DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
|
||||
//本地时间
|
||||
DateTime dt = webTime.ToLocalTime();
|
||||
bool isSuccess = SetLocalDateTime(dt);
|
||||
syncDateTime = dt;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
message = ex.Message;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
public class ServiceLog
|
||||
{
|
||||
public void Start()
|
||||
{
|
||||
Thread thread = new Thread(Init);
|
||||
thread.IsBackground = true;
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private void Init()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
DeleteFile(System.Environment.CurrentDirectory + @"\Logs\", 30); //删除该目录下 超过 30天的文件
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
Console.WriteLine(err.Message, err.StackTrace);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Thread.Sleep(100000);
|
||||
}
|
||||
}
|
||||
}
|
||||
private void DeleteFile(string fileDirect, int saveDay)
|
||||
{
|
||||
try
|
||||
{
|
||||
DateTime nowTime = DateTime.Now;
|
||||
string[] files = Directory.GetFiles(fileDirect, "*.txt", SearchOption.AllDirectories); //获取该目录下所有 .txt文件
|
||||
foreach (string file in files)
|
||||
{
|
||||
FileInfo fileInfo = new FileInfo(file);
|
||||
TimeSpan t = DateTime.Now - fileInfo.CreationTime; //当前时间 减去 文件创建时间
|
||||
int day = t.Days;
|
||||
if (day > saveDay) //保存的时间,单位:天
|
||||
{
|
||||
if (IsOccupy(fileInfo.FullName)) //判断文件是否被占用
|
||||
{
|
||||
System.IO.File.Delete(fileInfo.FullName); //删除文件
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Log4Helper.WriteLog("文件被占用,无法操作!","错误提示");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
Log4Helper.WriteLog("文件被占用,无法操作!",err);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
public static extern bool CloseHandle(IntPtr hObject);
|
||||
|
||||
public const int OF_READWRITE = 2;
|
||||
public const int OF_SHARE_DENY_NONE = 0x40;
|
||||
public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
|
||||
|
||||
/// <summary>
|
||||
/// 判断文件是否被占用
|
||||
/// </summary>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
private bool IsOccupy(string file)
|
||||
{
|
||||
bool result = true; //默认状态此文件未被占用
|
||||
try
|
||||
{
|
||||
//string vFileName = @"c:\temp\temp.bmp";
|
||||
string vFileName = file;
|
||||
if (!System.IO.File.Exists(vFileName))
|
||||
{
|
||||
//Logger.Info("文件都不存在!");
|
||||
result = false;
|
||||
}
|
||||
IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
|
||||
if (vHandle == HFILE_ERROR)
|
||||
{
|
||||
|
||||
Log4Helper.WriteLog("文件被占用!", "错误提示");
|
||||
result = false;
|
||||
}
|
||||
CloseHandle(vHandle);
|
||||
Log4Helper.WriteLog("没有被占用!", "错误提示");
|
||||
|
||||
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
result = false;
|
||||
Log4Helper.WriteLog("判断文件是否被占用", err);
|
||||
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.OleDb;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace JY.Infrastructure.Common
|
||||
{
|
||||
public class ExcelToSQL
|
||||
{
|
||||
//DBUnti _db = new DBUnti();
|
||||
|
||||
|
||||
public bool ExcelToSql(ref string strErr)
|
||||
{
|
||||
try
|
||||
{
|
||||
OpenFileDialog fd = new OpenFileDialog();
|
||||
fd.Filter = "导入SQL数据库|*.xlsx;*.xls";//打开文件对话框筛选器
|
||||
if (fd.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
bool b= TransferData(fd.FileName, "tb_hxconfigbase", ref strErr); //数据库表中名称
|
||||
if (b)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
strErr = ex.Message;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Excel导入到Mysql
|
||||
/// </summary>
|
||||
/// <param name="strErr"></param>
|
||||
/// <returns></returns>
|
||||
public bool ExcelToStandardSQL(ref string strErr)
|
||||
{
|
||||
try
|
||||
{
|
||||
strErr = "";
|
||||
OpenFileDialog fd = new OpenFileDialog();
|
||||
fd.Filter = "导入SQL数据库|*.xlsx;*.xls";//打开文件对话框筛选器
|
||||
if (fd.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
DataTable dt = GetExcelDatatable(fd.FileName, "mapTable");
|
||||
bool b = OpDataBase.InsetMySqlData(dt,ref strErr);
|
||||
if (strErr=="")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
//TransferData(fd.FileName, "tb_hxconfigbase", _db.connstr,ref strErr); //数据库表中名称
|
||||
}
|
||||
strErr = "取消导入";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
strErr = ex.Message;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Excel导入到SQLSERVER
|
||||
/// </summary>
|
||||
/// <param name="excelFile"></param>
|
||||
/// <param name="sheetName"></param>
|
||||
/// <param name="strErr"></param>
|
||||
/// <returns></returns>
|
||||
public bool TransferData(string excelFile, string sheetName, ref string strErr)
|
||||
{
|
||||
strErr = "";
|
||||
DataSet ds = new DataSet();
|
||||
try
|
||||
{
|
||||
string strConn = "";
|
||||
strConn = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + excelFile + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
|
||||
strConn = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
|
||||
OleDbConnection conn = new OleDbConnection(strConn);
|
||||
conn.Open();
|
||||
string strExcel = "";
|
||||
OleDbDataAdapter myCommand;
|
||||
strExcel = string.Format("select * from [{0}$]", sheetName);
|
||||
myCommand = new OleDbDataAdapter(strExcel, strConn);
|
||||
myCommand.Fill(ds, sheetName);
|
||||
bool b= OpDataBase.InsetSqlData(ds, sheetName,ref strErr);
|
||||
if (strErr=="")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
#region 屏蔽
|
||||
////列出ds内存表内所有数据,通过For循环把ModelType项数据添加到List集合
|
||||
//List<string> Mlist = new List<string>();
|
||||
//for (int i=0;i<ds.Tables[0].Rows.Count;i++)
|
||||
//{
|
||||
// Mlist.Add(ds.Tables[0].Rows[i][0].ToString());
|
||||
//}
|
||||
//HashSet<string> typeSet = new HashSet<string>(Mlist);//去除List集合重复项
|
||||
//foreach(var item in typeSet)
|
||||
//{
|
||||
// _sqldb.AddModelType(item, ref strErr);
|
||||
//}
|
||||
#endregion
|
||||
|
||||
//如果目标表不存在则创建,excel文件的第一行为列标题,从第二行开始全部都是数据记录
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
strErr = ex.Message;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public DataTable GetExcelDatatable(string fileUrl, string table)
|
||||
{
|
||||
//office2007之前 仅支持.xls
|
||||
//const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
|
||||
//支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes代表第一行是标题,不是数据;
|
||||
const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
|
||||
DataTable dt = null;
|
||||
//建立连接
|
||||
OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
|
||||
try
|
||||
{
|
||||
//打开连接
|
||||
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
|
||||
{
|
||||
conn.Open();
|
||||
}
|
||||
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
|
||||
//获取Excel的第一个Sheet名称
|
||||
string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
|
||||
//查询sheet中的数据
|
||||
string strSql = "select * from [" + sheetName + "]";
|
||||
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
|
||||
DataSet ds = new DataSet();
|
||||
da.Fill(ds, table);
|
||||
dt = ds.Tables[0];
|
||||
return dt;
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
throw exc;
|
||||
}
|
||||
finally
|
||||
{
|
||||
conn.Close();
|
||||
conn.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NPOI;
|
||||
using NPOI.HPSF;
|
||||
using NPOI.HSSF;
|
||||
using NPOI.HSSF.UserModel;
|
||||
using NPOI.SS.UserModel;
|
||||
using NPOI.POIFS;
|
||||
using NPOI.Util;
|
||||
using System.IO;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Infrastructure.Common
|
||||
{
|
||||
class ExportXls
|
||||
{
|
||||
/// <summary>
|
||||
/// 由DataTable导出Excel
|
||||
/// </summary>
|
||||
/// <param name="sourceTable">要导出数据的DataTable</param>
|
||||
/// <returns>Excel工作表</returns>
|
||||
public void ExportDataTableToExcel(DataTable sourceTable, string sheetName, string filepath)
|
||||
{
|
||||
|
||||
FileStream file = new FileStream(filepath, FileMode.Create);
|
||||
HSSFWorkbook workbook = new HSSFWorkbook();
|
||||
// MemoryStream ms = new MemoryStream();
|
||||
ISheet sheet = workbook.CreateSheet(sheetName);
|
||||
IRow headerRow = sheet.CreateRow(0);
|
||||
// handling header.
|
||||
foreach (DataColumn column in sourceTable.Columns)
|
||||
|
||||
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
|
||||
// handling value.
|
||||
int rowIndex = 1;
|
||||
|
||||
foreach (DataRow row in sourceTable.Rows)
|
||||
{
|
||||
IRow dataRow = sheet.CreateRow(rowIndex);
|
||||
foreach (DataColumn column in sourceTable.Columns)
|
||||
{
|
||||
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
|
||||
}
|
||||
rowIndex++;
|
||||
}
|
||||
|
||||
workbook.Write(file);
|
||||
file.Close();
|
||||
sheet = null;
|
||||
headerRow = null;
|
||||
workbook = null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using JY.Model;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
public class Global
|
||||
{
|
||||
/// <summary>
|
||||
/// 错误日志路径
|
||||
/// </summary>
|
||||
public static string strErrorLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\ErrorLogs";
|
||||
|
||||
public static string strSystemLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\SystemLogs";
|
||||
/// <summary>
|
||||
/// MES路径日志
|
||||
/// </summary>
|
||||
public static string strMesLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\MesLogs";
|
||||
/// <summary>
|
||||
/// PLC读取寄存器配置文件路径
|
||||
/// </summary>
|
||||
public static string ConfigPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "ini\\PlcConfig.ini");
|
||||
/// <summary>
|
||||
/// 系统程序配置文件路径
|
||||
/// </summary>
|
||||
public static string iniFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "ini\\Configure.ini");
|
||||
|
||||
public static string CollectItemCfgPath = Path.Combine(System.Windows.Forms.Application.StartupPath, @"Config/采集项参照表.xlsx");
|
||||
|
||||
|
||||
public static SystemConfig systemConfig = new SystemConfig();
|
||||
|
||||
|
||||
public static List<string> Instructions = new List<string>();
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using log4net;
|
||||
using System;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
internal class Log4Helper
|
||||
{
|
||||
public static void WriteLog(Type t, Exception ex)
|
||||
{
|
||||
ILog log = LogManager.GetLogger(t);
|
||||
log.Error(ex);
|
||||
}
|
||||
|
||||
public static void WriteLog(Type t, string msg)
|
||||
{
|
||||
ILog log = LogManager.GetLogger(t);
|
||||
log.Info(msg);
|
||||
}
|
||||
|
||||
public static void WriteLog(string className, Exception ex)
|
||||
{
|
||||
ILog log = LogManager.GetLogger(className);
|
||||
log.Error(ex);
|
||||
}
|
||||
|
||||
public static void WriteLog(string className, string msg)
|
||||
{
|
||||
ILog log = LogManager.GetLogger(className);
|
||||
log.Info(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
public class MessageBoxTimeOut
|
||||
{
|
||||
private string _caption;
|
||||
//public void Alert(string msg, FrmAlert.enmType type)
|
||||
//{
|
||||
// FrmAlert frm = new FrmAlert();
|
||||
// frm.ShowAlert(msg, type);
|
||||
//}
|
||||
public void Show(string text, FrmAlert.enmType type)
|
||||
{
|
||||
this._caption = "信息提示";
|
||||
StartTimer(3000);
|
||||
//Alert(text, type);
|
||||
|
||||
MessageBox.Show(text,"信息提示");
|
||||
}
|
||||
private void StartTimer(int interval)
|
||||
{
|
||||
Timer timer = new Timer();
|
||||
timer.Interval = interval;
|
||||
timer.Tick += new EventHandler(Timer_Tick);
|
||||
timer.Enabled = true;
|
||||
}
|
||||
private void Timer_Tick(object sender, EventArgs e)
|
||||
{
|
||||
KillMessageBox();
|
||||
//停止计时器
|
||||
((Timer)sender).Enabled = false;
|
||||
}
|
||||
[DllImport("User32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
|
||||
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
|
||||
[DllImport("User32.dll", CharSet = CharSet.Auto)]
|
||||
public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
|
||||
public const int WM_CLOSE = 0x10;
|
||||
private void KillMessageBox()
|
||||
{
|
||||
//查找MessageBox的弹出窗口,注意对应标题
|
||||
IntPtr ptr = FindWindow(null, this._caption);
|
||||
if (ptr != IntPtr.Zero)
|
||||
{
|
||||
//查找到窗口则关闭
|
||||
PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace JY.Inspection
|
||||
{
|
||||
|
||||
public enum Logstype//枚举类型
|
||||
{
|
||||
Message,
|
||||
Warning,
|
||||
Error
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 轻快型消息提示类
|
||||
/// </summary>
|
||||
public static class MessageTip
|
||||
{
|
||||
static readonly Image _iconOk;
|
||||
static readonly Image _iconWarning;
|
||||
static readonly Image _iconError;
|
||||
|
||||
/// <summary>
|
||||
/// 全局停留时长(毫秒),影响后续弹出的tip。默认500
|
||||
/// </summary>
|
||||
public static int DefaultDelay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否允许上浮动画。默认true
|
||||
/// </summary>
|
||||
public static bool AllowFloating { get; set; }
|
||||
|
||||
static MessageTip()
|
||||
{
|
||||
DefaultDelay = 500;
|
||||
AllowFloating = true;
|
||||
|
||||
Bitmap spriteImage;
|
||||
using (var ms = new MemoryStream(Convert.FromBase64String(DefaultIconData)))
|
||||
{
|
||||
//不能直接用Img.FromMs得到的对象,怀疑因该方法得到的对象与源ms有瓜葛
|
||||
//ms释放后会导致莫名问题,比如下面的Clone会引发内存不足异常
|
||||
//而new Bitmap(Image)相当于基于Image重造了一个全新的bmp
|
||||
spriteImage = new Bitmap(Image.FromStream(ms));
|
||||
}
|
||||
|
||||
_iconOk = spriteImage.Clone(new Rectangle(0, 0, 32, 32), spriteImage.PixelFormat);
|
||||
_iconWarning = spriteImage.Clone(new RectangleF(32, 0, 32, 32), spriteImage.PixelFormat);
|
||||
_iconError = spriteImage.Clone(new RectangleF(64, 0, 32, 32), spriteImage.PixelFormat);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示良好消息,图标为绿勾 √
|
||||
/// </summary>
|
||||
/// <param name="text">消息文本</param>
|
||||
/// <param name="delay">消息停留时长(毫秒)。指定负数则使用 DefaultDelay</param>
|
||||
public static void ShowOk(string text = null, int delay = -1)
|
||||
{
|
||||
Show(text, _iconOk, Color.SeaGreen, Color.White, delay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示警告消息,图标为黄色感叹号 !
|
||||
/// </summary>
|
||||
/// <param name="text">消息文本</param>
|
||||
/// <param name="delay">消息停留时长(毫秒)。指定负数则使用 DefaultDelay</param>
|
||||
public static void ShowWarning(string text = null, int delay = -1)
|
||||
{
|
||||
Show(text, _iconWarning, Color.DarkOrange, Color.Black, delay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示出错消息,图标为红叉 X
|
||||
/// </summary>
|
||||
/// <param name="text">消息文本</param>
|
||||
/// <param name="delay">消息停留时长(毫秒)。指定负数则使用 DefaultDelay</param>
|
||||
public static void ShowError(string text = null, int delay = -1)
|
||||
{
|
||||
Show(text, _iconError, Color.Red, Color.White, delay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示消息
|
||||
/// </summary>
|
||||
/// <param name="text">消息文本</param>
|
||||
/// <param name="icon">图标。不会进行缩放</param>
|
||||
/// <param name="delay">消息停留时长(毫秒)。指定负数则使用 DefaultDelay</param>
|
||||
public static void Show(string text, Image icon, Color bkColor, Color textColor, int delay = -1)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(obj => new TipForm
|
||||
{
|
||||
TipText = text,
|
||||
TipIcon = icon,
|
||||
Delay = delay < 0 ? DefaultDelay : delay,
|
||||
Floating = AllowFloating,
|
||||
BkColor = bkColor,
|
||||
TextColor= textColor,
|
||||
BasePoint = Control.MousePosition //在鼠标点击的附近弹出
|
||||
}.ShowDialog()); ;//要让创建浮动窗体的线程具有消息循环,所以要用ShowDialog
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 内置图标数据:√ ! X
|
||||
/// </summary>
|
||||
const string DefaultIconData = @"R0lGODlhYAAgANUAAOrcJ9LORebm5tJKShPLJLczM/z3s/XrkNfSOhS2JKaYMezeaMoREfhwcNS3
|
||||
t7IREVSkWpWQZjCpPfz8+zS4RN3PZdTU1EjLWG9uaO/w7/Dke1HVYfHsx5UzM8Q8PLjYuqmmn8bl
|
||||
yeO3txsbD+fck9DAUeDaVV1cHuHXMDGTOO3iSeHy4+BYWDvGTPn25O/hN5PIl8K1Pbfhu/z78nW/
|
||||
fPb39lbeZ5/WpIAzM2HpcqITExGiIjV/N8S9luLbqf///yH5BAAAAAAALAAAAABgACAAAAb/wJ9w
|
||||
SCwaj8ikcslsOp/QKFNUEEGpVqm2OQtUZlJqo+oUk7fHFUWmJWk0pKi4Mc4qxaw6uli7bNZRMxUG
|
||||
BhUuT3gseWdIc4p6e0I0Fzk5EmxPboQHcU2Jiot2RZ+PjFs3LTk2G5aYTC6DBweFh0wFDaC5kERi
|
||||
Ayy+v4oFeyEUNqsbrJdNmm8GcJ63A9PUA7s/VL/V0yymUWobNhfj4xsSTByxb7MVHNEN29xn2fG+
|
||||
3lB9F+LkfstLFbMWaBAoq0KZWx4SJhzgoZuIbB4YLox4DwqNFuJaaGxxgQIMdIM0RMCAIYKGQu6a
|
||||
OCjAQqHLAQUKSHSZsOKTG8YubNRIgUYT/4AHFpAkqaHghIMtPRRQuhAm06VQHSiRAQhJCAl/JCSQ
|
||||
wJUChBogDQgcimHBggPtnqyEGbOt27c2hciQYMNfkRUSOu7Yu1fCVyYTAA5cMJKk2aJfEHVgC9et
|
||||
UqlJqNowZlfIBAgULvDtK2FFEx+DzArFcCKCaLQ+rixVCpd1B1FG5k6mQNnVDxoUNmzewTUElxIH
|
||||
BhMeMeJEiQBeFpQAo7YDa9YPdEiP+0M27evmMN2QQCNBgs0SbjgBHXSBCQQniJ9AjnxBhU4H2Uqf
|
||||
L/21ErrXrydoIeHD1Q3e7eDdVh814QJwGpjAngLEKcBeeyWA5cli9FVYH2xEzPUHBS0MuP+fBClc
|
||||
4KGA3B3FTAUaBICAigEocMIJCqy4ohcBwHeHczpEZyF99iGhIQUeetfCH0H6lYETByaIwJJLxvBi
|
||||
DEwyaUIJtSThQAcFPBCdljl2uWV0PR7xQV4EDFhmAmWe6R0EnjlRQQULRLmkCW+cJ6eCBiUhApZa
|
||||
9unnn312AJmYErRAwKFopplmAin45gQHJWgg56SUTpmSEVcyAKiWHXSwKaeDGjGmooeWemgKHzwR
|
||||
mAkmoODqqygwOIICsL66Yp6j4KDpA7vuKuiVWu7KK6hJfJCCqcimUOCjJSxQ66vEEffsqyVcKoQD
|
||||
umqqrbY4QJYprwxs+4CgxR6LLAEp+KT/agkmqAArANBG+yy8KARQgok/YBvuvvx2S4S+4PLLgL9I
|
||||
GIvsDhDg+1kM7gLgMLwPR0BcBA8/jMLDMaQmRLYCh0vwvxx3jIMSBiMKwZGqxmDCCxW3rIIsKrTc
|
||||
MgIxmKivyKGC3PHAOf8wQQ0ZZCAACObyYIEAQWdQw9ITNH2EDwzLLPXUFWc8xM37fnwE1h73/APQ
|
||||
AlggNgg88NCD2EcLgLTSThtB6wsqvCD33HIDwDLLVDsc678dZO11EZl2jcTPQattuNpJK11D020T
|
||||
MUEPCkQu+eSUV255DwrrS65Kum4eyRJNAy304aSXXrriTk8wOgg4gIB22okbjjbrICC9E/jnuEcR
|
||||
+uiHB73076KT7rvTQQAAOw==";
|
||||
|
||||
/// <summary>
|
||||
/// 浮动消息层
|
||||
/// </summary>
|
||||
private class TipForm : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// 图标和文本之间的间距(像素)
|
||||
/// </summary>
|
||||
const int IconTextSpacing = 3;
|
||||
|
||||
/// <summary>
|
||||
/// 基准点。用于指导本窗体显示位置
|
||||
/// </summary>
|
||||
public Point BasePoint { get; set; }
|
||||
/// <summary>
|
||||
/// 显示文字
|
||||
/// </summary>
|
||||
string _tipText;
|
||||
/// <summary>
|
||||
/// 背景色
|
||||
/// </summary>
|
||||
Color _bkColor = Color.SeaGreen;
|
||||
/// <summary>
|
||||
/// 文字颜色
|
||||
/// </summary>
|
||||
Color _textColor=Color.Black;
|
||||
/// <summary>
|
||||
/// 提示图标
|
||||
/// </summary>
|
||||
public Image TipIcon { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 提示文本
|
||||
/// </summary>
|
||||
public string TipText
|
||||
{
|
||||
get { return _tipText ?? string.Empty; }
|
||||
set { _tipText = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字显示颜色
|
||||
/// </summary>
|
||||
//[DefaultValue(500)]
|
||||
public Color TextColor
|
||||
{
|
||||
get { return _textColor; }
|
||||
set
|
||||
{
|
||||
_textColor = value;
|
||||
this.ForeColor = _textColor;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停留时长(毫秒)
|
||||
/// </summary>
|
||||
[DefaultValue(500)]
|
||||
public int Delay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 停留时长(毫秒)
|
||||
/// </summary>
|
||||
//[DefaultValue(Color.White)]
|
||||
public Color BkColor
|
||||
{
|
||||
get { return _bkColor; }
|
||||
set
|
||||
{
|
||||
_bkColor = value;
|
||||
this.BackColor = _bkColor;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否允许浮动
|
||||
/// </summary>
|
||||
[DefaultValue(true)]
|
||||
public bool Floating { get; set; }
|
||||
|
||||
//显示后不激活,即不抢焦点
|
||||
protected override bool ShowWithoutActivation
|
||||
{
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
public TipForm()
|
||||
{
|
||||
//双缓冲。有必要
|
||||
SetStyle(ControlStyles.UserPaint, true);
|
||||
DoubleBuffered = true;
|
||||
|
||||
InitializeComponent();
|
||||
|
||||
Delay = 500;
|
||||
Floating = true;
|
||||
BkColor = Color.White;
|
||||
this._timer.Tick += timer_Tick;
|
||||
this.Load += TipForm_Load;
|
||||
this.Shown += TipForm_Shown;
|
||||
this.FormClosing += TipForm_FormClosing;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据图标和文字处理窗体尺寸
|
||||
/// </summary>
|
||||
private void ProcessClientSize()
|
||||
{
|
||||
Size size = Size.Empty;
|
||||
if (TipIcon != null)
|
||||
{
|
||||
size += TipIcon.Size;
|
||||
}
|
||||
if (TipText.Length != 0)
|
||||
{
|
||||
if (TipIcon != null)
|
||||
{
|
||||
size.Width += IconTextSpacing;//图标与文字的间距
|
||||
}
|
||||
var textSize = TextRenderer.MeasureText(TipText, this.Font);
|
||||
size.Width += textSize.Width;
|
||||
if (size.Height < textSize.Height) { size.Height = textSize.Height; }
|
||||
}
|
||||
this.ClientSize = size + Padding.Size;
|
||||
}
|
||||
private int x, y; //显示的坐标变量
|
||||
/// <summary>
|
||||
/// 根据基准点处理窗体显示位置
|
||||
/// </summary>
|
||||
private void ProcessLocation()
|
||||
{
|
||||
|
||||
#region 弹窗显示在屏幕中间
|
||||
this.y = (Screen.PrimaryScreen.Bounds.Height - 30 - this.Height) / 2;
|
||||
this.x = (Screen.PrimaryScreen.Bounds.Width - 10 - this.Width) / 2;
|
||||
this.Location = new Point(this.x, this.y);
|
||||
#endregion
|
||||
|
||||
#region 弹窗显示在屏幕右下角
|
||||
//this.x = Screen.PrimaryScreen.WorkingArea.Width - this.Width + 15;
|
||||
//this.y = Screen.PrimaryScreen.WorkingArea.Height - this.Height * i - 5 * i;
|
||||
//this.Location = new Point(this.x, this.y);
|
||||
#endregion
|
||||
|
||||
#region 弹窗跟随鼠标位置
|
||||
//var p = BasePoint;
|
||||
//p.X -= Screen.PrimaryScreen.WorkingArea.Width - this.Width - 1000;//Screen.PrimaryScreen.WorkingArea.Width-this.Width / 2;
|
||||
|
||||
////横向处理。距离屏幕左右两边太近时的处理
|
||||
//int screenWidth;
|
||||
//if (p.X < 10)
|
||||
//{
|
||||
// p.X = 10;
|
||||
//}
|
||||
//else if (p.X + this.Width > (screenWidth = Screen.PrimaryScreen.Bounds.Width) - 10)
|
||||
//{
|
||||
// p.X = screenWidth - 10 - this.Width;
|
||||
//}
|
||||
|
||||
////纵向处理。在鼠标上方显示
|
||||
//p.Y -= this.Height + 20;
|
||||
|
||||
//this.Location = p;
|
||||
#endregion
|
||||
}
|
||||
|
||||
void TipForm_Load(object sender, EventArgs e)
|
||||
{
|
||||
ProcessClientSize();
|
||||
ProcessLocation();
|
||||
|
||||
//上浮窗体动画。采用异步,以不阻塞透明渐变动画的进行
|
||||
if (Floating)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(obj =>
|
||||
{
|
||||
while (this.IsHandleCreated)
|
||||
{
|
||||
this.BeginInvoke(new Action<object>(arg =>
|
||||
{
|
||||
this.Top--;
|
||||
Application.DoEvents();
|
||||
}), (object)null);
|
||||
|
||||
Thread.Sleep(30);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//透明渐入动画。之所以不用异步是为了在完全显示后再开始Delay的计时
|
||||
//不然如果Delay设置过低,还没等看清就渐隐了
|
||||
this.Opacity = 0;
|
||||
while (this.Opacity < 1)
|
||||
{
|
||||
this.Opacity += 0.1;
|
||||
Application.DoEvents();
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
void TipForm_Shown(object sender, EventArgs e)
|
||||
{
|
||||
//因为timer.Interval不能为0
|
||||
if (Delay > 0)
|
||||
{
|
||||
_timer.Interval = Delay;
|
||||
_timer.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
}
|
||||
|
||||
void timer_Tick(object sender, EventArgs e)
|
||||
{
|
||||
_timer.Stop();
|
||||
this.Close();
|
||||
}
|
||||
|
||||
void TipForm_FormClosing(object sender, FormClosingEventArgs e)
|
||||
{
|
||||
//透明渐隐动画
|
||||
while (this.Opacity > 0)
|
||||
{
|
||||
this.Opacity -= 0.1;
|
||||
Application.DoEvents();
|
||||
Thread.Sleep(20);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);
|
||||
|
||||
var clip = GetPaddedRectangle();//得到作图区域
|
||||
var g = e.Graphics;
|
||||
//g.DrawRectangle(Pens.Red, clip);//debug
|
||||
|
||||
//画图标
|
||||
if (TipIcon != null)
|
||||
{
|
||||
g.DrawImageUnscaled(TipIcon, clip.Location);
|
||||
}
|
||||
//画文本
|
||||
if (TipText.Length != 0)
|
||||
{
|
||||
if (TipIcon != null)
|
||||
{
|
||||
clip.X += TipIcon.Width + IconTextSpacing;
|
||||
}
|
||||
TextRenderer.DrawText(g, TipText, this.Font, clip, this.ForeColor, TextFormatFlags.VerticalCenter);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnPaintBackground(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaintBackground(e);
|
||||
|
||||
//画边框
|
||||
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, SystemColors.ControlDark, ButtonBorderStyle.Solid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取刨去Padding的内容区
|
||||
/// </summary>
|
||||
private Rectangle GetPaddedRectangle()
|
||||
{
|
||||
Rectangle r = this.ClientRectangle;
|
||||
r.X += this.Padding.Left;
|
||||
r.Y += this.Padding.Top;
|
||||
r.Width -= this.Padding.Horizontal;
|
||||
r.Height -= this.Padding.Vertical;
|
||||
return r;
|
||||
}
|
||||
|
||||
#region 设计器内容
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_timer.Dispose();//这货必须显示释放
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this._timer = new System.Windows.Forms.Timer();
|
||||
this.SuspendLayout();
|
||||
|
||||
this.AutoScaleMode = AutoScaleMode.None;
|
||||
//this.ClientSize = new System.Drawing.Size(100, 100);
|
||||
this.BackColor = Color.White;
|
||||
this.Font = new Font(SystemFonts.MessageBoxFont.FontFamily, 12);
|
||||
this.FormBorderStyle = FormBorderStyle.None;
|
||||
this.Padding = new Padding(20, 10, 20, 10);
|
||||
this.Name = "TipForm";
|
||||
this.ShowInTaskbar = false;
|
||||
|
||||
this.ResumeLayout(false);
|
||||
}
|
||||
|
||||
private System.Windows.Forms.Timer _timer;
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using JY.Inspection.Entity;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace JY.Inspection.Common
|
||||
{
|
||||
public static class PLCAlarmParse
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 三菱将报警地址值转成报警List
|
||||
/// </summary>
|
||||
/// <param name="plcAddrSuffix">PLC地址值,如100</param>
|
||||
/// <param name="byteData">PLC读取出来的值</param>
|
||||
/// <param name="plcAddrPrefix">PLC地址类型,默认值R</param>
|
||||
/// <returns></returns>
|
||||
public static List<AlarmStatus> MelsecByte2Status(int plcAddrSuffix, byte[] byteData, char plcAddrPrefix = 'R')
|
||||
{
|
||||
var listAlarmStatus = new List<AlarmStatus>();
|
||||
// byte[]转为二进制字符串表示
|
||||
string strResult = "";
|
||||
for (int i = 0; i < byteData.Length; i++)
|
||||
{
|
||||
string strTemp = System.Convert.ToString(byteData[i], 2);
|
||||
strTemp = strTemp.PadLeft(8, '0').StrReverse();
|
||||
strResult += strTemp;
|
||||
}
|
||||
|
||||
for (int i = 0; i < strResult.Length; i++)
|
||||
{
|
||||
var plcByte = i % 16;
|
||||
//如果是16的倍数地址+1
|
||||
if (plcByte % 16 == 0 && i != 0)
|
||||
{
|
||||
plcAddrSuffix++;
|
||||
}
|
||||
//将地址和状态添加到结果集
|
||||
listAlarmStatus.Add(new AlarmStatus()
|
||||
{
|
||||
PLCAdress = $"{plcAddrPrefix}{plcAddrSuffix}.{plcByte.ToString("X")}",
|
||||
Status = strResult[i] == '1'
|
||||
});
|
||||
//if (strResult[i] == '1')
|
||||
// Console.WriteLine($"{plcAddrPrefix}{plcAddrSuffix}.{plcByte.ToString("X")}:{strResult[i]}");
|
||||
}
|
||||
|
||||
return listAlarmStatus;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 欧姆龙NX系列Ethernet/IP通讯时将报警地址值转成报警List {直接读取标签地址/无需高低位互换}
|
||||
/// </summary>
|
||||
/// <param name="plcAddrSuffix">PLC地址值,如100</param>
|
||||
/// <param name="byteData">PLC读取出来的值</param>
|
||||
/// <param name="plcAddrPrefix">PLC地址类型,默认值R</param>
|
||||
/// <returns></returns>
|
||||
public static List<AlarmStatus> OmronEIPByte2Status(int plcAddrSuffix, List<byte> byteData, char plcAddrPrefix = 'W')
|
||||
{
|
||||
var listAlarmStatus = new List<AlarmStatus>();
|
||||
// byte[]转为二进制字符串表示
|
||||
string strResult = "";
|
||||
for (int i = 0; i < byteData.Count; i++)
|
||||
{
|
||||
string strTemp = System.Convert.ToString(byteData[i], 2);
|
||||
strTemp = strTemp.PadLeft(8, '0').StrReverse();
|
||||
strResult += strTemp;
|
||||
}
|
||||
|
||||
for (int i = 0; i < strResult.Length; i++)
|
||||
{
|
||||
var plcByte = i % 16;
|
||||
//如果是16的倍数地址+1
|
||||
if (plcByte % 16 == 0 && i != 0)
|
||||
{
|
||||
plcAddrSuffix++;
|
||||
}
|
||||
//将地址和状态添加到结果集
|
||||
listAlarmStatus.Add(new AlarmStatus()
|
||||
{
|
||||
PLCAdress = $"{plcAddrPrefix}6100[{plcAddrSuffix}].B[{plcByte.ToString()}]",
|
||||
Status = strResult[i] == '1'
|
||||
});
|
||||
|
||||
//if (strResult[i] == '1')
|
||||
// Console.WriteLine($"{plcAddrPrefix}{plcAddrSuffix}.{plcByte.ToString("X")}:{strResult[i]}");
|
||||
}
|
||||
|
||||
return listAlarmStatus;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 欧姆龙FINS通讯读取EM数据寄存器是时将报警地址值转成报警List
|
||||
/// </summary>
|
||||
/// <param name="plcAddrSuffix">PLC地址值,如100</param>
|
||||
/// <param name="byteData">PLC读取出来的值</param>
|
||||
/// <param name="plcAddrPrefix">PLC地址类型,默认值W</param>
|
||||
/// <returns></returns>
|
||||
public static List<AlarmStatus> OmronFinsByte2Status(int plcAddrSuffix, byte[] byteData, char plcAddrPrefix = 'E')
|
||||
{
|
||||
var listAlarmStatus = new List<AlarmStatus>();
|
||||
// byte[]转为二进制字符串表示
|
||||
byte[] revBytes = SWAPbyte(byteData); //字节高低位互换
|
||||
string strResult = "";
|
||||
for (int i = 0; i < revBytes.Length; i++)
|
||||
{
|
||||
string strTemp = System.Convert.ToString(revBytes[i], 2);
|
||||
strTemp = strTemp.PadLeft(8, '0').StrReverse();
|
||||
strResult += strTemp;
|
||||
}
|
||||
|
||||
for (int i = 0; i < strResult.Length; i++)
|
||||
{
|
||||
var plcByte = i % 16;
|
||||
//如果是16的倍数地址+1
|
||||
if (plcByte % 16 == 0 && i != 0)
|
||||
{
|
||||
plcAddrSuffix++;
|
||||
}
|
||||
//将地址和状态添加到结果集
|
||||
listAlarmStatus.Add(new AlarmStatus()
|
||||
{
|
||||
PLCAdress = $"{plcAddrPrefix}{plcAddrSuffix}.{plcByte.ToString("X")}",
|
||||
Status = strResult[i] == '1'
|
||||
});
|
||||
//if (strResult[i] == '1')
|
||||
// Console.WriteLine($"{plcAddrPrefix}{plcAddrSuffix}.{plcByte.ToString("X")}:{strResult[i]}");
|
||||
}
|
||||
|
||||
return listAlarmStatus;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 欧姆龙FINS通讯读取W数据寄存器是时将报警地址值转成报警List
|
||||
/// </summary>
|
||||
/// <param name="plcAddrSuffix">PLC地址值,如100</param>
|
||||
/// <param name="byteData">PLC读取出来的值</param>
|
||||
/// <param name="plcAddrPrefix">PLC地址类型,默认值W</param>
|
||||
/// <returns></returns>
|
||||
//public static List<AlarmStatus> OmronByte2Status(int plcAddrSuffix, byte[] byteData, char plcAddrPrefix = 'W')
|
||||
//{
|
||||
// var listAlarmStatus = new List<AlarmStatus>();
|
||||
|
||||
// var addrCount = byteData.Length / 2;
|
||||
// // byte[]每个地址保存的都是bool值,只取双数index位
|
||||
// for (int i = 0; i < addrCount; i++)
|
||||
// {
|
||||
// //将地址和状态添加到结果集
|
||||
// listAlarmStatus.Add(new AlarmStatus()
|
||||
// {
|
||||
// PLCAdress = $"{plcAddrPrefix}{plcAddrSuffix + i}",
|
||||
// Status = byteData[i * 2 + 1] == 1
|
||||
|
||||
// });
|
||||
// //if (byteData[i * 2 + 1] == 1)
|
||||
// // Console.WriteLine($"原始数据 PLC地址:{plcAddrPrefix}{plcAddrSuffix + i} 报警值:{byteData[i * 2 + 1]}");
|
||||
// }
|
||||
|
||||
// return listAlarmStatus;
|
||||
//}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 字符串反转
|
||||
/// </summary>
|
||||
/// <param name="str">需要反转字符串.Reverse()</param>
|
||||
/// <returns></returns>
|
||||
public static string StrReverse(this string str)
|
||||
{
|
||||
return new string(str.Reverse().ToArray());
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
///byte字节高低位互换
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] SWAPbyte(byte[] data)
|
||||
{
|
||||
byte[] data2 = new byte[data.Length];
|
||||
for (int i = 0; i < data.Length; i += 2)
|
||||
{
|
||||
data2[i] = data[i + 1];
|
||||
data2[i + 1] = data[i];
|
||||
}
|
||||
return data2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection.Common
|
||||
{
|
||||
public class StrUtil
|
||||
{
|
||||
/// <summary>
|
||||
/// 前端字节补0
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetStartString(string str, int count)
|
||||
{
|
||||
string strRes = str;
|
||||
int strCount = str.Length;
|
||||
|
||||
if (strCount != count)
|
||||
{
|
||||
strRes = str.PadLeft(count, '0');
|
||||
|
||||
}
|
||||
return strRes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 增加结尾字节长度
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetEndString(string str, int count)
|
||||
{
|
||||
string strRes = str;
|
||||
int strCount = str.Length;
|
||||
|
||||
if (strCount != count)
|
||||
{
|
||||
|
||||
strRes = str.PadRight(count, ' ');
|
||||
|
||||
}
|
||||
return strRes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成字符串List集合
|
||||
/// </summary>
|
||||
/// <param name="Num"></param>
|
||||
/// <returns></returns>
|
||||
public static List<string> GetListString(int Num, string str)
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
for (int i = 0; i < Num; i++)
|
||||
{
|
||||
list.Add(str);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Common.Helper
|
||||
{
|
||||
public class TxtHelper
|
||||
{
|
||||
static ReaderWriterLockSlim sucessLogWriteLockSlim = new ReaderWriterLockSlim();
|
||||
|
||||
/// <summary>
|
||||
/// 写入TEXT文本
|
||||
/// </summary>
|
||||
/// <param name="fullName">文件名</param>
|
||||
/// <param name="content">内容</param>
|
||||
/// <returns>保存结果</returns>
|
||||
public static bool WriteTxt(string fullName, string content)
|
||||
{
|
||||
FileStream fs = null;
|
||||
StreamWriter sw = null;
|
||||
|
||||
try
|
||||
{
|
||||
string directory = fullName.Substring(0, fullName.LastIndexOf('\\'));
|
||||
if (!Directory.Exists(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
sucessLogWriteLockSlim.EnterWriteLock();//加锁防止抢占
|
||||
if (!File.Exists(fullName))
|
||||
{
|
||||
fs = new FileStream(fullName, FileMode.Create, FileAccess.Write);
|
||||
sw = new StreamWriter(fs, Encoding.UTF8);
|
||||
}
|
||||
else
|
||||
{
|
||||
fs = new FileStream(fullName, FileMode.Append, FileAccess.Write);
|
||||
sw = new StreamWriter(fs, Encoding.UTF8);
|
||||
}
|
||||
|
||||
sw.WriteLine(content);
|
||||
|
||||
sw.Close();
|
||||
fs.Close();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sw?.Close();
|
||||
fs?.Close();
|
||||
|
||||
}
|
||||
finally
|
||||
{
|
||||
sucessLogWriteLockSlim.ExitWriteLock();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JY.Inspection.Common
|
||||
{
|
||||
public class CurrentInfo
|
||||
{
|
||||
public static Autuority autuority = Autuority.Empty;
|
||||
public static bool LoginOut = false;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class User
|
||||
{
|
||||
/// <summary>
|
||||
/// 序号
|
||||
/// </summary>
|
||||
///
|
||||
[Display(Name = "序号")]
|
||||
public int Index { get; set; }
|
||||
/// <summary>
|
||||
/// 用户名
|
||||
/// </summary>
|
||||
///
|
||||
[Display(Name = "用户名")]
|
||||
public string UserName { get; set; }
|
||||
/// <summary>
|
||||
/// 密码
|
||||
/// </summary>
|
||||
///
|
||||
[Display(Name = "密码")]
|
||||
public string PassWord { get; set; }
|
||||
/// <summary>
|
||||
/// 权限
|
||||
/// </summary>
|
||||
///
|
||||
[Display(Name = "权限")]
|
||||
public Autuority Level { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 权限枚举
|
||||
/// </summary>
|
||||
public enum Autuority
|
||||
{
|
||||
管理员,//管理员
|
||||
工程师,//工程师
|
||||
操作员,//操作员
|
||||
Empty,
|
||||
}
|
||||
|
||||
public class UserHelper
|
||||
{
|
||||
private string filePath = string.Empty;
|
||||
public UserHelper(string path)
|
||||
{
|
||||
filePath = path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 序列化到文件
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="listUser"></param>
|
||||
/// <returns></returns>
|
||||
public bool SerializedUser(string path, List<User> listUser)
|
||||
{
|
||||
if (listUser == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
BinaryFormatter format = new BinaryFormatter();
|
||||
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
format.Serialize(fs, listUser);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 反序列化到文件
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
public List<User> DeSerializedUser(string path)
|
||||
{
|
||||
BinaryFormatter format = new BinaryFormatter();
|
||||
try
|
||||
{
|
||||
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
object o = format.Deserialize(fs);
|
||||
return o as List<User>;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建超级用户
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="listUser"></param>
|
||||
public void CheckSupperUser(string path, List<User> listUser)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
User user = new User()
|
||||
{
|
||||
Index = 0,
|
||||
UserName = "Admin",
|
||||
PassWord = "Admin",
|
||||
Level = Autuority.管理员
|
||||
};
|
||||
listUser.Add(user);
|
||||
SerializedUser(path, listUser);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查重复性
|
||||
/// </summary>
|
||||
/// <param name="listUser"></param>
|
||||
/// <param name="userNmae"></param>
|
||||
/// <returns></returns>
|
||||
public bool CheckContainUser(List<User> listUser, string userNmae)
|
||||
{
|
||||
var user = from item in listUser
|
||||
where item.UserName == userNmae
|
||||
select item;
|
||||
if (user.Count() > 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加用户
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="listUser"></param>
|
||||
/// <param name="user"></param>
|
||||
/// <returns></returns>
|
||||
public bool AddUser(string path, List<User> listUser, User user)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (CheckContainUser(listUser, user.UserName))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
listUser.Add(user);
|
||||
SerializedUser(path, listUser);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="listUser"></param>
|
||||
/// <param name="userNmae"></param>
|
||||
/// <returns></returns>
|
||||
public bool DeleteUser(string path, List<User> listUser, string userNmae)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (listUser == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
int index = 0;
|
||||
foreach (var item in listUser)
|
||||
{
|
||||
if (item.UserName == userNmae)
|
||||
{
|
||||
break;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
if (index == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
listUser.RemoveAt(index);
|
||||
SerializedUser(path, listUser);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改用户
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="listUser"></param>
|
||||
/// <param name="user"></param>
|
||||
/// <returns></returns>
|
||||
public bool EditUser(string path, List<User> listUser, User user)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (listUser == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
foreach (var item in listUser)
|
||||
{
|
||||
if (item.UserName == user.UserName)
|
||||
{
|
||||
item.PassWord = user.PassWord;
|
||||
item.Level = user.Level;
|
||||
SerializedUser(path, listUser);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public User CheckUserLogin(string path, string userName, string passWord, ref string strErr)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
List<User> list = DeSerializedUser(path);
|
||||
if (list == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
User user = new User();
|
||||
if (string.IsNullOrEmpty(userName))
|
||||
{
|
||||
var res1 = from item in list
|
||||
where item.PassWord == passWord
|
||||
select item;
|
||||
if (res1.Count() == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
foreach (var item in res1)
|
||||
{
|
||||
user.UserName = item.UserName;
|
||||
user.PassWord = item.PassWord;
|
||||
user.Level = item.Level;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var res = from item in list
|
||||
where item.PassWord == passWord && item.UserName == userName
|
||||
select item;
|
||||
if (res.Count() == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
foreach (var item in res)
|
||||
{
|
||||
user.UserName = item.UserName;
|
||||
user.PassWord = item.PassWord;
|
||||
user.Level = item.Level;
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user