基线 SVN r240

SVN-Revision: r240
This commit is contained in:
cyf
2025-02-06 06:46:06 +00:00
commit ab56a9bcf7
5317 changed files with 902274 additions and 0 deletions
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="dbserver" value="114.116.145.208,14331" />
<add key="dbdatabase" value="lserp_ymkser" />
<add key="dbuserid" value="lserpAdmin" />
<add key="dbpassword" value="lserp110" />
</appSettings>
</configuration>
+358
View File
@@ -0,0 +1,358 @@
namespace MQTTClient
{
partial class FrmMain
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dbInfoPanel = new System.Windows.Forms.Panel();
this.subscribeBtn = new System.Windows.Forms.Button();
this.passwordBox = new System.Windows.Forms.TextBox();
this.passwordLab = new System.Windows.Forms.Label();
this.userIdBox = new System.Windows.Forms.TextBox();
this.userIdLab = new System.Windows.Forms.Label();
this.databaseBox = new System.Windows.Forms.TextBox();
this.databaseLab = new System.Windows.Forms.Label();
this.serverBox = new System.Windows.Forms.TextBox();
this.serverLab = new System.Windows.Forms.Label();
this.mainGridControl = new DevExpress.XtraGrid.GridControl();
this.mainGridView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.id = new DevExpress.XtraGrid.Columns.GridColumn();
this.title = new DevExpress.XtraGrid.Columns.GridColumn();
this.mqttServer = new DevExpress.XtraGrid.Columns.GridColumn();
this.mqttPort = new DevExpress.XtraGrid.Columns.GridColumn();
this.mqttUserName = new DevExpress.XtraGrid.Columns.GridColumn();
this.mqttPassword = new DevExpress.XtraGrid.Columns.GridColumn();
this.clientId = new DevExpress.XtraGrid.Columns.GridColumn();
this.topic = new DevExpress.XtraGrid.Columns.GridColumn();
this.connectState = new DevExpress.XtraGrid.Columns.GridColumn();
this.msg = new DevExpress.XtraGrid.Columns.GridColumn();
this.dbInfoPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.mainGridControl)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.mainGridView)).BeginInit();
this.SuspendLayout();
//
// dbInfoPanel
//
this.dbInfoPanel.Controls.Add(this.subscribeBtn);
this.dbInfoPanel.Controls.Add(this.passwordBox);
this.dbInfoPanel.Controls.Add(this.passwordLab);
this.dbInfoPanel.Controls.Add(this.userIdBox);
this.dbInfoPanel.Controls.Add(this.userIdLab);
this.dbInfoPanel.Controls.Add(this.databaseBox);
this.dbInfoPanel.Controls.Add(this.databaseLab);
this.dbInfoPanel.Controls.Add(this.serverBox);
this.dbInfoPanel.Controls.Add(this.serverLab);
this.dbInfoPanel.Dock = System.Windows.Forms.DockStyle.Top;
this.dbInfoPanel.Location = new System.Drawing.Point(0, 0);
this.dbInfoPanel.Name = "dbInfoPanel";
this.dbInfoPanel.Size = new System.Drawing.Size(1049, 85);
this.dbInfoPanel.TabIndex = 5;
//
// subscribeBtn
//
this.subscribeBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.subscribeBtn.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.subscribeBtn.Location = new System.Drawing.Point(962, 9);
this.subscribeBtn.Name = "subscribeBtn";
this.subscribeBtn.Size = new System.Drawing.Size(75, 68);
this.subscribeBtn.TabIndex = 9;
this.subscribeBtn.Text = "开始";
this.subscribeBtn.UseVisualStyleBackColor = true;
//
// passwordBox
//
this.passwordBox.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.passwordBox.Location = new System.Drawing.Point(513, 45);
this.passwordBox.Name = "passwordBox";
this.passwordBox.PasswordChar = '●';
this.passwordBox.Size = new System.Drawing.Size(250, 27);
this.passwordBox.TabIndex = 8;
//
// passwordLab
//
this.passwordLab.AutoSize = true;
this.passwordLab.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.passwordLab.Location = new System.Drawing.Point(438, 45);
this.passwordLab.Name = "passwordLab";
this.passwordLab.Size = new System.Drawing.Size(69, 25);
this.passwordLab.TabIndex = 7;
this.passwordLab.Text = "密码:";
this.passwordLab.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// userIdBox
//
this.userIdBox.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.userIdBox.Location = new System.Drawing.Point(144, 45);
this.userIdBox.Name = "userIdBox";
this.userIdBox.Size = new System.Drawing.Size(250, 27);
this.userIdBox.TabIndex = 6;
//
// userIdLab
//
this.userIdLab.AutoSize = true;
this.userIdLab.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.userIdLab.Location = new System.Drawing.Point(50, 45);
this.userIdLab.Name = "userIdLab";
this.userIdLab.Size = new System.Drawing.Size(88, 25);
this.userIdLab.TabIndex = 5;
this.userIdLab.Text = "登录名:";
this.userIdLab.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// databaseBox
//
this.databaseBox.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.databaseBox.Location = new System.Drawing.Point(513, 12);
this.databaseBox.Name = "databaseBox";
this.databaseBox.Size = new System.Drawing.Size(250, 27);
this.databaseBox.TabIndex = 4;
//
// databaseLab
//
this.databaseLab.AutoSize = true;
this.databaseLab.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.databaseLab.Location = new System.Drawing.Point(400, 12);
this.databaseLab.Name = "databaseLab";
this.databaseLab.Size = new System.Drawing.Size(107, 25);
this.databaseLab.TabIndex = 3;
this.databaseLab.Text = "数据库名:";
this.databaseLab.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// serverBox
//
this.serverBox.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.serverBox.Location = new System.Drawing.Point(144, 12);
this.serverBox.Name = "serverBox";
this.serverBox.Size = new System.Drawing.Size(250, 27);
this.serverBox.TabIndex = 2;
//
// serverLab
//
this.serverLab.AutoSize = true;
this.serverLab.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.serverLab.Location = new System.Drawing.Point(12, 12);
this.serverLab.Name = "serverLab";
this.serverLab.Size = new System.Drawing.Size(126, 25);
this.serverLab.TabIndex = 0;
this.serverLab.Text = "服务器地址:";
this.serverLab.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// mainGridControl
//
this.mainGridControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.mainGridControl.Location = new System.Drawing.Point(0, 85);
this.mainGridControl.MainView = this.mainGridView;
this.mainGridControl.Name = "mainGridControl";
this.mainGridControl.Size = new System.Drawing.Size(1049, 554);
this.mainGridControl.TabIndex = 6;
this.mainGridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.mainGridView});
//
// mainGridView
//
this.mainGridView.Appearance.HeaderPanel.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.mainGridView.Appearance.HeaderPanel.Options.UseFont = true;
this.mainGridView.Appearance.HeaderPanel.Options.UseTextOptions = true;
this.mainGridView.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
this.mainGridView.Appearance.HeaderPanel.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
this.mainGridView.Appearance.Row.Font = new System.Drawing.Font("微软雅黑", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.mainGridView.Appearance.Row.Options.UseFont = true;
this.mainGridView.Appearance.Row.Options.UseTextOptions = true;
this.mainGridView.Appearance.Row.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
this.mainGridView.Appearance.Row.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
this.mainGridView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.id,
this.title,
this.mqttServer,
this.mqttPort,
this.mqttUserName,
this.mqttPassword,
this.clientId,
this.topic,
this.connectState,
this.msg});
this.mainGridView.GridControl = this.mainGridControl;
this.mainGridView.IndicatorWidth = 60;
this.mainGridView.Name = "mainGridView";
this.mainGridView.OptionsBehavior.Editable = false;
this.mainGridView.OptionsCustomization.AllowFilter = false;
this.mainGridView.OptionsCustomization.AllowSort = false;
this.mainGridView.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
this.mainGridView.OptionsView.ShowGroupPanel = false;
//
// id
//
this.id.Caption = "序号";
this.id.FieldName = "id";
this.id.Name = "id";
this.id.Width = 30;
//
// title
//
this.title.Caption = "设备名称";
this.title.FieldName = "title";
this.title.MaxWidth = 200;
this.title.MinWidth = 150;
this.title.Name = "title";
this.title.Visible = true;
this.title.VisibleIndex = 0;
this.title.Width = 150;
//
// mqttServer
//
this.mqttServer.Caption = "连接地址";
this.mqttServer.FieldName = "mqttServer";
this.mqttServer.MaxWidth = 200;
this.mqttServer.MinWidth = 150;
this.mqttServer.Name = "mqttServer";
this.mqttServer.Visible = true;
this.mqttServer.VisibleIndex = 1;
this.mqttServer.Width = 150;
//
// mqttPort
//
this.mqttPort.Caption = "连接端口";
this.mqttPort.FieldName = "mqttPort";
this.mqttPort.MaxWidth = 200;
this.mqttPort.MinWidth = 100;
this.mqttPort.Name = "mqttPort";
this.mqttPort.Visible = true;
this.mqttPort.VisibleIndex = 2;
this.mqttPort.Width = 100;
//
// mqttUserName
//
this.mqttUserName.Caption = "登录名";
this.mqttUserName.FieldName = "mqttUserName";
this.mqttUserName.MaxWidth = 200;
this.mqttUserName.MinWidth = 150;
this.mqttUserName.Name = "mqttUserName";
this.mqttUserName.Visible = true;
this.mqttUserName.VisibleIndex = 3;
this.mqttUserName.Width = 150;
//
// mqttPassword
//
this.mqttPassword.Caption = "登录密码";
this.mqttPassword.FieldName = "mqttPassword";
this.mqttPassword.MaxWidth = 200;
this.mqttPassword.MinWidth = 150;
this.mqttPassword.Name = "mqttPassword";
this.mqttPassword.Visible = true;
this.mqttPassword.VisibleIndex = 4;
this.mqttPassword.Width = 150;
//
// clientId
//
this.clientId.Caption = "客户端编码";
this.clientId.FieldName = "clientId";
this.clientId.MaxWidth = 200;
this.clientId.MinWidth = 150;
this.clientId.Name = "clientId";
this.clientId.Visible = true;
this.clientId.VisibleIndex = 5;
this.clientId.Width = 150;
//
// topic
//
this.topic.Caption = "订阅主题";
this.topic.FieldName = "topic";
this.topic.MaxWidth = 200;
this.topic.MinWidth = 100;
this.topic.Name = "topic";
this.topic.Visible = true;
this.topic.VisibleIndex = 6;
this.topic.Width = 100;
//
// connectState
//
this.connectState.Caption = "连接状态";
this.connectState.FieldName = "connectState";
this.connectState.MaxWidth = 200;
this.connectState.MinWidth = 100;
this.connectState.Name = "connectState";
this.connectState.Visible = true;
this.connectState.VisibleIndex = 7;
this.connectState.Width = 100;
//
// msg
//
this.msg.Caption = "提示信息";
this.msg.FieldName = "msg";
this.msg.MaxWidth = 800;
this.msg.MinWidth = 400;
this.msg.Name = "msg";
this.msg.Visible = true;
this.msg.VisibleIndex = 8;
this.msg.Width = 400;
//
// FrmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1049, 639);
this.Controls.Add(this.mainGridControl);
this.Controls.Add(this.dbInfoPanel);
this.Name = "FrmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "MQTTClient";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.dbInfoPanel.ResumeLayout(false);
this.dbInfoPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.mainGridControl)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.mainGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel dbInfoPanel;
private DevExpress.XtraGrid.GridControl mainGridControl;
private DevExpress.XtraGrid.Views.Grid.GridView mainGridView;
private DevExpress.XtraGrid.Columns.GridColumn id;
private DevExpress.XtraGrid.Columns.GridColumn title;
private DevExpress.XtraGrid.Columns.GridColumn mqttServer;
private DevExpress.XtraGrid.Columns.GridColumn mqttPort;
private DevExpress.XtraGrid.Columns.GridColumn mqttUserName;
private DevExpress.XtraGrid.Columns.GridColumn mqttPassword;
private DevExpress.XtraGrid.Columns.GridColumn topic;
private DevExpress.XtraGrid.Columns.GridColumn connectState;
private DevExpress.XtraGrid.Columns.GridColumn msg;
private System.Windows.Forms.TextBox databaseBox;
private System.Windows.Forms.Label databaseLab;
private System.Windows.Forms.TextBox serverBox;
private System.Windows.Forms.Label serverLab;
private System.Windows.Forms.TextBox passwordBox;
private System.Windows.Forms.Label passwordLab;
private System.Windows.Forms.TextBox userIdBox;
private System.Windows.Forms.Label userIdLab;
private System.Windows.Forms.Button subscribeBtn;
private DevExpress.XtraGrid.Columns.GridColumn clientId;
}
}
@@ -0,0 +1,267 @@
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MQTTClient
{
public partial class FrmMain : Form
{
/// <summary>
/// 配置读取
/// </summary>
private Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
/// <summary>
/// mqtt连接字典
/// </summary>
private Dictionary<string, MqttConnect> mqttConnectDic = new Dictionary<string, MqttConnect>();
/// <summary>
/// 数据库连接
/// </summary>
private SqlHelper sqlHelper;
/// <summary>
/// 主配置数据源
/// </summary>
private DataTable sourceTable = new DataTable();
public FrmMain()
{
InitializeComponent();
this.Load += OnFrmMainLoad;
this.mainGridView.CustomDrawRowIndicator += OnCustomDrawRowIndicator;
this.subscribeBtn.Click += OnSubscribeBtnClick;
}
/// <summary>
/// 初始化时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnFrmMainLoad(object sender, EventArgs e)
{
string dbServer = configuration.AppSettings.Settings["dbserver"].Value;
string dbDatabase = configuration.AppSettings.Settings["dbdatabase"].Value;
string dbUserId = configuration.AppSettings.Settings["dbuserid"].Value;
string dbPassword = configuration.AppSettings.Settings["dbpassword"].Value;
serverBox.Text = MqttConnectModel._dbServer = dbServer;
databaseBox.Text = MqttConnectModel._dbDatabase = dbDatabase;
userIdBox.Text = MqttConnectModel._dbUserId = dbUserId;
passwordBox.Text = MqttConnectModel._dbPassword = dbPassword;
serverBox.TextChanged += OnTextChanged;
databaseBox.TextChanged += OnTextChanged;
userIdBox.TextChanged += OnTextChanged;
passwordBox.TextChanged += OnTextChanged;
MqttConnect.MainGridControl = mainGridControl;
MqttConnect.MainGridView = mainGridView;
InitGridRightMenu();
if (!InitGridAndMqttConnect())
{
this.Close();
}
}
private bool InitGridAndMqttConnect()
{
bool isInit;
try
{
string sqlConnectionStr = $"Server={MqttConnectModel._dbServer};Database={MqttConnectModel._dbDatabase};Persist Security Info=True;User ID={MqttConnectModel._dbUserId};Password={MqttConnectModel._dbPassword};Connection Timeout=5;MultipleActiveResultSets=true";
sqlHelper = new SqlHelper(new SqlConnection(sqlConnectionStr));
sourceTable = sqlHelper.ExecuteDataTable("select * from Mqtt_SubscribeMainTab");
if (!sourceTable.Columns.Contains("clientId"))
{
sourceTable.Columns.Add("clientId");
}
if (!sourceTable.Columns.Contains("connectState"))
{
sourceTable.Columns.Add("connectState");
}
if (!sourceTable.Columns.Contains("msg"))
{
sourceTable.Columns.Add("msg");
}
if (sourceTable.Columns.Contains("disenable"))
{
DataTable dataTable = sourceTable.Clone();
sourceTable.Select(string.Format("disenable <> '1'")).CopyToDataTable(dataTable, LoadOption.PreserveChanges);
sourceTable = dataTable;
}
mainGridControl.DataSource = sourceTable;
foreach (DataRow sourceRow in sourceTable.Rows)
{
string index = sourceRow["id"] + "";
MqttConnect mqttConnect = new MqttConnect(sourceRow);
mqttConnectDic.Add(index, mqttConnect);
}
isInit = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误");
isInit = false;
}
return isInit;
}
/// <summary>
/// 订阅按钮点击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void OnSubscribeBtnClick(object sender, EventArgs e)
{
subscribeBtn.Enabled = false;
try
{
foreach (string key in mqttConnectDic.Keys)
{
MqttConnect mqttConnect = mqttConnectDic[key];
await mqttConnect.Subscribe();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误");
this.subscribeBtn.Enabled = true;
}
}
/// <summary>
/// 改变数据库连接参数时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox == serverBox)
{
configuration.AppSettings.Settings["dbserver"].Value = textBox.Text;
MqttConnectModel._dbServer = textBox.Text;
}
else if (textBox == databaseBox)
{
configuration.AppSettings.Settings["dbdatabase"].Value = textBox.Text;
MqttConnectModel._dbDatabase = textBox.Text;
}
else if (textBox == userIdBox)
{
configuration.AppSettings.Settings["dbuserid"].Value = textBox.Text;
MqttConnectModel._dbUserId = textBox.Text;
}
else if (textBox == passwordBox)
{
configuration.AppSettings.Settings["dbpassword"].Value = textBox.Text;
MqttConnectModel._dbPassword = textBox.Text;
}
configuration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// 表格序号
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnCustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
{
try
{
e.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
if (e.Info.IsRowIndicator)
{
if (e.RowHandle >= 0)
{
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
}
}
catch (Exception)
{
}
}
/// <summary>
/// 右键菜单打开前判断
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuStripOpening(object sender, CancelEventArgs e)
{
Point mousePoint = mainGridControl.PointToClient(MousePosition);
GridHitInfo gridHitInfo = mainGridView.CalcHitInfo(mousePoint);
ContextMenuStrip menuStrip = (ContextMenuStrip)sender;
ToolStripMenuItem subscribeStripItem = menuStrip.Items.Cast<ToolStripMenuItem>().Where(n => n.Name.Equals("subscribeMenu")).FirstOrDefault();
ToolStripMenuItem stopStripItem = menuStrip.Items.Cast<ToolStripMenuItem>().Where(n => n.Name.Equals("stopMenu")).FirstOrDefault();
//DataRow dataRow = mainGridView.GetFocusedDataRow();
DataRow dataRow = mainGridView.GetDataRow(gridHitInfo.RowHandle);
if (dataRow != null)
{
string id = dataRow["id"] + "";
MqttConnect mqttConnect = mqttConnectDic[id];
if (subscribeStripItem != null && mqttConnect != null)
{
subscribeStripItem.Enabled = !mqttConnect.MqttSubscribeStart ? true : false;
}
if (stopStripItem != null)
{
stopStripItem.Enabled = !mqttConnect.MqttSubscribeStop ? true : false;
}
}
else
{
e.Cancel = true;
}
}
/// <summary>
/// 右键菜单点击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void OnMenuStripItemClick(object sender, EventArgs e)
{
DataRow dataRow = mainGridView.GetFocusedDataRow();
string id = dataRow["id"] + "";
MqttConnect mqttConnect = mqttConnectDic[id];
if (mqttConnect != null)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
if (menuItem.Name.Equals("subscribeMenu"))
{
await mqttConnect.Subscribe();
}
else if (menuItem.Name.Equals("stopMenu"))
{
await mqttConnect.Stop();
}
}
}
/// <summary>
/// 初始化表格右键
/// </summary>
private void InitGridRightMenu()
{
ContextMenuStrip menuStrip = new ContextMenuStrip();
menuStrip.Opening += new CancelEventHandler(MenuStripOpening);
ToolStripMenuItem subscribeMenuItem = new ToolStripMenuItem();
subscribeMenuItem.Name = "subscribeMenu";
subscribeMenuItem.Text = "订阅";
subscribeMenuItem.Click += new EventHandler(OnMenuStripItemClick);
menuStrip.Items.Add(subscribeMenuItem);
ToolStripMenuItem stopMenuItem = new ToolStripMenuItem();
stopMenuItem.Name = "stopMenu";
stopMenuItem.Text = "停止";
stopMenuItem.Click += new EventHandler(OnMenuStripItemClick);
menuStrip.Items.Add(stopMenuItem);
mainGridControl.ContextMenuStrip = menuStrip;
}
}
}
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C8445635-88C7-477B-9844-DD9E944DEA93}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>MQTTClient</RootNamespace>
<AssemblyName>MQTTClient</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="DevExpress.Data.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.Printing.v15.2.Core, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.Sparkline.v15.2.Core, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.Utils.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.XtraEditors.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.XtraGrid.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DevExpress.XtraLayout.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.XtraPrinting.v15.2, Version=15.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="MQTTnet, Version=4.3.2.930, Culture=neutral, PublicKeyToken=fdb7629f2e364a63, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.4.3.2.930\lib\net48\MQTTnet.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="FrmMain.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmMain.Designer.cs">
<DependentUpon>FrmMain.cs</DependentUpon>
</Compile>
<Compile Include="MqttConnect.cs" />
<Compile Include="MqttConnectModel.cs" />
<Compile Include="MqttDataFieldModel.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SqlHelper.cs" />
<EmbeddedResource Include="FrmMain.resx">
<DependentUpon>FrmMain.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\licenses.licx" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,307 @@
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using MQTTnet;
using MQTTnet.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MQTTClient
{
public class MqttConnect
{
/// <summary>
/// 主界面GridControl
/// </summary>
public static GridControl MainGridControl;
/// <summary>
/// 主界面GridView
/// </summary>
public static GridView MainGridView;
/// <summary>
/// 启动连接标识
/// </summary>
public bool MqttSubscribeStart;
/// <summary>
/// 终止连接标识
/// </summary>
public bool MqttSubscribeStop;
/// <summary>
/// MQTT主配置表
/// </summary>
//private readonly string mainTableName = "Mqtt_SubscribeMainTab";
/// <summary>
/// MQTT字段配置表
/// </summary>
private readonly string fieldTableName = "Mqtt_SubscribeFieldsTab";
/// <summary>
/// 数据库连接类
/// </summary>
private SqlHelper sqlHelper;
/// <summary>
/// MQTT客户端唯一Id
/// </summary>
private readonly string clientId = Guid.NewGuid().ToString().Substring(0, 13);
/// <summary>
/// MQTT客户端对象
/// </summary>
private MqttClient mqttClient = null;
/// <summary>
/// MQTT连接属性行数据
/// </summary>
private DataRow mqttDataRow = null;
/// <summary>
/// MQTT连接属性
/// </summary>
private MqttConnectModel mqttConnectModel = null;
/// <summary>
/// MQTT连接保存字段配置
/// </summary>
private List<MqttDataFieldModel> mqttDataFields = new List<MqttDataFieldModel>();
/// <summary>
/// MQTT保存业务表字段表
/// </summary>
private DataTable tempTableFields = new DataTable();
public MqttConnect(DataRow dataRow)
{
Update(dataRow);
}
public void Update(DataRow dataRow)
{
mqttDataRow = dataRow;
MainGridControl.Invoke((new Action(() =>
{
mqttDataRow["clientId"] = clientId;
})));
mqttConnectModel = new MqttConnectModel(dataRow);
sqlHelper = new SqlHelper(new SqlConnection(GetSqlConnection()));
if (!string.IsNullOrWhiteSpace(mqttConnectModel.TempTable))
{
string selectSql = $"select name from sys.columns where object_id=object_id('{mqttConnectModel.TempTable}')";
tempTableFields = sqlHelper.ExecuteDataTable(selectSql);
}
string selectDataFields = $"select * from {fieldTableName} where id = '{mqttConnectModel.Id}'";
DataTable dataFieldsTable = sqlHelper.ExecuteDataTable(selectDataFields);
mqttDataFields.Clear();
foreach (DataRow dataFieldRow in dataFieldsTable.Rows)
{
MqttDataFieldModel mqttDataFieldModel = new MqttDataFieldModel(dataFieldRow);
if (!string.IsNullOrWhiteSpace(mqttDataFieldModel.FieldName) && tempTableFields.Rows.Cast<DataRow>().Where(n => (n["name"] + "").Equals(mqttDataFieldModel.FieldName)).Count() > 0)
{
mqttDataFields.Add(mqttDataFieldModel);
}
}
}
#region
/// <summary>
/// 连接mqtt服务器
/// </summary>
/// <returns></returns>
private async Task<bool> ConnectionMqttServerAsync()
{
bool isConnect = false;
if (mqttClient == null)
{
var mqttFactory = new MqttFactory();
mqttClient = mqttFactory.CreateMqttClient() as MqttClient;
mqttClient.ConnectedAsync += OnConnectedAsync;
mqttClient.DisconnectedAsync += OnDisconnectedAsync;
mqttClient.ApplicationMessageReceivedAsync += OnApplicationMessageReceivedAsync;
}
try
{
var options = new MqttClientOptions
{
ClientId = clientId,
ProtocolVersion = MQTTnet.Formatter.MqttProtocolVersion.V500,
ChannelOptions = new MqttClientTcpOptions
{
Server = mqttConnectModel.MqttServer,
Port = mqttConnectModel.MqttPort,
}
};
options.CleanSession = true;
options.Credentials = new MqttClientCredentials(mqttConnectModel.MqttUserName, Encoding.UTF8.GetBytes(mqttConnectModel.MqttPassword));
await mqttClient.ConnectAsync(options);
isConnect = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
isConnect = false;
}
return isConnect;
}
/// <summary>
/// 订阅主题
/// </summary>
public async Task Subscribe(bool isConnect = false)
{
MqttSubscribeStart = true;
MqttSubscribeStop = false;
if (!isConnect)
{
MainGridControl.Invoke(new Action(() =>
{
mqttDataRow["connectState"] = "";
mqttDataRow["msg"] = "正在连接Mqtt服务器";
}));
isConnect = await ConnectionMqttServerAsync();
}
if (isConnect)
{
MainGridControl.Invoke(new Action(() =>
{
mqttDataRow["connectState"] = "已连接";
}));
string topic = mqttConnectModel.Topic;
if (string.IsNullOrEmpty(topic))
{
MainGridControl.Invoke(new Action(() =>
{
mqttDataRow["msg"] = "订阅主题不能为空";
}));
MqttSubscribeStart = false;
return;
}
await mqttClient.SubscribeAsync(topic);
//订阅成功
MainGridControl.Invoke(new Action(() =>
{
mqttDataRow["msg"] = $"订阅主题{topic}成功";
}));
}
}
/// <summary>
/// 停止连接
/// </summary>
public async Task Stop()
{
MqttSubscribeStop = true;
if (mqttClient.IsConnected)
{
bool isDisconnect = await mqttClient.TryDisconnectAsync();
if (isDisconnect)
{
MqttSubscribeStart = true;
MainGridControl.Invoke((new Action(() =>
{
mqttDataRow["msg"] = "已断开连接";
})));
}
}
else
{
MainGridControl.Invoke((new Action(() =>
{
mqttDataRow["msg"] = "正在停止连接,请稍候";
})));
}
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns></returns>
private string GetSqlConnection()
{
return string.Format("Server={0};Database={1};Persist Security Info=True;User ID={2};Password={3};Connection Timeout=5;MultipleActiveResultSets=true", mqttConnectModel.DbServer, mqttConnectModel.DbDatabase, mqttConnectModel.DbUserId, mqttConnectModel.DbPassword);
}
#endregion
#region
/// <summary>
/// 断开mqtt连接
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
private async Task OnDisconnectedAsync(MqttClientDisconnectedEventArgs arg)
{
MainGridControl.Invoke((new Action(() =>
{
mqttDataRow["connectState"] = "已断开";
mqttDataRow["msg"] = "已断开连接";
})));
if (MqttSubscribeStart && !MqttSubscribeStop && !mqttClient.IsConnected)
{
MainGridControl.Invoke((new Action(() =>
{
mqttDataRow["msg"] = "连接失败,正在尝试重新连接";
})));
bool isConnect = await ConnectionMqttServerAsync();
if (isConnect)
{
await Subscribe(isConnect);
}
}
else if (MqttSubscribeStart && MqttSubscribeStop && !mqttClient.IsConnected)
{
MqttSubscribeStart = false;
}
}
/// <summary>
/// 连接mqtt服务
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
private Task OnConnectedAsync(MqttClientConnectedEventArgs arg)
{
MainGridControl.Invoke((new Action(() =>
{
mqttDataRow["msg"] = "已连接到MQTT服务器";
})));
return Task.CompletedTask;
}
/// <summary>
/// 接收订阅消息
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
private Task OnApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
string messageReceive = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment.ToArray());
//string messageReceive = jsonStr;
if (string.IsNullOrWhiteSpace(messageReceive))
{
return Task.CompletedTask;
}
using (SqlConnection sqlConnection = new SqlConnection(GetSqlConnection()))
{
sqlConnection.Open();
using (var bulkCopy = new SqlBulkCopy(sqlConnection))
{
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(messageReceive);
bulkCopy.DestinationTableName = mqttConnectModel.TempTable;
bulkCopy.BulkCopyTimeout = 0;
try
{
bulkCopy.ColumnMappings.Clear();
foreach (MqttDataFieldModel dataFieldModel in mqttDataFields)
{
string receiveFieldName = !string.IsNullOrWhiteSpace(dataFieldModel.ReceiveFieldName) ? dataFieldModel.ReceiveFieldName : dataFieldModel.FieldName;
if (dataTable.Columns.Contains(receiveFieldName))
{
bulkCopy.ColumnMappings.Add(receiveFieldName, dataFieldModel.FieldName);
}
}
bulkCopy.WriteToServer(dataTable);
}
catch (Exception ex)
{
MainGridControl.Invoke((new Action(() =>
{
string exMsg = ex != null ? ex.Message : "";
string innerMsg = ex != null && ex.InnerException != null ? ex.InnerException.Message : "";
mqttDataRow["msg"] = $"保存数据失败,原因:{exMsg},{innerMsg}";
})));
}
}
}
return Task.CompletedTask;
}
#endregion
}
}
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MQTTClient
{
public class MqttConnectModel
{
private string _id;
public static string _dbServer;
public static string _dbDatabase;
public static string _dbUserId;
public static string _dbPassword;
private string _mqttServer;
private int _mqttPort;
private string _mqttUserName;
private string _mqttPassword;
private string _topic;
private string _tempTable;
public string Id
{
get { return _id; }
set { _id = value; }
}
public string MqttServer
{
get { return _mqttServer; }
set { _mqttServer = value; }
}
public int MqttPort
{
get { return _mqttPort; }
set { _mqttPort = value; }
}
public string MqttUserName
{
get { return _mqttUserName; }
set { _mqttUserName = value; }
}
public string MqttPassword
{
get { return _mqttPassword; }
set { _mqttPassword = value; }
}
public string DbServer
{
get { return _dbServer; }
set { _dbServer = value; }
}
public string DbDatabase
{
get { return _dbDatabase; }
set { _dbDatabase = value; }
}
public string DbUserId
{
get { return _dbUserId; }
set { _dbUserId = value; }
}
public string DbPassword
{
get { return _dbPassword; }
set { _dbPassword = value; }
}
public string Topic
{
get { return _topic; }
set { _topic = value; }
}
public string TempTable
{
get { return _tempTable; }
set { _tempTable = value; }
}
public MqttConnectModel(DataRow dataRow)
{
Update(dataRow);
}
public void Update(DataRow dataRow)
{
_id = dataRow != null && dataRow.Table.Columns.Contains("id") && dataRow["id"] != null ? dataRow["id"].ToString() : "";
_mqttServer = dataRow != null && dataRow.Table.Columns.Contains("mqttServer") && dataRow["mqttServer"] != null ? dataRow["mqttServer"].ToString() : "";
_mqttPort = dataRow != null && dataRow.Table.Columns.Contains("mqttPort") && dataRow["mqttPort"] != null && int.TryParse(dataRow["mqttPort"].ToString(), out _mqttPort) ? _mqttPort : 0;
_mqttUserName = dataRow != null && dataRow.Table.Columns.Contains("mqttUserName") && dataRow["mqttUserName"] != null ? dataRow["mqttUserName"].ToString() : "";
_mqttPassword = dataRow != null && dataRow.Table.Columns.Contains("mqttPassword") && dataRow["mqttPassword"] != null ? dataRow["mqttPassword"].ToString() : "";
//_dbServer = dataRow != null && dataRow.Table.Columns.Contains("dbServer") && dataRow["dbServer"] != null ? dataRow["dbServer"].ToString() : "";
//_dbDatabase = dataRow != null && dataRow.Table.Columns.Contains("dbDatabase") && dataRow["dbDatabase"] != null ? dataRow["dbDatabase"].ToString() : "";
//_dbUserId = dataRow != null && dataRow.Table.Columns.Contains("dbUserId") && dataRow["dbUserId"] != null ? dataRow["dbUserId"].ToString() : "";
//_dbPassword = dataRow != null && dataRow.Table.Columns.Contains("dbPassword") && dataRow["dbPassword"] != null ? dataRow["dbPassword"].ToString() : "";
_topic = dataRow != null && dataRow.Table.Columns.Contains("topic") && dataRow["topic"] != null ? dataRow["topic"].ToString() : "";
_tempTable = dataRow != null && dataRow.Table.Columns.Contains("tempTable") && dataRow["tempTable"] != null ? dataRow["tempTable"].ToString() : "";
}
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MQTTClient
{
public class MqttDataFieldModel
{
private string _id;
private string _fieldName;
private string _receiveFieldName;
public string Id
{
get { return _id; }
set { _id = value; }
}
public string FieldName
{
get { return _fieldName; }
set { _fieldName = value; }
}
public string ReceiveFieldName
{
get { return _receiveFieldName; }
set { _receiveFieldName = value; }
}
public MqttDataFieldModel(DataRow dataRow)
{
Update(dataRow);
}
public void Update(DataRow dataRow)
{
_id = dataRow != null && dataRow.Table.Columns.Contains("id") && dataRow["id"] != null ? dataRow["id"].ToString() : "";
_fieldName = dataRow != null && dataRow.Table.Columns.Contains("fieldName") && dataRow["fieldName"] != null ? dataRow["fieldName"].ToString() : "";
_receiveFieldName = dataRow != null && dataRow.Table.Columns.Contains("receiveFieldName") && dataRow["receiveFieldName"] != null ? dataRow["receiveFieldName"].ToString() : "";
}
}
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MQTTClient
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("MQTTClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MQTTClient")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c8445635-88c7-477b-9844-dd9e944dea93")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MQTTClient.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MQTTClient.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,29 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MQTTClient.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,603 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace MQTTClient
{
public class SqlHelper
{ /// <summary>
/// 数据连接
/// </summary>
public SqlConnection Connection;
/// <summary>
/// 请求超时时间
/// </summary>
public int CommandTimeout;
public SqlHelper(SqlConnection connection)
{
this.Connection = connection;
this.Connection.Open();
}
#region ExecuteAdapter
/// <summary>
/// <para>说明:获取适配器</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>SqlDataAdapter.</returns>
public SqlDataAdapter ExecuteAdapter(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlDataAdapter adapter;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, commandParameters);
adapter = new SqlDataAdapter(cmd);
}
catch
{
throw;
}
return adapter;
}
/// <summary>
/// <para>说明:获取适配器</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>SqlDataAdapter.</returns>
public SqlDataAdapter ExecuteAdapter(CommandType cmdType, string cmdText)
{
SqlDataAdapter adapter;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, null);
adapter = new SqlDataAdapter(cmd);
}
catch
{
throw;
}
return adapter;
}
#endregion
#region ExecuteDataTable
/// <summary>
/// <para>说明:执行sql返回DataTable</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>DataTable.</returns>
public DataTable ExecuteDataTable(string cmdText)
{
DataTable dataTable = null;
try
{
dataTable = ExecuteDataSet(cmdText).Tables[0];
}
catch (Exception)
{
}
return dataTable;
}
/// <summary>
/// <para>说明:执行sql返回DataTable</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>DataTable.</returns>
public DataTable ExecuteDataTable(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(CommandType.Text, cmdText, "temp", commandParameters).Tables[0];
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public object ExecuteObject(string fieldName, string cmdText)
{
object result = null;
try
{
result = ExecuteDataSet(cmdText).Tables[0].Rows[0][fieldName];
}
catch (Exception)
{
}
return result;
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-27 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Object.</returns>
public object ExecuteObject(string fieldName, string cmdText, params SqlParameter[] commandParameters)
{
object result = null;
try
{
result = ExecuteDataSet(CommandType.Text, cmdText, "temp", commandParameters).Tables[0].Rows[0][fieldName];
}
catch (Exception)
{
}
return result;
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public string ExecuteString(string fieldName, string cmdText)
{
object obj = ExecuteObject(fieldName, cmdText);
return obj == null ? "" : obj.ToString();
}
/// <summary>
/// <para>说明:执行sql返回指定字段值</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-27 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.String.</returns>
public string ExecuteString(string fieldName, string cmdText, params SqlParameter[] commandParameters)
{
object obj = ExecuteObject(fieldName, cmdText, commandParameters);
return obj == null ? "" : obj.ToString();
}
#endregion
#region ExecuteDataSet
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="tabName">Name of the tab.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>DataSet.</returns>
public DataSet ExecuteDataSet(int cmdType, string cmdText, string tabName, params SqlParameter[] commandParameters)
{
CommandType _cmdType = CommandType.Text;
switch (cmdType)
{
case 4:
_cmdType = CommandType.StoredProcedure;
break;
case 512:
_cmdType = CommandType.TableDirect;
break;
}
return ExecuteDataSet(_cmdType, cmdText, tabName, commandParameters);
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">语句类型存储过程或者sql语句</param>
/// <param name="cmdText">执行内容</param>
/// <param name="tabName">表名</param>
/// <param name="commandParameters">参数</param>
/// <returns>DataSet.</returns>
public DataSet ExecuteDataSet(CommandType cmdType, string cmdText, string tabName, params SqlParameter[] commandParameters)
{
DataSet set2;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, commandParameters);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tabName);
//adapter.FillSchema(dataSet, SchemaType.Mapped, tabName);
set2 = dataSet;
}
catch (Exception e)
{
if (e.Message.StartsWith("在从服务器接收结果时发生传输级错误") ||
e.Message.StartsWith("在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误") ||
e.Message.StartsWith("在向服务器发送请求时发生传输级错误"))
{
throw new Exception("无法连接服务器,请检查网络连接.");
}
else
{
throw;
}
}
finally
{
cmd.Dispose();
}
return set2;
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">语句类型存储过程或者sql语句</param>
/// <param name="cmdText">执行内容</param>
/// <param name="tabName">表名</param>
/// <returns>DataSet.</returns>
public DataSet ExecuteDataSet(CommandType cmdType, string cmdText, string tabName)
{
return ExecuteDataSet(cmdType, cmdText, tabName, null);
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">执行内容</param>
/// <returns>DataSet.</returns>
public DataSet ExecuteDataSet(string cmdText)
{
return ExecuteDataSet(CommandType.Text, cmdText, "temp");
}
/// <summary>
/// <para>说明:查询结果集</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="procedureName">Name of the procedure.</param>
/// <param name="tabName">表名</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="parameterValues">The parameter values.</param>
/// <returns>DataSet.</returns>
public DataSet ExecuteDataSet(string procedureName, string tabName, string[] parameterNames, object[] parameterValues)
{
DataSet set2;
try
{
SqlCommand cmd = new SqlCommand(procedureName, Connection);
cmd.CommandType = CommandType.StoredProcedure;
if (parameterNames != null && parameterValues != null)
{
for (int i = 0; i < parameterNames.Length && i < parameterValues.Length; i++)
{
cmd.Parameters.AddWithValue(parameterNames[i], parameterValues[i]);
}
}
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tabName);
set2 = dataSet;
}
catch
{
throw;
}
return set2;
}
#endregion
#region ExecuteNonQuery
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Int32.</returns>
public int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
int num = 0;
try
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, commandParameters);
num = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception e)
{
if (e.Message.StartsWith("在从服务器接收结果时发生传输级错误") ||
e.Message.StartsWith("在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误") ||
e.Message.StartsWith("在向服务器发送请求时发生传输级错误"))
{
throw new Exception("无法连接服务器,请检查网络连接.");
}
else
{
throw;
}
}
finally
{
cmd.Dispose();
}
return num;
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Int32.</returns>
public int ExecuteNonQuery(CommandType cmdType, string cmdText)
{
return ExecuteNonQuery(CommandType.Text, cmdText, null);
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Int32.</returns>
public int ExecuteNonQuery(string cmdText)
{
return ExecuteNonQuery(CommandType.Text, cmdText);
}
#endregion
#region ExecuteReader
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集(只读、只进)</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>SqlDataReader.</returns>
public SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlDataReader reader2;
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, commandParameters);
SqlDataReader reader = cmd.ExecuteReader();
cmd.Parameters.Clear();
reader2 = reader;
}
catch
{
throw;
}
return reader2;
}
#endregion
#region ExecuteScalar
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="Connectionection">The connectionection.</param>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Object.</returns>
public object ExecuteScalar(SqlConnection Connectionection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, Connectionection, null, cmdType, cmdText, commandParameters);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="commandParameters">The command parameters.</param>
/// <returns>System.Object.</returns>
public object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, commandParameters);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public object ExecuteScalar(CommandType cmdType, string cmdText)
{
SqlCommand cmd = new SqlCommand();
{
PrepareCommand(cmd, Connection, null, cmdType, cmdText, null);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
}
/// <summary>
/// <para>说明:执行sql语句或者存储过程并返回结果集第一行第一列</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-21 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmdText">The command text.</param>
/// <returns>System.Object.</returns>
public object ExecuteScalar(string cmdText)
{
SqlCommand cmd = new SqlCommand();
{
PrepareCommand(cmd, Connection, null, CommandType.Text, cmdText, null);
object obj2 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return obj2;
}
}
#endregion
#region PrepareCommand
/// <summary>
/// <para>说明: sql参数处理</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-07-24 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="cmd">The command.</param>
/// <param name="Connection">The connection.</param>
/// <param name="trans">The trans.</param>
/// <param name="cmdType">Type of the command.</param>
/// <param name="cmdText">The command text.</param>
/// <param name="cmdParms">The command parms.</param>
private void PrepareCommand(SqlCommand cmd, SqlConnection Connection, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
}
cmd.Connection = Connection;
cmd.CommandTimeout = CommandTimeout;
cmd.CommandText = cmdText;
if (trans != null)
{
cmd.Transaction = trans;
}
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
}
#endregion
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MQTTnet" version="4.3.2.930" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
</packages>