台州海关TD3600上线版本

This commit is contained in:
terry.wang
2025-11-26 17:20:53 +08:00
parent ccaffc1014
commit 80be2ed45e
961 changed files with 1395034 additions and 0 deletions

157
JJMediSys/cs/ComTool.cs Normal file
View File

@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JJMediSys
{
public class ComTool
{
SerialPort serialPort;
/// <summary>
/// 打开串口
/// </summary>
/// <param name="protName">串口号</param>
/// <param name="baudRate">波特率</param>
/// <param name="dataBit">数据位</param>
/// <param name="stopBits">停止位</param>
/// /// <param name="parity">校验位</param>
/// <returns></returns>
public bool OpenCom(string protName, int baudRate, int dataBit, float stopBits, int parity)
{
bool flag = true;
if (serialPort == null)
{
serialPort = new SerialPort();
}
serialPort.PortName = protName;//串口号
serialPort.BaudRate = baudRate;//波特率
float f = stopBits;//停止位
if (f == 0)
{
serialPort.StopBits = StopBits.None;
}
else if (f == 1.5)
{
serialPort.StopBits = StopBits.OnePointFive;
}
else if (f == 1)
{
serialPort.StopBits = StopBits.One;
}
else
{
serialPort.StopBits = StopBits.Two;
}
serialPort.DataBits = dataBit;//数据位
if (parity == 0)
{
serialPort.Parity = Parity.None;
}
else if (parity == 1)
{
serialPort.Parity = Parity.Odd;
}
else if (parity == 2)
{
serialPort.Parity = Parity.Even;
}
else
{
serialPort.Parity = Parity.None;
}
// sp.ReadTimeout = 1000;//设置超时读取时间
// sp.WriteTimeout = 1000;//超时写入时间
try
{
if (!serialPort.IsOpen)
{
serialPort.Open();
}
}
catch (Exception ex)
{
string msg = ex.Message;
flag = false;
}
return flag;
}
/// <summary>
/// 关闭端口
/// </summary>
/// <returns></returns>
public bool CloseCom()
{
try
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
return true;
}
catch
{
return false;
}
}
public bool isOpen()
{
return serialPort.IsOpen;
}
public byte[] SendAndRecv(byte[] sendData, int timeout = 5000)
{
//打开连接
if (!serialPort.IsOpen) serialPort.Open();
serialPort.DiscardInBuffer();
//发送数据
serialPort.Write(sendData, 0, sendData.Length);
//读取返回数据
DateTime dt = DateTime.Now;
while (serialPort.BytesToRead < 2)
{
Thread.Sleep(50);
if (DateTime.Now.Subtract(dt).TotalMilliseconds > timeout)
{
throw new Exception("主版无响应");
}
}
List<byte> recList = new List<byte>();
byte[] recData = new byte[serialPort.BytesToRead];
byte[] Heard = new byte[2];
serialPort.Read(Heard, 0, 2);
recList.AddRange(Heard);
int length = Heard[1] + 3; //报文数据总长度
while (recList.Count < length)
{
if (serialPort.BytesToRead > 0)
{
int ToRead = 0;
if (serialPort.BytesToRead > (length - recList.Count))
{
ToRead = length - recList.Count;
}
else
{
ToRead = serialPort.BytesToRead;
}
recData = new byte[ToRead];
serialPort.Read(recData, 0, ToRead);
recList.AddRange(recData);
}
Thread.Sleep(1);
}
return recList.ToArray();
}
}
}

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace JJMediSys.cs
{
public class ConfigFileReader
{
static XmlDocument xmlDocument = null;
static string filepath = System.AppDomain.CurrentDomain.BaseDirectory + "\\JJMediSys.exe.config";
public static string GetValue(string key)
{
if (xmlDocument == null)
xmlDocument = new XmlDocument();
xmlDocument.Load(filepath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
XmlNode xmlNode = xmlDocument.SelectSingleNode(key, nsmgr);
XmlElement Xe = (XmlElement)xmlNode;
return Xe.GetAttribute("value");
}
public static void SetValue(string appKey, string newValue)
{
if (xmlDocument == null)
xmlDocument = new XmlDocument();
xmlDocument.Load(filepath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
XmlNode xmlNode = xmlDocument.SelectSingleNode(appKey, nsmgr);
XmlElement Xe = (XmlElement)xmlNode;
Xe.SetAttribute("value", newValue);
xmlDocument.Save(filepath);
}
}
}

View File

@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JJMediSys
{
/// <summary>
/// 使窗口的中的指定控件支持运行时移动
/// TODO:运行时缩放
/// </summary>
public class ControlMoveResize
{
#region
bool isMoving = false;
Point pCtrlLastCoordinate = new Point(0, 0);
Point pCursorOffset = new Point(0, 0);
Point pCursorLastCoordinate = new Point(0, 0);
private Control ctrl = null;
private ScrollableControl containe = null;
#endregion
#region
/// <summary>
/// 在鼠标左键按下的状态记录鼠标当前的位置,以及被移动组件的当前位置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MouseDown(object sender, MouseEventArgs e)
{
if (containe == null)
{
return;
}
if (e.Button == MouseButtons.Left)
{
isMoving = true;
pCtrlLastCoordinate.X = ctrl.Left;
pCtrlLastCoordinate.Y = ctrl.Top;
pCursorLastCoordinate.X = Cursor.Position.X;
pCursorLastCoordinate.Y = Cursor.Position.Y;
}
}
private void MouseMove(object sender, MouseEventArgs e)
{
if (containe == null)
{
return;
}
if (e.Button == MouseButtons.Left)
{
if (this.isMoving)
{
ctrl.BringToFront();
Point pCursor = new Point(Cursor.Position.X, Cursor.Position.Y);
pCursorOffset.X = pCursor.X - pCursorLastCoordinate.X;
pCursorOffset.Y = pCursor.Y - pCursorLastCoordinate.Y;
ctrl.Left = pCtrlLastCoordinate.X + pCursorOffset.X;
ctrl.Top = pCtrlLastCoordinate.Y + pCursorOffset.Y;
ctrl.Parent.Refresh();
}
}
}
private void MouseUp(object sender, MouseEventArgs e)
{
if (containe == null)
{
return;
}
if (this.isMoving)
{
if (pCursorOffset.X == 0 && pCursorOffset.Y == 0)
{
return;
}
if ((pCtrlLastCoordinate.X + pCursorOffset.X + ctrl.Width) > 0)
{
ctrl.Left = pCtrlLastCoordinate.X + pCursorOffset.X;
}
else
{
ctrl.Left = 0;
}
if ((pCtrlLastCoordinate.Y + pCursorOffset.Y + ctrl.Height) > 0)
{
ctrl.Top = pCtrlLastCoordinate.Y + pCursorOffset.Y;
}
else
{
ctrl.Top = 0;
}
pCursorOffset.X = 0;
pCursorOffset.Y = 0;
}
moveDownAction?.Invoke();
}
#endregion
public Action moveDownAction;
#region
/// <summary>
/// 获取被移动控件对象和容器对象
/// </summary>
/// <param name="c">被设置为可运行时移动的控件</param>
/// <param name="parentContain">可移动控件的容器</param>
public void SetDev(Control c, ScrollableControl parentContain)
{
ctrl = c;
this.containe = parentContain;
ctrl.MouseDown += new MouseEventHandler(MouseDown);
ctrl.MouseMove += new MouseEventHandler(MouseMove);
ctrl.MouseUp += new MouseEventHandler(MouseUp);
}
#endregion
}
}

925
JJMediSys/cs/DoDBMySql.cs Normal file
View File

@@ -0,0 +1,925 @@
using MySql.Data.MySqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace JJMediSys
{
public class DoDBMySql
{
//数据库连接字符串(web.config来配置)可以动态更改connectionString支持多数据库.
public static string connectionString = "";
public DoDBMySql()
{
}
public static bool IsConnectionValid()
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
if (connection.Ping())
{
MainForm.DBStat = 0;
return true;
}
else
{
MainForm.DBStat = -1;
return false;
}
}
}
catch (Exception ex)
{
MainForm.DBStat = -1;
return false;
}
}
public enum EffentNextType
{
/// <summary>
/// 对其他语句无任何影响
/// </summary>
None,
/// <summary>
/// 当前语句必须为"SELECT COUNT(1) FROM .."格式,如果存在则继续执行,不存在回滚事务
/// </summary>
WhenHaveContine,
/// <summary>
/// 当前语句必须为"SELECT COUNT(1) FROM .."格式,如果不存在则继续执行,存在回滚事务
/// </summary>
WhenNoHaveContine,
/// <summary>
/// 当前语句影响到的行数必须大于0否则回滚事务
/// </summary>
ExcuteEffectRows,
/// <summary>
/// 引发事件-当前语句必须为"SELECT COUNT(1) FROM .."格式,如果不存在则继续执行,存在回滚事务
/// </summary>
SolicitationEvent
}
public class CommandInfo
{
public object ShareObject = null;
public object OriginalData = null;
event EventHandler SsolicitationEvent;
public event EventHandler SolicitationEvent
{
add
{
SsolicitationEvent += value;
}
remove
{
SsolicitationEvent -= value;
}
}
public void OnSolicitationEvent()
{
SsolicitationEvent?.Invoke(this, new EventArgs());
}
public string CommandText;
public System.Data.Common.DbParameter[] Parameters;
public EffentNextType EffentNextType = EffentNextType.None;
public CommandInfo()
{
}
public CommandInfo(string sqlText, SqlParameter[] para)
{
this.CommandText = sqlText;
this.Parameters = para;
}
public CommandInfo(string sqlText, SqlParameter[] para, EffentNextType type)
{
this.CommandText = sqlText;
this.Parameters = para;
this.EffentNextType = type;
}
}
#region
/// <summary>
/// 得到最大值
/// </summary>
/// <param name="FieldName"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 是否存在基于MySqlParameter
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion
#region SQL语句
/// <summary>
/// 执行SQL语句返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
MainForm.DBStat = -1;
throw e;
}
}
}
}
/// <summary>
/// 执行SQL语句返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static long ExecuteSqlReturnID(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return cmd.LastInsertedId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
MainForm.DBStat = -1;
throw e;
}
}
}
}
public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
MainForm.DBStat = -1;
throw e;
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static int ExecuteSqlTran(List<String> SQLStringList)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand cmd = new MySqlCommand
{
Connection = connection
};
MySqlTransaction tx = connection.BeginTransaction();
cmd.Transaction = tx;
string strsql = "";
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch (Exception aaa)
{
// Tools.WriteTextLog("批量写入失败:" + aaa.Message + "_SQL:" + strsql, "error");
// tx.Rollback();
return 0;
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText)
{
Value = content
};
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
MainForm.DBStat = -1;
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText)
{
Value = content
};
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
MainForm.DBStat = -1;
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image)
{
Value = fs
};
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
MainForm.DBStat = -1;
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行一条计算查询结果语句返回查询结果object
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果object</returns>
public static object GetSingle(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
MainForm.DBStat = -1;
throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
MainForm.DBStat = -1;
throw e;
}
}
}
}
/// <summary>
/// 执行查询语句返回MySqlDataReader ( 注意调用该方法后一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string strSQL)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
try
{
connection.Open();
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
MainForm.DBStat = -1;
throw e;
}
}
/// <summary>
/// 执行查询语句返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MainForm.DBStat = -1;
throw new Exception(ex.Message);
}
return ds;
}
}
public static DataSet Query(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MainForm.DBStat = -1;
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region SQL语句
/// <summary>
/// 执行SQL语句返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表key为sql语句value是该语句的MySqlParameter[]</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表key为sql语句value是该语句的MySqlParameter[]</param>
public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int count = 0;
//循环
foreach (CommandInfo myDE in cmdList)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
{
if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
{
trans.Rollback();
return 0;
}
object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > 0;
if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
{
trans.Rollback();
return 0;
}
if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
{
trans.Rollback();
return 0;
}
continue;
}
int val = cmd.ExecuteNonQuery();
count += val;
if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
{
trans.Rollback();
return 0;
}
cmd.Parameters.Clear();
}
trans.Commit();
return count;
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表key为sql语句value是该语句的MySqlParameter[]</param>
public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = 0;
//循环
foreach (CommandInfo myDE in SQLStringList)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表key为sql语句value是该语句的MySqlParameter[]</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = 0;
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句返回查询结果object
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果object</returns>
public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 执行查询语句返回MySqlDataReader ( 注意调用该方法后一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// }
}
/// <summary>
/// 执行查询语句返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (MySqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
public static object ExecuteProc(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
cmd.CommandType = CommandType.StoredProcedure;
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
#endregion
}
}

267
JJMediSys/cs/NetCom.cs Normal file
View File

@@ -0,0 +1,267 @@
using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Web;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.Reflection;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
namespace JJMediSys
{
class NetCom
{
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
public static void WriteLog(string msg)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "LisLog";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string logPath = AppDomain.CurrentDomain.BaseDirectory + "LisLog\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
try
{
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + msg + "\r\n");
sw.Flush();
sw.Close();
sw.Dispose();
}
}
catch (IOException e)
{
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine("异常:" + e.Message + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss.fff") + "\r\n");
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
if (property != null)
{
var collection = property.GetValue(header, null) as NameValueCollection;
collection[name] = value;
}
}
public static HttpWebResponse CreatePostHttpResponse(string url, string Input, Encoding charset)
{
HttpWebRequest request = null;
//HTTPSQ请求
// ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
// 1. 统一设置:跳过任何证书错误(开发/测试用)
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
//request.ContentLength = Input.Length;
request.ContentType = "application/json";
//request.UserAgent = DefaultUserAgent;
request.Timeout = 30000;
request.Proxy = null;
//如果需要POST数据
byte[] data = charset.GetBytes(Input);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
return request.GetResponse() as HttpWebResponse;
}
public string GetHttpResponse(string url, int Timeout)
{
string retString = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.UserAgent = null;
request.Timeout = Timeout;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
}
catch (System.Exception ex)
{
WriteLog("Exception Error Message is " + ex.Message);
}
return retString;
}
public static HttpWebResponse CreateGetHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset)
{
StringBuilder builder = new StringBuilder();
builder.Append(url);
if (parameters.Count > 0)
{
builder.Append("?");
int i = 0;
foreach (var item in parameters)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
}
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
return (HttpWebResponse)req.GetResponse() as HttpWebResponse;
}
public string OutString;
public bool SendAndRecv(string url, string Input,string PatID)
{
//OutString = "{\"code\": \"200\",\"msg\": \"成功\",\"data\": {\"patientId\": \"HN755155\",\"name\": \"马洪义\",\"age\": \"66\",\"sex\": \"男\",\"windowNo\": \"\",\"photo\": \"\",\"itemCount\": 7,\"userType\": \"0\",\"idCardNo\": \"\",\"phone\": \"\",\"healthCardNo\": \"\",\"doctor\": \"\",\"pojoList\": [{\"requestId\": \"2412062091\",\"patientId\": \"HN755155\",\"ward\": \"健康管理中心\",\"wardId\": \"812030\",\"bedNo\": \"\",\"tubeConvert\": \"YELLOW\",\"noteLabel\": \"静脉血\",\"mnemotests\": \"超级赛亚人检测\",\"station\": \"免疫室\",\"stationId\": \"817440\",\"state\": \"0\",\"datebz\": \"2024-12-06 10:11:42\",\"descbz\": \"\",\"pickupLocation\": \"门诊一层检验报告领取处\",\"pickupTime\": \"下个工作日16:30后\",\"groupId\": \"\",\"labelCount\": \"1\",\"mnemoitems\": \"防御力检测;\"},{\"requestId\": \"2412062072\",\"patientId\": \"HN755155\",\"ward\": \"健康管理中心\",\"wardId\": \"812030\",\"bedNo\": \"\",\"tubeConvert\": \"YELLOW\",\"noteLabel\": \"静脉血\",\"mnemotests\": \"波塞冬测试\",\"station\": \"免疫室\",\"stationId\": \"817440\",\"state\": \"0\",\"datebz\": \"2024-12-06 10:11:42\",\"descbz\": \"\",\"pickupLocation\": \"门诊一层检验报告领取处\",\"pickupTime\": \"下工作日16:30后(周末延1个工作日)\",\"groupId\": \"\",\"labelCount\": \"1\",\"mnemoitems\": \"乙型肝炎病毒表面抗体(发光法);乙型肝炎病毒E抗原发光法;乙型肝炎病毒E抗体发光法;乙型肝炎病毒核心抗体(发光法);艾滋病抗原、抗体测定(发光法);丙型肝炎病毒抗体(发光法);乙型肝炎病毒表面抗原(发光法);梅毒血清特异抗体测定(发光法);\"}]}}";
//string sql1 = "Insert into lis_log (PatID,Req,Res) values('" + PatID + "','" + Input + "','" + OutString + "')";
//try
//{
// int Ret = DoDBMySql.ExecuteSql(sql1);
//}
//catch (Exception ex)
//{
//}
//return true;
//WriteLog(Input);
Encoding encoding = Encoding.GetEncoding("utf-8");
OutString = "";
try
{
HttpWebResponse response = CreatePostHttpResponse(url, Input, encoding);
Stream stream = response.GetResponseStream(); //获取响应的字符串流
StreamReader sr = new StreamReader(stream); //创建一个stream读取流
OutString = sr.ReadToEnd(); //从头读到尾放到字符串html
string logstr = string.Format("url={0}\r\n Req={1}\r\nRes={2}", url, Input, OutString);
WriteLog(logstr);
string sql = "Insert into lis_log (PatID,Req,Res) values('" + PatID + "','" + Input + "','" + OutString + "')";
try
{
int Ret = DoDBMySql.ExecuteSql(sql);
}
catch (Exception ex)
{
}
return true;
}
catch (Exception e)
{
WriteLog("Exception Error Message is " + e.Message);
string sql = "Insert into lis_log (PatID,Req,Res) values('" + PatID + "','" + Input + "','" + e.Message + "')";
try
{
int Ret = DoDBMySql.ExecuteSql(sql);
}
catch (Exception ex)
{
}
return false;
}
}
public static async Task<bool> SendHisComplete(string PatID)
{
WriteLog($"进入诊结");
try
{
using (var client = new HttpClient())
{
// 准备表单数据
var formData = new Dictionary<string, string>
{
{ "out_code", PatID }
};
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(
"http://10.10.8.244:10005/api/doctor/his/completed", // 替换为你的目标 URL
new FormUrlEncodedContent(formData)
);
// 确保成功
response.EnsureSuccessStatusCode();
// 读取响应内容
bool ExcutResult = false;
string Outmsg = await response.Content.ReadAsStringAsync();
WriteLog($"诊结请求[{PatID}] 应答:[{Outmsg}]");
string sql = "Insert into lis_log (PatID,Req,Res) values('" + PatID + "','" + PatID + "','" + Outmsg + "')";
JObject jObject = (JObject)JsonConvert.DeserializeObject(Outmsg);
if (jObject["status"].ToString().Equals("200"))
{
WriteLog("提交诊结成功 , 回参:" + Outmsg);
ExcutResult = true;
}
else
{
WriteLog("提交诊结失败, 回参:" + Outmsg);
}
try
{
int Ret = DoDBMySql.ExecuteSql(sql);
}
catch (Exception e)
{
}
return ExcutResult;
}
}
catch (WebException ex)
{
WriteLog("提交诊结异常:" + ex.Message);
using (var reader = new StreamReader(ex.Response?.GetResponseStream()))
{
string Outmsg = reader.ReadToEnd();
WriteLog("提交诊结异常:" + ex.Message+", 回参:"+ Outmsg);
string sql = "Insert into lis_log (PatID,Req,Res) values('" + PatID + "','" + PatID + "','" + Outmsg + "')";
try
{
int Ret = DoDBMySql.ExecuteSql(sql);
}
catch (Exception e)
{
}
return false;
}
}
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JJMediSys.cs
{
class PublicStatic
{
public static SqlHelper EventMgr = new SqlHelper();
}
}

452
JJMediSys/cs/RecpCreate.cs Normal file
View File

@@ -0,0 +1,452 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
namespace JJMediSys
{
public class RecpCreate
{
SolidBrush sbrush = new SolidBrush(System.Drawing.Color.Black);
StringFormat strFormat = new StringFormat();
//static int RecpW = 448;
//static int RecpH = 240;
static int RecpW = 672;
static int RecpH = 354;
int PerLineLen = RecpW / 8;
public Image CreateImage(string Indate, ref Byte[] ImgaeData)
{
TubeLabelTool.logger.Info("RecpInfo: " + Indate);
if (SystemSet.RecpImageSize == 29736)
{
RecpW = 672;
RecpH = 354;
}
else
{
RecpW = 448;
RecpH = 240;
}
PerLineLen = RecpW / 8;
strFormat.Alignment = StringAlignment.Near; //左对齐
strFormat.LineAlignment = StringAlignment.Near;
Image img = new Bitmap(RecpW, RecpH);
Graphics g = Graphics.FromImage(img);
g.DrawImage(img, 1, 1, RecpW, RecpH);
g.Clear(Color.White);
string[] Arrstr = Indate.Split('@');
foreach (string Temp in Arrstr)
{
Draw(g, Temp);
}
Bitmap bmp = new Bitmap(RecpW, RecpH);
Graphics gg = Graphics.FromImage(bmp);
gg.DrawImage(img, 0, 0, new Rectangle(0, 0, RecpW, RecpH), GraphicsUnit.Pixel);
// Byte[] PrintDate = new byte[56 * 240];
Bitmap mybitmap = new Bitmap(img);
Color srcColor;
int wide = mybitmap.Width;
int height = mybitmap.Height;
int Index = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < wide; x++)
{
//获取像素的RGB颜色值
srcColor = mybitmap.GetPixel(x, y);
if (srcColor.R != 255)
{
Index = y * PerLineLen + x / 8;
ImgaeData[Index] |= (byte)(0x80 >> (x % 8));
}
}
}
string Hexstr = ToHexStrFromByte(ImgaeData);
//img.Save("D:\\1.bmp");
g.Dispose();
gg.Dispose();
return img;
}
public Image CreateBLEImage(string Indate, ref Byte[] ImgaeDataBlack, ref Byte[] ImgaeDataRed)
{
RecpW = 250;
RecpH = 128;
PerLineLen = RecpW / 8;
strFormat.Alignment = StringAlignment.Near; //左对齐
strFormat.LineAlignment = StringAlignment.Near;
Image img = new Bitmap(RecpW, RecpH);
Graphics g = Graphics.FromImage(img);
/****************设置图片质量 防止有噪点*****************/
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.DrawImage(img, 1, 1, RecpW, RecpH);
g.Clear(Color.White);
string[] Arrstr = Indate.Split('@');
foreach (string Temp in Arrstr)
{
Draw(g, Temp);
}
if (Indate.Length == 0)
{
Pen pen = new Pen(Color.Black, 2);
g.DrawLine(pen, 1, 0, 1, 20);
g.DrawLine(pen, 5, 0, 5, 20);
g.DrawLine(pen, 10, 0, 10, 20);
pen.Dispose();
}
Bitmap bmp = new Bitmap(RecpW, RecpH);
Graphics gg = Graphics.FromImage(bmp);
gg.DrawImage(img, 0, 0, new Rectangle(0, 0, RecpW, RecpH), GraphicsUnit.Pixel);
Bitmap mybitmap = new Bitmap(img);
Color srcColor;
int wide = mybitmap.Width;
int height = mybitmap.Height;
int Index = 0;
int posion = 0;
for (int x = 0; x < wide; x++)
{
for (int y = 0; y < height; y++)
{
//获取像素的RGB颜色值
srcColor = mybitmap.GetPixel(x, y);
if (srcColor.R == 0) //黑色
{
Index = posion / 8;
ImgaeDataBlack[Index] |= (byte)(0x80 >> (posion % 8));
}
else if (srcColor.R == 255 && srcColor.G != 255) //红色
{
Index = posion / 8;
ImgaeDataRed[Index] |= (byte)(0x80 >> (posion % 8));
}
posion++;
}
}
g.Dispose();
gg.Dispose();
return img;
}
public Byte[] CreateImageDate(string Indate)
{
strFormat.Alignment = StringAlignment.Near; //左对齐
strFormat.LineAlignment = StringAlignment.Near;
Image img = new Bitmap(RecpW, RecpH);
Graphics g = Graphics.FromImage(img);
g.DrawImage(img, 1, 1, RecpW, RecpH);
g.Clear(Color.White);
string[] Arrstr = Indate.Split('@');
foreach (string Temp in Arrstr)
{
Draw(g, Temp);
}
Bitmap bmp = new Bitmap(RecpW, RecpH);
Graphics gg = Graphics.FromImage(bmp);
gg.DrawImage(img, 0, 0, new Rectangle(0, 0, RecpW, RecpH), GraphicsUnit.Pixel);
Byte[] PrintDate = new byte[PerLineLen * RecpH];
Bitmap mybitmap = new Bitmap(img);
Color srcColor;
int wide = mybitmap.Width;
int height = mybitmap.Height;
int Index = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < wide; x++)
{
//获取像素的RGB颜色值
srcColor = mybitmap.GetPixel(x, y);
if (srcColor.R != 255)
{
Index = y * PerLineLen + x / 8;
PrintDate[Index] |= (byte)(0x80 >> (x % 8));
}
}
}
//string Hexstr = ToHexStrFromByte(PrintDate);
g.Dispose();
gg.Dispose();
return PrintDate;
}
public void Draw(Graphics g, string InData)
{
if (InData == "")
return;
SolidBrush drawbrush = sbrush;
string[] Arrstr = InData.Split('|');
if (Arrstr[0].Substring(0, 1) == "T")
{
if (Arrstr[0].Length != 16)
return;
Font font;
int FontSize = int.Parse(Arrstr[0].Substring(2, 2));
int X = int.Parse(Arrstr[0].Substring(4, 3));
int Y = int.Parse(Arrstr[0].Substring(7, 3));
int LineWeight = int.Parse(Arrstr[0].Substring(10, 3));
int LineHeight = int.Parse(Arrstr[0].Substring(13, 3));
if (Arrstr[0].Substring(1, 1) == "B")
{
font = new Font("宋体", FontSize, FontStyle.Bold);
}
else if (Arrstr[0].Substring(1, 1) == "U")
{
font = new Font("宋体", FontSize, FontStyle.Underline);
}
else
{
font = new Font("宋体", FontSize);
}
string[] Temp = Arrstr[1].Split('^');
if (Temp.Length == 1)
{
StringFormat tempstrFormat = new StringFormat();
tempstrFormat.LineAlignment = strFormat.LineAlignment;
tempstrFormat.Alignment = StringAlignment.Center;
g.DrawString(Arrstr[1] == null ? " " : Arrstr[1], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
else
{
StringFormat tempstrFormat = new StringFormat();
tempstrFormat.LineAlignment = strFormat.LineAlignment;
if (Temp.Length == 2)
{
if (Temp[0].Substring(0, 1) == "R")
{
tempstrFormat.Alignment = StringAlignment.Far;
g.DrawString(Temp[1] == null ? " " : Temp[1], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
else if (Temp[0].Substring(0, 1) == "L")
{
tempstrFormat.Alignment = StringAlignment.Near;
g.DrawString(Temp[1] == null ? " " : Temp[1], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
else
{
tempstrFormat.Alignment = StringAlignment.Center;
g.DrawString(Temp[1] == null ? " " : Temp[1], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
}
else if (Temp.Length == 3)
{
drawbrush = new SolidBrush((Color)ColorTranslator.FromHtml(Temp[1]));
if (Temp[0].Substring(0, 1) == "R")
{
tempstrFormat.Alignment = StringAlignment.Far;
g.DrawString(Temp[2] == null ? " " : Temp[2], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
else if (Temp[0].Substring(0, 1) == "L")
{
tempstrFormat.Alignment = StringAlignment.Near;
g.DrawString(Temp[2] == null ? " " : Temp[2], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
else
{
tempstrFormat.Alignment = StringAlignment.Center;
g.DrawString(Temp[2] == null ? " " : Temp[2], font, drawbrush, new Rectangle(X, Y, LineWeight, LineHeight), tempstrFormat);
}
}
}
}
else if (Arrstr[0].Substring(0, 1) == "P")
{
if (Arrstr[0].Length != 13)
return;
int X = int.Parse(Arrstr[0].Substring(1, 3));
int Y = int.Parse(Arrstr[0].Substring(4, 3));
int LineWeight = int.Parse(Arrstr[0].Substring(7, 3));
int LineHeight = int.Parse(Arrstr[0].Substring(10, 3));
if (Arrstr[1] == null)
return;
if (!System.IO.File.Exists(Arrstr[1]))
{
return;
}
Image img = Image.FromFile(Arrstr[1]);
g.DrawImage(img, new Rectangle(X, Y, LineWeight, LineHeight));
}
else if (Arrstr[0].Substring(0, 1) == "B") //一维码
{
if (Arrstr[0].Length != 13)
return;
int X = int.Parse(Arrstr[0].Substring(1, 3));
int Y = int.Parse(Arrstr[0].Substring(4, 3));
int LineWeight = int.Parse(Arrstr[0].Substring(7, 3));
int LineHeight = int.Parse(Arrstr[0].Substring(10, 3));
if (Arrstr[1] == null)
return;
//Image img = Image.FromFile(Arrstr[1]);
g.DrawImage(GetBarcodeBitmap1(Arrstr[1], LineWeight, LineHeight), new Rectangle(X, Y, LineWeight, LineHeight));
}
else if (Arrstr[0].Substring(0, 1) == "L") //画线
{
if (Arrstr[0].Length != 13)
return;
int X1 = int.Parse(Arrstr[0].Substring(1, 3));
int Y1 = int.Parse(Arrstr[0].Substring(4, 3));
int X2 = int.Parse(Arrstr[0].Substring(7, 3));
int Y2 = int.Parse(Arrstr[0].Substring(10, 3));
Pen pen = new Pen(Color.Black);
try
{
pen.Width = int.Parse(Arrstr[1]);
}
catch (Exception a)
{
}
g.DrawLine(pen, X1, Y1, X2, Y2);
}
else if (Arrstr[0].Substring(0, 1) == "Q") //二维码
{
if (Arrstr[0].Length != 13)
return;
int X = int.Parse(Arrstr[0].Substring(1, 3));
int Y = int.Parse(Arrstr[0].Substring(4, 3));
int LineWeight = int.Parse(Arrstr[0].Substring(7, 3));
int LineHeight = int.Parse(Arrstr[0].Substring(10, 3));
if (Arrstr[1] == null)
return;
g.DrawImage(GetQRCode(Arrstr[1], LineWeight, LineHeight), new Rectangle(X, Y, LineWeight, LineHeight));
}
else if (Arrstr[0].Substring(0, 1) == "V") //加载图片
{
if (Arrstr[0].Length != 13)
return;
int X = int.Parse(Arrstr[0].Substring(1, 3));
int Y = int.Parse(Arrstr[0].Substring(4, 3));
int LineWeight = int.Parse(Arrstr[0].Substring(7, 3));
int LineHeight = int.Parse(Arrstr[0].Substring(10, 3));
if (Arrstr[1] == null)
return;
Image img;
byte[] bytearr = Convert.FromBase64String(Arrstr[1]);
using (MemoryStream ms = new MemoryStream(bytearr))
{
img = Image.FromStream(ms);
}
Bitmap binaryImage = new Bitmap(img.Width, img.Height);
// 对图像进行二值化处理 抹除杂乱点
using (Graphics g1 = Graphics.FromImage(binaryImage))
{
g1.DrawImage(img, 0, 0);
// 将图像转换为黑白
for (int y = 0; y < binaryImage.Height; y++)
{
for (int x = 0; x < binaryImage.Width; x++)
{
Color pixelColor = binaryImage.GetPixel(x, y);
int averageColor = (pixelColor.R + pixelColor.G + pixelColor.B) / 3;
Color newColor = averageColor < 128 ? Color.Black : Color.White;
binaryImage.SetPixel(x, y, newColor);
}
}
}
g.DrawImage(binaryImage, new Rectangle(X, Y, LineWeight, LineHeight));
}
else if (Arrstr[0].Substring(0, 1) == "D")//画背景DXXXYYYWWWHHH|FF0000
{
if (Arrstr[0].Length != 13)
return;
int X = int.Parse(Arrstr[0].Substring(1, 3));
int Y = int.Parse(Arrstr[0].Substring(4, 3));
int LineWeight = int.Parse(Arrstr[0].Substring(7, 3));
int LineHeight = int.Parse(Arrstr[0].Substring(10, 3));
if (Arrstr[1] == null)
return;
SolidBrush brush = new SolidBrush((Color)ColorTranslator.FromHtml(Arrstr[1]));
g.FillRectangle(brush, new Rectangle(X, Y, LineWeight, LineHeight));
}
}
/// <summary>
/// 生成条形码
/// </summary>
/// <param name="barcodeContent">需要生成条码的内容</param>
/// <param name="barcodeWidth">条码宽度</param>
/// <param name="barcodeHeight">条码长度</param>
/// <returns>返回条码图形</returns>
public static Bitmap GetBarcodeBitmap(string barcodeContent, int barcodeWidth, int barcodeHeight)
{
BarcodeWriter barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.CODE_128;//设置编码格式
EncodingOptions encodingOptions = new EncodingOptions();
encodingOptions.Width = barcodeWidth;//设置宽度
encodingOptions.Height = barcodeHeight;//设置长度
encodingOptions.Margin = 0;//设置边距
encodingOptions.PureBarcode = true;
barcodeWriter.Options = encodingOptions;
Bitmap bitmap = barcodeWriter.Write(barcodeContent);
return bitmap;
}
public static Bitmap GetBarcodeBitmap1(string code, int width, int height)
{
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
b.IncludeLabel = false;
b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;//code的显示位置
//System.Drawing.Font font = new System.Drawing.Font("Arial", 25, FontStyle.Bold);//字体设置
//b.LabelFont = font;
// b.BarWidth = 6;
Image Image = b.Encode(BarcodeLib.TYPE.CODE128, code, System.Drawing.Color.Black, System.Drawing.Color.White, width, height);
Bitmap bitmap = new Bitmap(Image);
return bitmap;
}
public string ToHexStrFromByte(byte[] byteDatas)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < byteDatas.Length; i++)
{
builder.Append(string.Format("{0:X2} ", byteDatas[i]));
}
return builder.ToString().Trim();
}
public static Bitmap GetQRCode(string text, int width, int height)
{
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
DisableECI = true,//设置内容编码
CharacterSet = "UTF-8",
Width = width,//设置二维码的宽度和高度
Height = height,
Margin = 1//设置二维码的边距,单位不是固定像素
};
writer.Options = options;
Bitmap map = writer.Write(text);
return map;
}
}
}

View File

@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace JJMediSys
{
public class SocketClient
{
private Socket _clientSocket;
private IPEndPoint _serverEndPoint;
public bool Status = false;
public SocketClient(string serverIp, int serverPort)
{
_serverEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
}
public bool Connect()
{
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_clientSocket.Connect(_serverEndPoint);
Status = true;
SystemSet.logger.Info("Connected to server");
return Status;
}
catch (SocketException ex)
{
Status = false;
SystemSet.logger.Info($"Connection failed: {ex.Message}");
return Status;
}
}
public bool SendData(string data)
{
if (_clientSocket == null || !_clientSocket.Connected)
{
SystemSet.logger.Info("Not connected to server");
Status = false;
return false;
}
byte[] buffer = Encoding.UTF8.GetBytes(data);
try
{
_clientSocket.Send(buffer);
SystemSet.logger.Info($"Sent data: {data}");
return true;
}
catch (SocketException ex)
{
SystemSet.logger.Info($"Send failed: {ex.Message}");
return false;
}
}
public string ReceiveData()
{
if (_clientSocket == null || !_clientSocket.Connected)
{
SystemSet.logger.Info("Not connected to server");
Status = false;
return null;
}
byte[] buffer = new byte[1024];
try
{
int bytesReceived = _clientSocket.Receive(buffer);
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
SystemSet.logger.Info($"Received data: {receivedData}");
return receivedData;
}
catch (SocketException ex)
{
SystemSet.logger.Info($"Receive failed: {ex.Message}");
return null;
}
}
public void Disconnect()
{
if (_clientSocket != null)
{
_clientSocket.Shutdown(SocketShutdown.Both);
_clientSocket.Close();
_clientSocket = null;
SystemSet.logger.Info("Disconnected from server");
Status = false;
}
}
}
}

74
JJMediSys/cs/SqlHelper.cs Normal file
View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JJMediSys
{
class SqlHelper
{
private SQLiteDBHelper _mgr;
string file = "";
string CurDay = "";
string CreateSql = "";
public void initDB(string fileName,string mCreatSql)
{
string path = System.IO.Directory.GetCurrentDirectory();
file = string.Format($"{path}\\{fileName}", path);
bool exist = File.Exists(file);
CreateSql = mCreatSql;
if (exist != true)
{
System.IO.File.Create(file).Dispose();
OpenCon();
_mgr.CreateDB(file, CreateSql);
}
else
{
OpenCon();
}
// int Ret = OpenCon();
}
public int OpenCon()
{
this._mgr = new SQLiteDBHelper(file);
this._mgr.SetDataSource(file, null);
return 0;
}
public string GetBLEAddr(string BarCode) //通过条码号 获取盒子蓝牙地址
{
string sql = "Select MacAddr from BOXLIST where Barcode='" + BarCode + "'";
DataTable dataTable = _mgr.ExecQuery(sql);
if (dataTable == null || dataTable.Rows.Count <= 0)
return "";
return dataTable.Rows[0]["MacAddr"].ToString();
}
public void ExcuteCmd(string sql)
{
_mgr.ExecuteCommand(sql);
}
public DataTable ExcQuery(string sql)
{
DataTable dataTable = _mgr.ExecQuery(sql);
return dataTable;
}
}
}

151
JJMediSys/cs/Sqlite.cs Normal file
View File

@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JJMediSys
{
class SQLiteDBHelper
{
/// <summary>
///
/// </summary>
public string connectionString = string.Empty;
/// <summary>
///
/// </summary>
public SQLiteConnection connection = null;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dbPath">数据库文件路径</param>
public SQLiteDBHelper(string dbPath)
{
this.connectionString = "Data Source=" + dbPath;
}
/// <summary>
/// 创建数据库文件
/// </summary>
/// <param name="dbPath"></param>
public void CreateDB(string dbPath,string CreateSql)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand(connection))
{
bool ret = ExecuteCommand(CreateSql);
}
}
}
/// <summary>
/// 打开连接
/// </summary>
/// <param name="dataSource"></param>
/// <param name="password"></param>
public void SetDataSource(string dataSource, string password)
{
connectionString = string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dataSource);
connection = new SQLiteConnection(connectionString);
if (!string.IsNullOrEmpty(password))
{
//connection.SetPassword(password);
}
connection.Open();
}
#region
/// <summary>
/// 查询表
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public DataTable ExecQuery(string sqlStr)
{
DataTable dt = new DataTable();
try
{
SQLiteDataAdapter OraDa = new SQLiteDataAdapter(sqlStr, connection);
OraDa.Fill(dt);
return dt;
}
catch (SQLiteException e)
{
string s = e.Message;
return null;
}
}
/// <summary>
/// 增、删、改操作
/// </summary>
/// <param name="commandStr">sql语句</param>
/// <returns>是否成功</returns>
public bool ExecuteCommand(string sqlStr)
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlStr, connection))
{
try
{
if (cmd.ExecuteNonQuery() > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
ex.ToString();
return false;
}
}
}
/// <summary>
/// 根据查询语句,获取表中记录的条数 select count(*) from t_Developer
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public int GetRecordCount(string sqlStr)
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlStr, connection))
{
try
{
cmd.CommandText = sqlStr;
SQLiteDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
return dr.FieldCount;
}
return 0;
}
catch (Exception e)
{
e.ToString();
return 0;
}
}
}
#endregion
}
}

File diff suppressed because it is too large Load Diff