diff --git a/MES_PLC_Control.sln b/MES_PLC_Control.sln new file mode 100644 index 0000000..0557977 --- /dev/null +++ b/MES_PLC_Control.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.12.35527.113 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MES_PLC_Control", "WindowsFormsApp1\MES_PLC_Control.csproj", "{81A4C6F2-1D92-4791-A23E-BF8792781B0D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/WindowsFormsApp1/App.config b/WindowsFormsApp1/App.config new file mode 100644 index 0000000..7c0a716 --- /dev/null +++ b/WindowsFormsApp1/App.config @@ -0,0 +1,17 @@ + + + + +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/WindowsFormsApp1/MES_PLC_Control.csproj b/WindowsFormsApp1/MES_PLC_Control.csproj new file mode 100644 index 0000000..243cd9e --- /dev/null +++ b/WindowsFormsApp1/MES_PLC_Control.csproj @@ -0,0 +1,186 @@ + + + + + Debug + AnyCPU + {81A4C6F2-1D92-4791-A23E-BF8792781B0D} + WinExe + WindowsFormsApp1 + WindowsFormsApp1 + v4.8 + 512 + true + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\HslCommunication.7.0.1\lib\net451\HslCommunication.dll + + + ..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + Form + + + FLOW_Manage.cs + + + Form + + + LINE_Manage.cs + + + Form + + + PLCADDRESS_Manage.cs + + + Form + + + PLC_Manage.cs + + + Form + + + USER_ChangeP.cs + + + Form + + + MainForm.cs + + + Form + + + LoginForm.cs + + + Form + + + MES_URL.cs + + + + + + + + + + + + + Form + + + USER_Manage.cs + + + + + + + FLOW_Manage.cs + + + LINE_Manage.cs + + + PLCADDRESS_Manage.cs + + + PLC_Manage.cs + + + USER_ChangeP.cs + + + USER_Manage.cs + + + MainForm.cs + + + LoginForm.cs + + + MES_URL.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + Always + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + + + + \ No newline at end of file diff --git a/WindowsFormsApp1/MainForm.Designer.cs b/WindowsFormsApp1/MainForm.Designer.cs new file mode 100644 index 0000000..b9167da --- /dev/null +++ b/WindowsFormsApp1/MainForm.Designer.cs @@ -0,0 +1,494 @@ +namespace WindowsFormsApp1 +{ + partial class MainForm + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows 窗体设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.用户管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.修改密码ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.切换用户ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.用户管理ToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.产线管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.pLC管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.pLC通讯设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.pLC地址设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.流程管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.mES接口配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.扫码枪配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.扫码枪配置ToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.扭力曲线配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.系统参数配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); + this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + this.label4 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.label6 = new System.Windows.Forms.Label(); + this.label7 = new System.Windows.Forms.Label(); + this.label8 = new System.Windows.Forms.Label(); + this.开始处理 = new System.Windows.Forms.Button(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.richTextBox1 = new System.Windows.Forms.RichTextBox(); + this.操作页面 = new System.Windows.Forms.GroupBox(); + this.menuStrip1.SuspendLayout(); + this.tableLayoutPanel1.SuspendLayout(); + this.groupBox1.SuspendLayout(); + this.tableLayoutPanel3.SuspendLayout(); + this.tableLayoutPanel2.SuspendLayout(); + this.groupBox3.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip1 + // + this.menuStrip1.Font = new System.Drawing.Font("Microsoft YaHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.menuStrip1.ImageScalingSize = new System.Drawing.Size(24, 24); + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.用户管理ToolStripMenuItem, + this.产线管理ToolStripMenuItem, + this.pLC管理ToolStripMenuItem, + this.流程管理ToolStripMenuItem, + this.mES接口配置ToolStripMenuItem, + this.扫码枪配置ToolStripMenuItem, + this.系统参数配置ToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 1, 0, 1); + this.menuStrip1.Size = new System.Drawing.Size(1826, 27); + this.menuStrip1.TabIndex = 0; + this.menuStrip1.Text = "menuStrip1"; + // + // 用户管理ToolStripMenuItem + // + this.用户管理ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.修改密码ToolStripMenuItem, + this.切换用户ToolStripMenuItem, + this.用户管理ToolStripMenuItem1}); + this.用户管理ToolStripMenuItem.Name = "用户管理ToolStripMenuItem"; + this.用户管理ToolStripMenuItem.Size = new System.Drawing.Size(86, 25); + this.用户管理ToolStripMenuItem.Text = "用户管理"; + // + // 修改密码ToolStripMenuItem + // + this.修改密码ToolStripMenuItem.Name = "修改密码ToolStripMenuItem"; + this.修改密码ToolStripMenuItem.Size = new System.Drawing.Size(144, 26); + this.修改密码ToolStripMenuItem.Text = "修改密码"; + this.修改密码ToolStripMenuItem.Click += new System.EventHandler(this.修改密码ToolStripMenuItem_Click); + // + // 切换用户ToolStripMenuItem + // + this.切换用户ToolStripMenuItem.Name = "切换用户ToolStripMenuItem"; + this.切换用户ToolStripMenuItem.Size = new System.Drawing.Size(144, 26); + this.切换用户ToolStripMenuItem.Text = "切换用户"; + this.切换用户ToolStripMenuItem.Click += new System.EventHandler(this.切换用户ToolStripMenuItem_Click); + // + // 用户管理ToolStripMenuItem1 + // + this.用户管理ToolStripMenuItem1.Name = "用户管理ToolStripMenuItem1"; + this.用户管理ToolStripMenuItem1.Size = new System.Drawing.Size(144, 26); + this.用户管理ToolStripMenuItem1.Text = "用户管理"; + this.用户管理ToolStripMenuItem1.Click += new System.EventHandler(this.用户管理ToolStripMenuItem1_Click); + // + // 产线管理ToolStripMenuItem + // + this.产线管理ToolStripMenuItem.Name = "产线管理ToolStripMenuItem"; + this.产线管理ToolStripMenuItem.Size = new System.Drawing.Size(86, 25); + this.产线管理ToolStripMenuItem.Text = "产线管理"; + this.产线管理ToolStripMenuItem.Click += new System.EventHandler(this.产线管理ToolStripMenuItem_Click); + // + // pLC管理ToolStripMenuItem + // + this.pLC管理ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.pLC通讯设置ToolStripMenuItem, + this.pLC地址设置ToolStripMenuItem}); + this.pLC管理ToolStripMenuItem.Name = "pLC管理ToolStripMenuItem"; + this.pLC管理ToolStripMenuItem.Size = new System.Drawing.Size(83, 25); + this.pLC管理ToolStripMenuItem.Text = "PLC管理"; + // + // pLC通讯设置ToolStripMenuItem + // + this.pLC通讯设置ToolStripMenuItem.Name = "pLC通讯设置ToolStripMenuItem"; + this.pLC通讯设置ToolStripMenuItem.Size = new System.Drawing.Size(173, 26); + this.pLC通讯设置ToolStripMenuItem.Text = "PLC通讯设置"; + this.pLC通讯设置ToolStripMenuItem.Click += new System.EventHandler(this.pLC通讯设置ToolStripMenuItem_Click); + // + // pLC地址设置ToolStripMenuItem + // + this.pLC地址设置ToolStripMenuItem.Name = "pLC地址设置ToolStripMenuItem"; + this.pLC地址设置ToolStripMenuItem.Size = new System.Drawing.Size(173, 26); + this.pLC地址设置ToolStripMenuItem.Text = "PLC地址设置"; + this.pLC地址设置ToolStripMenuItem.Click += new System.EventHandler(this.pLC地址设置ToolStripMenuItem_Click); + // + // 流程管理ToolStripMenuItem + // + this.流程管理ToolStripMenuItem.Name = "流程管理ToolStripMenuItem"; + this.流程管理ToolStripMenuItem.Size = new System.Drawing.Size(86, 25); + this.流程管理ToolStripMenuItem.Text = "流程管理"; + this.流程管理ToolStripMenuItem.Click += new System.EventHandler(this.流程管理ToolStripMenuItem_Click); + // + // mES接口配置ToolStripMenuItem + // + this.mES接口配置ToolStripMenuItem.Name = "mES接口配置ToolStripMenuItem"; + this.mES接口配置ToolStripMenuItem.Size = new System.Drawing.Size(120, 25); + this.mES接口配置ToolStripMenuItem.Text = "MES接口配置"; + this.mES接口配置ToolStripMenuItem.Click += new System.EventHandler(this.mES接口配置ToolStripMenuItem_Click); + // + // 扫码枪配置ToolStripMenuItem + // + this.扫码枪配置ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.扫码枪配置ToolStripMenuItem1, + this.扭力曲线配置ToolStripMenuItem}); + this.扫码枪配置ToolStripMenuItem.Name = "扫码枪配置ToolStripMenuItem"; + this.扫码枪配置ToolStripMenuItem.Size = new System.Drawing.Size(118, 25); + this.扫码枪配置ToolStripMenuItem.Text = "外围设备配置"; + // + // 扫码枪配置ToolStripMenuItem1 + // + this.扫码枪配置ToolStripMenuItem1.Name = "扫码枪配置ToolStripMenuItem1"; + this.扫码枪配置ToolStripMenuItem1.Size = new System.Drawing.Size(176, 26); + this.扫码枪配置ToolStripMenuItem1.Text = "扫码枪配置"; + // + // 扭力曲线配置ToolStripMenuItem + // + this.扭力曲线配置ToolStripMenuItem.Name = "扭力曲线配置ToolStripMenuItem"; + this.扭力曲线配置ToolStripMenuItem.Size = new System.Drawing.Size(176, 26); + this.扭力曲线配置ToolStripMenuItem.Text = "扭力曲线配置"; + // + // 系统参数配置ToolStripMenuItem + // + this.系统参数配置ToolStripMenuItem.Name = "系统参数配置ToolStripMenuItem"; + this.系统参数配置ToolStripMenuItem.Size = new System.Drawing.Size(118, 25); + this.系统参数配置ToolStripMenuItem.Text = "系统参数配置"; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel1.ColumnCount = 1; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.groupBox3, 0, 2); + this.tableLayoutPanel1.Controls.Add(this.操作页面, 0, 1); + this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 30); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 3; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.28571F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 42.85714F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 42.85714F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1802, 996); + this.tableLayoutPanel1.TabIndex = 6; + // + // groupBox1 + // + this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.groupBox1.Controls.Add(this.tableLayoutPanel3); + this.groupBox1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox1.Location = new System.Drawing.Point(2, 2); + this.groupBox1.Margin = new System.Windows.Forms.Padding(2); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Padding = new System.Windows.Forms.Padding(2); + this.groupBox1.Size = new System.Drawing.Size(1798, 138); + this.groupBox1.TabIndex = 4; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "处理界面"; + // + // tableLayoutPanel3 + // + this.tableLayoutPanel3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel3.ColumnCount = 4; + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 1F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 8F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 1F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F)); + this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel2, 3, 0); + this.tableLayoutPanel3.Controls.Add(this.开始处理, 1, 1); + this.tableLayoutPanel3.Location = new System.Drawing.Point(10, 24); + this.tableLayoutPanel3.Name = "tableLayoutPanel3"; + this.tableLayoutPanel3.RowCount = 3; + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel3.Size = new System.Drawing.Size(1783, 108); + this.tableLayoutPanel3.TabIndex = 4; + // + // tableLayoutPanel2 + // + this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel2.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; + this.tableLayoutPanel2.ColumnCount = 5; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.Controls.Add(this.label4, 3, 0); + this.tableLayoutPanel2.Controls.Add(this.label3, 2, 0); + this.tableLayoutPanel2.Controls.Add(this.label2, 1, 0); + this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0); + this.tableLayoutPanel2.Controls.Add(this.label5, 0, 1); + this.tableLayoutPanel2.Controls.Add(this.label6, 1, 1); + this.tableLayoutPanel2.Controls.Add(this.label7, 2, 1); + this.tableLayoutPanel2.Controls.Add(this.label8, 3, 1); + this.tableLayoutPanel2.Location = new System.Drawing.Point(179, 3); + this.tableLayoutPanel2.Name = "tableLayoutPanel2"; + this.tableLayoutPanel2.RowCount = 2; + this.tableLayoutPanel3.SetRowSpan(this.tableLayoutPanel2, 3); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel2.Size = new System.Drawing.Size(1601, 102); + this.tableLayoutPanel2.TabIndex = 3; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Dock = System.Windows.Forms.DockStyle.Fill; + this.label4.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label4.Location = new System.Drawing.Point(964, 1); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(313, 49); + this.label4.TabIndex = 6; + this.label4.Text = "label4"; + this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Dock = System.Windows.Forms.DockStyle.Fill; + this.label3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label3.Location = new System.Drawing.Point(644, 1); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(313, 49); + this.label3.TabIndex = 5; + this.label3.Text = "label3"; + this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Dock = System.Windows.Forms.DockStyle.Fill; + this.label2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label2.Location = new System.Drawing.Point(324, 1); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(313, 49); + this.label2.TabIndex = 4; + this.label2.Text = "label2"; + this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Dock = System.Windows.Forms.DockStyle.Fill; + this.label1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label1.Location = new System.Drawing.Point(4, 1); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(313, 49); + this.label1.TabIndex = 3; + this.label1.Text = "label1"; + this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Dock = System.Windows.Forms.DockStyle.Fill; + this.label5.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label5.Location = new System.Drawing.Point(4, 51); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(313, 50); + this.label5.TabIndex = 7; + this.label5.Text = "label5"; + this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Dock = System.Windows.Forms.DockStyle.Fill; + this.label6.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label6.Location = new System.Drawing.Point(324, 51); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(313, 50); + this.label6.TabIndex = 8; + this.label6.Text = "label6"; + this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Dock = System.Windows.Forms.DockStyle.Fill; + this.label7.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label7.Location = new System.Drawing.Point(644, 51); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(313, 50); + this.label7.TabIndex = 9; + this.label7.Text = "label7"; + this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Dock = System.Windows.Forms.DockStyle.Fill; + this.label8.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label8.Location = new System.Drawing.Point(964, 51); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(313, 50); + this.label8.TabIndex = 10; + this.label8.Text = "label8"; + this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // 开始处理 + // + this.开始处理.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); + this.开始处理.Dock = System.Windows.Forms.DockStyle.Fill; + this.开始处理.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.开始处理.Location = new System.Drawing.Point(19, 12); + this.开始处理.Margin = new System.Windows.Forms.Padding(2); + this.开始处理.Name = "开始处理"; + this.开始处理.Size = new System.Drawing.Size(138, 82); + this.开始处理.TabIndex = 1; + this.开始处理.Text = "开始处理"; + this.开始处理.UseVisualStyleBackColor = false; + this.开始处理.Click += new System.EventHandler(this.开始处理_Click); + // + // groupBox3 + // + this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.groupBox3.Controls.Add(this.richTextBox1); + this.groupBox3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox3.Location = new System.Drawing.Point(2, 570); + this.groupBox3.Margin = new System.Windows.Forms.Padding(2); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Padding = new System.Windows.Forms.Padding(2); + this.groupBox3.Size = new System.Drawing.Size(1798, 424); + this.groupBox3.TabIndex = 6; + this.groupBox3.TabStop = false; + this.groupBox3.Text = "日志页面"; + // + // richTextBox1 + // + this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.richTextBox1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.richTextBox1.Location = new System.Drawing.Point(10, 24); + this.richTextBox1.Name = "richTextBox1"; + this.richTextBox1.Size = new System.Drawing.Size(1783, 395); + this.richTextBox1.TabIndex = 0; + this.richTextBox1.Text = ""; + // + // 操作页面 + // + this.操作页面.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.操作页面.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.操作页面.Location = new System.Drawing.Point(2, 144); + this.操作页面.Margin = new System.Windows.Forms.Padding(2); + this.操作页面.Name = "操作页面"; + this.操作页面.Padding = new System.Windows.Forms.Padding(2); + this.操作页面.Size = new System.Drawing.Size(1798, 422); + this.操作页面.TabIndex = 5; + this.操作页面.TabStop = false; + this.操作页面.Text = "操作页面"; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1826, 1038); + this.Controls.Add(this.menuStrip1); + this.Controls.Add(this.tableLayoutPanel1); + this.MainMenuStrip = this.menuStrip1; + this.Margin = new System.Windows.Forms.Padding(2); + this.Name = "MainForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Form1"; + this.WindowState = System.Windows.Forms.FormWindowState.Maximized; + this.Load += new System.EventHandler(this.Form1_Load); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.tableLayoutPanel1.ResumeLayout(false); + this.groupBox1.ResumeLayout(false); + this.tableLayoutPanel3.ResumeLayout(false); + this.tableLayoutPanel2.ResumeLayout(false); + this.tableLayoutPanel2.PerformLayout(); + this.groupBox3.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.ToolStripMenuItem 用户管理ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem pLC管理ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 流程管理ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem mES接口配置ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem pLC通讯设置ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem pLC地址设置ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 扫码枪配置ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 系统参数配置ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 扫码枪配置ToolStripMenuItem1; + private System.Windows.Forms.ToolStripMenuItem 修改密码ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 切换用户ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 用户管理ToolStripMenuItem1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.GroupBox 操作页面; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.ToolStripMenuItem 扭力曲线配置ToolStripMenuItem; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.ToolStripMenuItem 产线管理ToolStripMenuItem; + private System.Windows.Forms.RichTextBox richTextBox1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; + private System.Windows.Forms.Button 开始处理; + } +} + diff --git a/WindowsFormsApp1/MainForm.cs b/WindowsFormsApp1/MainForm.cs new file mode 100644 index 0000000..f87a332 --- /dev/null +++ b/WindowsFormsApp1/MainForm.cs @@ -0,0 +1,365 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.InteropServices; +using System.Runtime.Remoting.Contexts; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Xml.Linq; +using HslCommunication.LogNet; +using WindowsFormsApp1.db; +using WindowsFormsApp1.form; +using WindowsFormsApp1.mod; +using WindowsFormsApp1.server; +using static SQLite.SQLite3; + +namespace WindowsFormsApp1 +{ + public partial class MainForm : Form + { + private Thread thread_plc1; + private Thread thread_plc2; + public MainForm() + { + InitializeComponent(); + CheckForIllegalCrossThreadCalls = false; + } + + private void Form1_Load(object sender, EventArgs e) + { + label1.Visible = false; + label2.Visible = false; + label3.Visible = false; + label4.Visible = false; + label5.Visible = false; + label6.Visible = false; + label7.Visible = false; + label8.Visible = false; + + LogExecute.logNet.BeforeSaveToFile += LogNet_BeforeSaveToFile; + LogExecute.PlclogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile; + LogExecute.ApilogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile; + + } + public void build(t_plc Plc, CancellationToken token) + { + while (true) + { + try + { + if (token.IsCancellationRequested) + { + break; + } + + + if (Plc == null) + { + continue; + } + + SiemensHelp siemensHelp = Plc.plchelp; + + var readlist = Init.t_Plcaddresses.FindAll(a=>a.plcid == Plc.id && a.type == "read"); + var writelist = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id && a.type == "write"); + + var openresult = siemensHelp.OpenConn(); + if (!openresult.Success) + { + label8.Text = $"PLC:{Plc.id}:{Plc.plcip}建立S7连接失败"; + //LogExecute.logNet.WriteError($"{Plc.plcip}建立S7连接失败"); + continue; + } + var resdresult = siemensHelp.ReadAddress(readlist); + if (!resdresult.Success) + { + label8.Text = $"PLC:{Plc.id}:{Plc.plcip}读取地址处理错误"; + //LogExecute.logNet.WriteError($"{Plc.plcip}读取地址处理错误:处理停止"); + continue; + } + + Plc.dateTime = DateTime.Now; + var status = readlist.FirstOrDefault(a=>a.remark == "触发字"); + if (status == null) + { + label8.Text = $"PLC:{Plc.id}:未找到触发字对应的字段"; + //LogExecute.logNet.WriteError($"未找到触发字对应的字段!"); + continue; + } + var nowstatus = int.Parse(status.value); + + //测试用 + nowstatus = 3; + if (nowstatus == 0) + { + continue; + } + var nowflow = Init.t_Flows.FirstOrDefault(a=>a.hopestatus == nowstatus); + if (nowflow == null) + { + label8.Text = $"PLC:{Plc.id}:未找到当前触发字{nowstatus},对应的流程"; + //LogExecute.logNet.WriteError($"未找到当前触发字{nowstatus},对应的流程!"); + continue; + } + var nowinterface = Init.t_Interfaces.FirstOrDefault(a=>a.id == nowflow.hopeinterfaceid); + if (nowinterface == null) + { + label8.Text = $"PLC:{Plc.id}:未找到当前期望接口ID {nowflow.hopeinterfaceid},对应的接口"; + //LogExecute.logNet.WriteError($"未找到当前期望接口ID {nowflow.hopeinterfaceid},对应的接口!"); + continue; + } + + ApiClient apiClient = new ApiClient(); + var result = apiClient.CallFunctionByName(nowinterface.code); + if (result.Success) + { + var writeresult = siemensHelp.WriteAddress(writelist); + if (!writeresult.Success) + { + label8.Text = $"PLC:{Plc.id}:{Plc.plcip}写入地址处理错误"; + //LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止"); + continue; + } + } + else + { + + } + + + } + catch (Exception e) + { + LogExecute.logNet.WriteError(e.Message); + } + finally + { + Thread.Sleep(1000); + } + + } + } + + #region 开始及结束处理按钮 + private void 开始处理_Click(object sender, EventArgs e) + { + if (开始处理.Text == "开始处理") + { + + SQLiteHelper sQLiteHelper_plc = new db.SQLiteHelper(); + BllResult plc_result = sQLiteHelper_plc.QuerySingle(a => a.id == Init.t_Line.plcid1); + BllResult plc_result2 = new BllResult(false, "", null); + if (!plc_result.Success) + { + MessageBox.Show("无法初始化PLC1信息,无法开始处理!"); + return; + } + if (Init.t_Line.plcid2 != 0) + { + plc_result2 = sQLiteHelper_plc.QuerySingle(a => a.id == Init.t_Line.plcid2); + if (!plc_result2.Success) + { + MessageBox.Show("无法初始化PLC2信息,无法开始处理!"); + return; + } + } + + SQLiteHelper sQLiteHelper_flow = new db.SQLiteHelper(); + var flow_result = sQLiteHelper_flow.Query(a => a.flowid == Init.t_Line.flowid); + if (!flow_result.Success) + { + MessageBox.Show("无法初始化流程信息,无法开始处理!"); + return; + } + + SQLiteHelper sQLiteHelper_address = new db.SQLiteHelper(); + var address_result = sQLiteHelper_address.QueryAll(); + if (!address_result.Success) + { + MessageBox.Show("无法初始化PLC地址信息,无法开始处理!"); + return; + } + + SQLiteHelper sQLiteHelper_interface = new db.SQLiteHelper(); + var interface_result = sQLiteHelper_interface.QueryAll(); + if (!interface_result.Success) + { + MessageBox.Show("无法初始化接口地址信息,无法开始处理!"); + return; + } + + Init.t_Plc1 = plc_result.Data; + Init.t_Plc1.plchelp = new SiemensHelp(Init.t_Plc1.plcip, Init.t_Plc1.timeout); + Init.t_Plc2 = plc_result2.Data; + if (Init.t_Plc2 != null) + { + Init.t_Plc2.plchelp = new SiemensHelp(Init.t_Plc2.plcip, Init.t_Plc2.timeout); + } + + Init.t_Flows = flow_result.Data; + + Init.t_Plcaddresses = address_result.Data; + Init.t_Interfaces = interface_result.Data; + + if (!Init.isrunning1) + { + Init.cancellationTokenSource1 = new CancellationTokenSource(); + thread_plc1 = new Thread(() => build(Init.t_Plc1, Init.cancellationTokenSource1.Token)); + thread_plc1.Start(); + Init.isrunning1 = true; + } + + //if (!Init.isrunning2) + //{ + // Init.cancellationTokenSource2 = new CancellationTokenSource(); + // thread_plc2 = new Thread(() => build(Init.t_Plc2, Init.cancellationTokenSource2.Token)); + // thread_plc2.Start(); + // Init.isrunning2 = true; + //} + + 开始处理.Text = "停止处理"; + 开始处理.BackColor = Color.Red; + label1.Text = "MES站名:" + Init.t_Line.linename; + label2.Text = "MES站名:" + Init.t_Line.linecode; + label3.Text = "类型:" + Init.t_Line.linetype; + label4.Text = "模组:" + Init.t_Line.linemode; + + + label1.Visible = true; + label2.Visible = true; + label3.Visible = true; + label4.Visible = true; + label5.Visible = true; + label6.Visible = true; + label7.Visible = true; + label8.Visible = true; + LogExecute.logNet.WriteInfo($"用户{Init.t_User.username},开始处理!"); + } + else + { + if (thread_plc1 != null && thread_plc1.IsAlive) + { + // 请求取消线程 + Init.cancellationTokenSource1?.Cancel(); + thread_plc1.Join(); // 等待线程完成 + } + Init.isrunning1 = false; + + if (thread_plc2 != null && thread_plc2.IsAlive) + { + // 请求取消线程 + Init.cancellationTokenSource2?.Cancel(); + thread_plc2.Join(); // 等待线程完成 + } + Init.isrunning2 = false; + + Thread.Sleep(500); + 开始处理.Text = "开始处理"; + 开始处理.BackColor = Color.Green; + label1.Visible = false; + label2.Visible = false; + label3.Visible = false; + label4.Visible = false; + LogExecute.logNet.WriteInfo($"用户{Init.t_User.username},停止处理!"); + } + } + #endregion + #region 页面按钮-跳转 + private void 流程管理ToolStripMenuItem_Click(object sender, EventArgs e) + { + FLOW_Manage fLOW_Mange = new FLOW_Manage(); + fLOW_Mange.ShowDialog(); + } + + private void 产线管理ToolStripMenuItem_Click(object sender, EventArgs e) + { + LINE_Manage lINE_Manage = new LINE_Manage(); + lINE_Manage.ShowDialog(); + } + + private void pLC通讯设置ToolStripMenuItem_Click(object sender, EventArgs e) + { + PLC_Manage pLC_Manage = new PLC_Manage(); + pLC_Manage.ShowDialog(); + } + + private void pLC地址设置ToolStripMenuItem_Click(object sender, EventArgs e) + { + PLCADDRESS_Manage pLCADDRESS_Manage = new PLCADDRESS_Manage(); + pLCADDRESS_Manage.ShowDialog(); + } + private void 切换用户ToolStripMenuItem_Click(object sender, EventArgs e) + { + Application.Restart(); + } + + private void mES接口配置ToolStripMenuItem_Click(object sender, EventArgs e) + { + MES_URL mES_URL = new MES_URL(); + mES_URL.ShowDialog(); + } + + private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e) + { + USER_ChangeP uSER_ChangeP = new USER_ChangeP(); + uSER_ChangeP.ShowDialog(); + } + + private void 用户管理ToolStripMenuItem1_Click(object sender, EventArgs e) + { + USER_Manage uSER_Manage = new USER_Manage(); + uSER_Manage.ShowDialog(); + } + #endregion + #region 页面-布局、日志等 + private void LogNet_BeforeSaveToFile(object sender, HslEventArgs e) + { + lock (this) + { + DateTime time = e.HslMessage.Time;//获取时间 + string text = e.HslMessage.Text;//日志文本 + int textLength = richTextBox1.TextLength; + int lineCount = richTextBox1.GetLineFromCharIndex(textLength); + + if (lineCount >= 20) + { + richTextBox1.Clear(); + } + + if (e.HslMessage.Degree == HslMessageDegree.ERROR) + { + richTextBox1.SelectionColor = Color.Red; + richTextBox1.AppendText("[错误] " + time.ToString() + " | " + text + "\n"); + } + else if (e.HslMessage.Degree == HslMessageDegree.DEBUG) + { + richTextBox1.SelectionColor = Color.Green; + richTextBox1.AppendText("[日志] " + time.ToString() + " | " + text + "\n"); + } + else if (e.HslMessage.Degree == HslMessageDegree.WARN) + { + richTextBox1.SelectionColor = Color.Orange; + richTextBox1.AppendText("[警告] " + time.ToString() + " | " + text + "\n"); + } + else if (e.HslMessage.Degree == HslMessageDegree.INFO) + { + richTextBox1.SelectionColor = Color.Orange; + richTextBox1.AppendText("[提示] " + time.ToString() + " | " + text + "\n"); + } + else + { + richTextBox1.SelectionColor = Color.Red; + richTextBox1.AppendText("[未知] " + time.ToString() + " | " + text + "\n"); + } + } + } + #endregion + } +} diff --git a/WindowsFormsApp1/MainForm.resx b/WindowsFormsApp1/MainForm.resx new file mode 100644 index 0000000..7670a02 --- /dev/null +++ b/WindowsFormsApp1/MainForm.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 79 + + \ No newline at end of file diff --git a/WindowsFormsApp1/Program.cs b/WindowsFormsApp1/Program.cs new file mode 100644 index 0000000..a328c0d --- /dev/null +++ b/WindowsFormsApp1/Program.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.mod; +using WindowsFormsApp1.server; + +namespace WindowsFormsApp1 +{ + internal static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + //Application.Run(new MainForm()); + + //创建窗体 + LoginForm frm = new LoginForm(); + //验证成功显示主窗体 + if (frm.ShowDialog() == DialogResult.OK) + { + Application.Run(new MainForm()); + } + } + } + + public static class Init + { + public static t_user t_User; + public static t_line t_Line; + public static List t_Flows; + public static t_plc t_Plc1; + public static t_plc t_Plc2; + + public static List t_Interfaces; + public static List t_Plcaddresses; + public static bool isrunning1 = false; + public static CancellationTokenSource cancellationTokenSource1; + public static bool isrunning2 = false; + public static CancellationTokenSource cancellationTokenSource2; + + public static int errinterface1 = 0; + public static int errinterface2 = 0; + } +} diff --git a/WindowsFormsApp1/Properties/AssemblyInfo.cs b/WindowsFormsApp1/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7383a06 --- /dev/null +++ b/WindowsFormsApp1/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("WindowsFormsApp1")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WindowsFormsApp1")] +[assembly: AssemblyCopyright("Copyright © 2025")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("81a4c6f2-1d92-4791-a23e-bf8792781b0d")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/WindowsFormsApp1/Properties/Resources.Designer.cs b/WindowsFormsApp1/Properties/Resources.Designer.cs new file mode 100644 index 0000000..8b479b7 --- /dev/null +++ b/WindowsFormsApp1/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace WindowsFormsApp1.Properties +{ + + + /// + /// 强类型资源类,用于查找本地化字符串等。 + /// + // 此类是由 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() + { + } + + /// + /// 返回此类使用的缓存 ResourceManager 实例。 + /// + [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("WindowsFormsApp1.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/WindowsFormsApp1/Properties/Resources.resx b/WindowsFormsApp1/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/WindowsFormsApp1/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WindowsFormsApp1/Properties/Settings.Designer.cs b/WindowsFormsApp1/Properties/Settings.Designer.cs new file mode 100644 index 0000000..438df21 --- /dev/null +++ b/WindowsFormsApp1/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// 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. +// +//------------------------------------------------------------------------------ + +namespace WindowsFormsApp1.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; + } + } + } +} diff --git a/WindowsFormsApp1/Properties/Settings.settings b/WindowsFormsApp1/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/WindowsFormsApp1/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/WindowsFormsApp1/db/MES_PLC.db b/WindowsFormsApp1/db/MES_PLC.db new file mode 100644 index 0000000..b9f1c56 Binary files /dev/null and b/WindowsFormsApp1/db/MES_PLC.db differ diff --git a/WindowsFormsApp1/db/SQLite.cs b/WindowsFormsApp1/db/SQLite.cs new file mode 100644 index 0000000..7504a8d --- /dev/null +++ b/WindowsFormsApp1/db/SQLite.cs @@ -0,0 +1,4428 @@ +// +// Copyright (c) 2009-2019 Krueger Systems, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE +#define USE_CSHARP_SQLITE +#endif + +using System; +using System.Collections; +using System.Diagnostics; +#if !USE_SQLITEPCL_RAW +using System.Runtime.InteropServices; +#endif +using System.Collections.Generic; +using System.Reflection; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading; + +#if USE_CSHARP_SQLITE +using Sqlite3 = Community.CsharpSqlite.Sqlite3; +using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3; +using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe; +#elif USE_WP8_NATIVE_SQLITE +using Sqlite3 = Sqlite.Sqlite3; +using Sqlite3DatabaseHandle = Sqlite.Database; +using Sqlite3Statement = Sqlite.Statement; +#elif USE_SQLITEPCL_RAW +using Sqlite3DatabaseHandle = SQLitePCL.sqlite3; +using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup; +using Sqlite3Statement = SQLitePCL.sqlite3_stmt; +using Sqlite3 = SQLitePCL.raw; +#else +using Sqlite3DatabaseHandle = System.IntPtr; +using Sqlite3BackupHandle = System.IntPtr; +using Sqlite3Statement = System.IntPtr; +#endif + +#pragma warning disable 1591 // XML Doc Comments + +namespace SQLite +{ + public class SQLiteException : Exception + { + public SQLite3.Result Result { get; private set; } + + protected SQLiteException (SQLite3.Result r, string message) : base (message) + { + Result = r; + } + + public static SQLiteException New (SQLite3.Result r, string message) + { + return new SQLiteException (r, message); + } + } + + public class NotNullConstraintViolationException : SQLiteException + { + public IEnumerable Columns { get; protected set; } + + protected NotNullConstraintViolationException (SQLite3.Result r, string message) + : this (r, message, null, null) + { + + } + + protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj) + : base (r, message) + { + if (mapping != null && obj != null) { + this.Columns = from c in mapping.Columns + where c.IsNullable == false && c.GetValue (obj) == null + select c; + } + } + + public static new NotNullConstraintViolationException New (SQLite3.Result r, string message) + { + return new NotNullConstraintViolationException (r, message); + } + + public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj) + { + return new NotNullConstraintViolationException (r, message, mapping, obj); + } + + public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj) + { + return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj); + } + } + + [Flags] + public enum SQLiteOpenFlags + { + ReadOnly = 1, ReadWrite = 2, Create = 4, + NoMutex = 0x8000, FullMutex = 0x10000, + SharedCache = 0x20000, PrivateCache = 0x40000, + ProtectionComplete = 0x00100000, + ProtectionCompleteUnlessOpen = 0x00200000, + ProtectionCompleteUntilFirstUserAuthentication = 0x00300000, + ProtectionNone = 0x00400000 + } + + [Flags] + public enum CreateFlags + { + /// + /// Use the default creation options + /// + None = 0x000, + /// + /// Create a primary key index for a property called 'Id' (case-insensitive). + /// This avoids the need for the [PrimaryKey] attribute. + /// + ImplicitPK = 0x001, + /// + /// Create indices for properties ending in 'Id' (case-insensitive). + /// + ImplicitIndex = 0x002, + /// + /// Create a primary key for a property called 'Id' and + /// create an indices for properties ending in 'Id' (case-insensitive). + /// + AllImplicit = 0x003, + /// + /// Force the primary key property to be auto incrementing. + /// This avoids the need for the [AutoIncrement] attribute. + /// The primary key property on the class should have type int or long. + /// + AutoIncPK = 0x004, + /// + /// Create virtual table using FTS3 + /// + FullTextSearch3 = 0x100, + /// + /// Create virtual table using FTS4 + /// + FullTextSearch4 = 0x200 + } + + /// + /// An open connection to a SQLite database. + /// + [Preserve (AllMembers = true)] + public partial class SQLiteConnection : IDisposable + { + private bool _open; + private TimeSpan _busyTimeout; + readonly static Dictionary _mappings = new Dictionary (); + private System.Diagnostics.Stopwatch _sw; + private long _elapsedMilliseconds = 0; + + private int _transactionDepth = 0; + private Random _rand = new Random (); + + public Sqlite3DatabaseHandle Handle { get; private set; } + static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle); + static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle); + + /// + /// Gets the database path used by this connection. + /// + public string DatabasePath { get; private set; } + + /// + /// Gets the SQLite library version number. 3007014 would be v3.7.14 + /// + public int LibVersionNumber { get; private set; } + + /// + /// Whether Trace lines should be written that show the execution time of queries. + /// + public bool TimeExecution { get; set; } + + /// + /// Whether to writer queries to during execution. + /// + /// The tracer. + public bool Trace { get; set; } + + /// + /// The delegate responsible for writing trace lines. + /// + /// The tracer. + public Action Tracer { get; set; } + + /// + /// Whether to store DateTime properties as ticks (true) or strings (false). + /// + public bool StoreDateTimeAsTicks { get; private set; } + + /// + /// Whether to store TimeSpan properties as ticks (true) or strings (false). + /// + public bool StoreTimeSpanAsTicks { get; private set; } + + /// + /// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true. + /// + /// The date time string format. + public string DateTimeStringFormat { get; private set; } + + /// + /// The DateTimeStyles value to use when parsing a DateTime property string. + /// + /// The date time style. + internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; } + +#if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES + static SQLiteConnection () + { + SQLitePCL.Batteries_V2.Init (); + } +#endif + + /// + /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true) + : this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)) + { + } + + /// + /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Flags controlling how the connection should be opened. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true) + : this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks)) + { + } + + /// + /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. + /// + /// + /// Details on how to find and open the database. + /// + public SQLiteConnection (SQLiteConnectionString connectionString) + { + if (connectionString == null) + throw new ArgumentNullException (nameof (connectionString)); + if (connectionString.DatabasePath == null) + throw new InvalidOperationException ("DatabasePath must be specified"); + + DatabasePath = connectionString.DatabasePath; + + LibVersionNumber = SQLite3.LibVersionNumber (); + +#if NETFX_CORE + SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path); +#endif + + Sqlite3DatabaseHandle handle; + +#if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW + var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName); +#else + // open using the byte[] + // in the case where the path may include Unicode + // force open to using UTF-8 using sqlite3_open_v2 + var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath); + var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName); +#endif + + Handle = handle; + if (r != SQLite3.Result.OK) { + throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r)); + } + _open = true; + + StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks; + DateTimeStringFormat = connectionString.DateTimeStringFormat; + DateTimeStyle = connectionString.DateTimeStyle; + + BusyTimeout = TimeSpan.FromSeconds (0.1); + Tracer = line => Debug.WriteLine (line); + + connectionString.PreKeyAction?.Invoke (this); + if (connectionString.Key is string stringKey) { + SetKey (stringKey); + } + else if (connectionString.Key is byte[] bytesKey) { + SetKey (bytesKey); + } + else if (connectionString.Key != null) { + throw new InvalidOperationException ("Encryption keys must be strings or byte arrays"); + } + connectionString.PostKeyAction?.Invoke (this); + } + + /// + /// Enables the write ahead logging. WAL is significantly faster in most scenarios + /// by providing better concurrency and better disk IO performance than the normal + /// jounral mode. You only need to call this function once in the lifetime of the database. + /// + public void EnableWriteAheadLogging() + { + ExecuteScalar ("PRAGMA journal_mode=WAL"); + } + + /// + /// Convert an input string to a quoted SQL string that can be safely used in queries. + /// + /// The quoted string. + /// The unsafe string to quote. + static string Quote (string unsafeString) + { + // TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153 + if (unsafeString == null) return "NULL"; + var safe = unsafeString.Replace ("'", "''"); + return "'" + safe + "'"; + } + + /// + /// Sets the key used to encrypt/decrypt the database with "pragma key = ...". + /// This must be the first thing you call before doing anything else with this connection + /// if your database is encrypted. + /// This only has an effect if you are using the SQLCipher nuget package. + /// + /// Ecryption key plain text that is converted to the real encryption key using PBKDF2 key derivation + void SetKey (string key) + { + if (key == null) throw new ArgumentNullException (nameof (key)); + var q = Quote (key); + Execute ("pragma key = " + q); + } + + /// + /// Sets the key used to encrypt/decrypt the database. + /// This must be the first thing you call before doing anything else with this connection + /// if your database is encrypted. + /// This only has an effect if you are using the SQLCipher nuget package. + /// + /// 256-bit (32 byte) ecryption key data + void SetKey (byte[] key) + { + if (key == null) throw new ArgumentNullException (nameof (key)); + if (key.Length != 32) throw new ArgumentException ("Key must be 32 bytes (256-bit)", nameof(key)); + var s = String.Join ("", key.Select (x => x.ToString ("X2"))); + Execute ("pragma key = \"x'" + s + "'\""); + } + + /// + /// Enable or disable extension loading. + /// + public void EnableLoadExtension (bool enabled) + { + SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0); + if (r != SQLite3.Result.OK) { + string msg = SQLite3.GetErrmsg (Handle); + throw SQLiteException.New (r, msg); + } + } + +#if !USE_SQLITEPCL_RAW + static byte[] GetNullTerminatedUtf8 (string s) + { + var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s); + var bytes = new byte [utf8Length + 1]; + utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); + return bytes; + } +#endif + + /// + /// Sets a busy handler to sleep the specified amount of time when a table is locked. + /// The handler will sleep multiple times until a total time of has accumulated. + /// + public TimeSpan BusyTimeout { + get { return _busyTimeout; } + set { + _busyTimeout = value; + if (Handle != NullHandle) { + SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds); + } + } + } + + /// + /// Returns the mappings from types to tables that the connection + /// currently understands. + /// + public IEnumerable TableMappings { + get { + lock (_mappings) { + return new List (_mappings.Values); + } + } + } + + /// + /// Retrieves the mapping that is automatically generated for the given type. + /// + /// + /// The type whose mapping to the database is returned. + /// + /// + /// Optional flags allowing implicit PK and indexes based on naming conventions + /// + /// + /// The mapping represents the schema of the columns of the database and contains + /// methods to set and get properties of objects. + /// + public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None) + { + TableMapping map; + var key = type.FullName; + lock (_mappings) { + if (_mappings.TryGetValue (key, out map)) { + if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) { + map = new TableMapping (type, createFlags); + _mappings[key] = map; + } + } + else { + map = new TableMapping (type, createFlags); + _mappings.Add (key, map); + } + } + return map; + } + + /// + /// Retrieves the mapping that is automatically generated for the given type. + /// + /// + /// Optional flags allowing implicit PK and indexes based on naming conventions + /// + /// + /// The mapping represents the schema of the columns of the database and contains + /// methods to set and get properties of objects. + /// + public TableMapping GetMapping (CreateFlags createFlags = CreateFlags.None) + { + return GetMapping (typeof (T), createFlags); + } + + private struct IndexedColumn + { + public int Order; + public string ColumnName; + } + + private struct IndexInfo + { + public string IndexName; + public string TableName; + public bool Unique; + public List Columns; + } + + /// + /// Executes a "drop table" on the database. This is non-recoverable. + /// + public int DropTable () + { + return DropTable (GetMapping (typeof (T))); + } + + /// + /// Executes a "drop table" on the database. This is non-recoverable. + /// + /// + /// The TableMapping used to identify the table. + /// + public int DropTable (TableMapping map) + { + var query = string.Format ("drop table if exists \"{0}\"", map.TableName); + return Execute (query); + } + + /// + /// Executes a "create table if not exists" on the database. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated. + /// + public CreateTableResult CreateTable (CreateFlags createFlags = CreateFlags.None) + { + return CreateTable (typeof (T), createFlags); + } + + /// + /// Executes a "create table if not exists" on the database. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// Type to reflect to a database table. + /// Optional flags allowing implicit PK and indexes based on naming conventions. + /// + /// Whether the table was created or migrated. + /// + public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None) + { + var map = GetMapping (ty, createFlags); + + // Present a nice error if no columns specified + if (map.Columns.Length == 0) { + throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName)); + } + + // Check if the table exists + var result = CreateTableResult.Created; + var existingCols = GetTableInfo (map.TableName); + + // Create or migrate it + if (existingCols.Count == 0) { + + // Facilitate virtual tables a.k.a. full-text search. + bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0; + bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0; + bool fts = fts3 || fts4; + var @virtual = fts ? "virtual " : string.Empty; + var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty; + + // Build query. + var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n"; + var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks)); + var decl = string.Join (",\n", decls.ToArray ()); + query += decl; + query += ")"; + if(map.WithoutRowId) { + query += " without rowid"; + } + + Execute (query); + } + else { + result = CreateTableResult.Migrated; + MigrateTable (map, existingCols); + } + + var indexes = new Dictionary (); + foreach (var c in map.Columns) { + foreach (var i in c.Indices) { + var iname = i.Name ?? map.TableName + "_" + c.Name; + IndexInfo iinfo; + if (!indexes.TryGetValue (iname, out iinfo)) { + iinfo = new IndexInfo { + IndexName = iname, + TableName = map.TableName, + Unique = i.Unique, + Columns = new List () + }; + indexes.Add (iname, iinfo); + } + + if (i.Unique != iinfo.Unique) + throw new Exception ("All the columns in an index must have the same value for their Unique property"); + + iinfo.Columns.Add (new IndexedColumn { + Order = i.Order, + ColumnName = c.Name + }); + } + } + + foreach (var indexName in indexes.Keys) { + var index = indexes[indexName]; + var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray (); + CreateIndex (indexName, index.TableName, columns, index.Unique); + } + + return result; + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + { + return CreateTables (createFlags, typeof (T), typeof (T2)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + where T3 : new() + { + return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + where T3 : new() + where T4 : new() + { + return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + where T3 : new() + where T4 : new() + where T5 : new() + { + return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types) + { + var result = new CreateTablesResult (); + foreach (Type type in types) { + var aResult = CreateTable (type, createFlags); + result.Results[type] = aResult; + } + return result; + } + + /// + /// Creates an index for the specified table and columns. + /// + /// Name of the index to create + /// Name of the database table + /// An array of column names to index + /// Whether the index should be unique + public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false) + { + const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; + var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName); + return Execute (sql); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the index to create + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false) + { + return CreateIndex (indexName, tableName, new string[] { columnName }, unique); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public int CreateIndex (string tableName, string columnName, bool unique = false) + { + return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique); + } + + /// + /// Creates an index for the specified table and columns. + /// + /// Name of the database table + /// An array of column names to index + /// Whether the index should be unique + public int CreateIndex (string tableName, string[] columnNames, bool unique = false) + { + return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique); + } + + /// + /// Creates an index for the specified object property. + /// e.g. CreateIndex<Client>(c => c.Name); + /// + /// Type to reflect to a database table. + /// Property to index + /// Whether the index should be unique + public int CreateIndex (Expression> property, bool unique = false) + { + MemberExpression mx; + if (property.Body.NodeType == ExpressionType.Convert) { + mx = ((UnaryExpression)property.Body).Operand as MemberExpression; + } + else { + mx = (property.Body as MemberExpression); + } + var propertyInfo = mx.Member as PropertyInfo; + if (propertyInfo == null) { + throw new ArgumentException ("The lambda expression 'property' should point to a valid Property"); + } + + var propName = propertyInfo.Name; + + var map = GetMapping (); + var colName = map.FindColumnWithPropertyName (propName).Name; + + return CreateIndex (map.TableName, colName, unique); + } + + [Preserve (AllMembers = true)] + public class ColumnInfo + { + // public int cid { get; set; } + + [Column ("name")] + public string Name { get; set; } + + // [Column ("type")] + // public string ColumnType { get; set; } + + public int notnull { get; set; } + + // public string dflt_value { get; set; } + + // public int pk { get; set; } + + public override string ToString () + { + return Name; + } + } + + /// + /// Query the built-in sqlite table_info table for a specific tables columns. + /// + /// The columns contains in the table. + /// Table name. + public List GetTableInfo (string tableName) + { + var query = "pragma table_info(\"" + tableName + "\")"; + return Query (query); + } + + void MigrateTable (TableMapping map, List existingCols) + { + var toBeAdded = new List (); + + foreach (var p in map.Columns) { + var found = false; + foreach (var c in existingCols) { + found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0); + if (found) + break; + } + if (!found) { + toBeAdded.Add (p); + } + } + + foreach (var p in toBeAdded) { + var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks); + Execute (addCol); + } + } + + /// + /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class. + /// + /// + protected virtual SQLiteCommand NewCommand () + { + return new SQLiteCommand (this); + } + + /// + /// Creates a new SQLiteCommand given the command text with arguments. Place a '?' + /// in the command text for each of the arguments. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the command text. + /// + /// + /// A + /// + public SQLiteCommand CreateCommand (string cmdText, params object[] ps) + { + if (!_open) + throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database"); + + var cmd = NewCommand (); + cmd.CommandText = cmdText; + foreach (var o in ps) { + cmd.Bind (o); + } + return cmd; + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// Use this method instead of Query when you don't expect rows back. Such cases include + /// INSERTs, UPDATEs, and DELETEs. + /// You can set the Trace or TimeExecution properties of the connection + /// to profile execution. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The number of rows modified in the database as a result of this execution. + /// + public int Execute (string query, params object[] args) + { + var cmd = CreateCommand (query, args); + + if (TimeExecution) { + if (_sw == null) { + _sw = new Stopwatch (); + } + _sw.Reset (); + _sw.Start (); + } + + var r = cmd.ExecuteNonQuery (); + + if (TimeExecution) { + _sw.Stop (); + _elapsedMilliseconds += _sw.ElapsedMilliseconds; + Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); + } + + return r; + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// Use this method when return primitive values. + /// You can set the Trace or TimeExecution properties of the connection + /// to profile execution. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The number of rows modified in the database as a result of this execution. + /// + public T ExecuteScalar (string query, params object[] args) + { + var cmd = CreateCommand (query, args); + + if (TimeExecution) { + if (_sw == null) { + _sw = new Stopwatch (); + } + _sw.Reset (); + _sw.Start (); + } + + var r = cmd.ExecuteScalar (); + + if (TimeExecution) { + _sw.Stop (); + _elapsedMilliseconds += _sw.ElapsedMilliseconds; + Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); + } + + return r; + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the mapping automatically generated for + /// the given type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// + public List Query (string query, params object[] args) where T : new() + { + var cmd = CreateCommand (query, args); + return cmd.ExecuteQuery (); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the mapping automatically generated for + /// the given type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// The enumerator (retrieved by calling GetEnumerator() on the result of this method) + /// will call sqlite3_step on each call to MoveNext, so the database + /// connection must remain open for the lifetime of the enumerator. + /// + public IEnumerable DeferredQuery (string query, params object[] args) where T : new() + { + var cmd = CreateCommand (query, args); + return cmd.ExecuteDeferredQuery (); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the specified mapping. This function is + /// only used by libraries in order to query the database via introspection. It is + /// normally not used. + /// + /// + /// A to use to convert the resulting rows + /// into objects. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// + public List Query (TableMapping map, string query, params object[] args) + { + var cmd = CreateCommand (query, args); + return cmd.ExecuteQuery (map); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the specified mapping. This function is + /// only used by libraries in order to query the database via introspection. It is + /// normally not used. + /// + /// + /// A to use to convert the resulting rows + /// into objects. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// The enumerator (retrieved by calling GetEnumerator() on the result of this method) + /// will call sqlite3_step on each call to MoveNext, so the database + /// connection must remain open for the lifetime of the enumerator. + /// + public IEnumerable DeferredQuery (TableMapping map, string query, params object[] args) + { + var cmd = CreateCommand (query, args); + return cmd.ExecuteDeferredQuery (map); + } + + /// + /// Returns a queryable interface to the table represented by the given type. + /// + /// + /// A queryable object that is able to translate Where, OrderBy, and Take + /// queries into native SQL. + /// + public TableQuery Table () where T : new() + { + return new TableQuery (this); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The object with the given primary key. Throws a not found exception + /// if the object is not found. + /// + public T Get (object pk) where T : new() + { + var map = GetMapping (typeof (T)); + return Query (map.GetByPrimaryKeySql, pk).First (); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The object with the given primary key. Throws a not found exception + /// if the object is not found. + /// + public object Get (object pk, TableMapping map) + { + return Query (map, map.GetByPrimaryKeySql, pk).First (); + } + + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate. Throws a not found exception + /// if the object is not found. + /// + public T Get (Expression> predicate) where T : new() + { + return Table ().Where (predicate).First (); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The object with the given primary key or null + /// if the object is not found. + /// + public T Find (object pk) where T : new() + { + var map = GetMapping (typeof (T)); + return Query (map.GetByPrimaryKeySql, pk).FirstOrDefault (); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The object with the given primary key or null + /// if the object is not found. + /// + public object Find (object pk, TableMapping map) + { + return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault (); + } + + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public T Find (Expression> predicate) where T : new() + { + return Table ().Where (predicate).FirstOrDefault (); + } + + /// + /// Attempts to retrieve the first object that matches the query from the table + /// associated with the specified type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public T FindWithQuery (string query, params object[] args) where T : new() + { + return Query (query, args).FirstOrDefault (); + } + + /// + /// Attempts to retrieve the first object that matches the query from the table + /// associated with the specified type. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public object FindWithQuery (TableMapping map, string query, params object[] args) + { + return Query (map, query, args).FirstOrDefault (); + } + + /// + /// Whether has been called and the database is waiting for a . + /// + public bool IsInTransaction { + get { return _transactionDepth > 0; } + } + + /// + /// Begins a new transaction. Call to end the transaction. + /// + /// Throws if a transaction has already begun. + public void BeginTransaction () + { + // The BEGIN command only works if the transaction stack is empty, + // or in other words if there are no pending transactions. + // If the transaction stack is not empty when the BEGIN command is invoked, + // then the command fails with an error. + // Rather than crash with an error, we will just ignore calls to BeginTransaction + // that would result in an error. + if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) { + try { + Execute ("begin transaction"); + } + catch (Exception ex) { + var sqlExp = ex as SQLiteException; + if (sqlExp != null) { + // It is recommended that applications respond to the errors listed below + // by explicitly issuing a ROLLBACK command. + // TODO: This rollback failsafe should be localized to all throw sites. + switch (sqlExp.Result) { + case SQLite3.Result.IOError: + case SQLite3.Result.Full: + case SQLite3.Result.Busy: + case SQLite3.Result.NoMem: + case SQLite3.Result.Interrupt: + RollbackTo (null, true); + break; + } + } + else { + // Call decrement and not VolatileWrite in case we've already + // created a transaction point in SaveTransactionPoint since the catch. + Interlocked.Decrement (ref _transactionDepth); + } + + throw; + } + } + else { + // Calling BeginTransaction on an already open transaction is invalid + throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction."); + } + } + + /// + /// Creates a savepoint in the database at the current point in the transaction timeline. + /// Begins a new transaction if one is not in progress. + /// + /// Call to undo transactions since the returned savepoint. + /// Call to commit transactions after the savepoint returned here. + /// Call to end the transaction, committing all changes. + /// + /// A string naming the savepoint. + public string SaveTransactionPoint () + { + int depth = Interlocked.Increment (ref _transactionDepth) - 1; + string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth; + + try { + Execute ("savepoint " + retVal); + } + catch (Exception ex) { + var sqlExp = ex as SQLiteException; + if (sqlExp != null) { + // It is recommended that applications respond to the errors listed below + // by explicitly issuing a ROLLBACK command. + // TODO: This rollback failsafe should be localized to all throw sites. + switch (sqlExp.Result) { + case SQLite3.Result.IOError: + case SQLite3.Result.Full: + case SQLite3.Result.Busy: + case SQLite3.Result.NoMem: + case SQLite3.Result.Interrupt: + RollbackTo (null, true); + break; + } + } + else { + Interlocked.Decrement (ref _transactionDepth); + } + + throw; + } + + return retVal; + } + + /// + /// Rolls back the transaction that was begun by or . + /// + public void Rollback () + { + RollbackTo (null, false); + } + + /// + /// Rolls back the savepoint created by or SaveTransactionPoint. + /// + /// The name of the savepoint to roll back to, as returned by . If savepoint is null or empty, this method is equivalent to a call to + public void RollbackTo (string savepoint) + { + RollbackTo (savepoint, false); + } + + /// + /// Rolls back the transaction that was begun by . + /// + /// The name of the savepoint to roll back to, as returned by . If savepoint is null or empty, this method is equivalent to a call to + /// true to avoid throwing exceptions, false otherwise + void RollbackTo (string savepoint, bool noThrow) + { + // Rolling back without a TO clause rolls backs all transactions + // and leaves the transaction stack empty. + try { + if (String.IsNullOrEmpty (savepoint)) { + if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) { + Execute ("rollback"); + } + } + else { + DoSavePointExecute (savepoint, "rollback to "); + } + } + catch (SQLiteException) { + if (!noThrow) + throw; + + } + // No need to rollback if there are no transactions open. + } + + /// + /// Releases a savepoint returned from . Releasing a savepoint + /// makes changes since that savepoint permanent if the savepoint began the transaction, + /// or otherwise the changes are permanent pending a call to . + /// + /// The RELEASE command is like a COMMIT for a SAVEPOINT. + /// + /// The name of the savepoint to release. The string should be the result of a call to + public void Release (string savepoint) + { + try { + DoSavePointExecute (savepoint, "release "); + } + catch (SQLiteException ex) { + if (ex.Result == SQLite3.Result.Busy) { + // Force a rollback since most people don't know this function can fail + // Don't call Rollback() since the _transactionDepth is 0 and it won't try + // Calling rollback makes our _transactionDepth variable correct. + // Writes to the database only happen at depth=0, so this failure will only happen then. + try { + Execute ("rollback"); + } + catch { + // rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best + } + } + throw; + } + } + + void DoSavePointExecute (string savepoint, string cmd) + { + // Validate the savepoint + int firstLen = savepoint.IndexOf ('D'); + if (firstLen >= 2 && savepoint.Length > firstLen + 1) { + int depth; + if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) { + // TODO: Mild race here, but inescapable without locking almost everywhere. + if (0 <= depth && depth < _transactionDepth) { +#if NETFX_CORE || USE_SQLITEPCL_RAW || NETCORE + Volatile.Write (ref _transactionDepth, depth); +#elif SILVERLIGHT + _transactionDepth = depth; +#else + Thread.VolatileWrite (ref _transactionDepth, depth); +#endif + Execute (cmd + savepoint); + return; + } + } + } + + throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint"); + } + + /// + /// Commits the transaction that was begun by . + /// + public void Commit () + { + if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) { + try { + Execute ("commit"); + } + catch { + // Force a rollback since most people don't know this function can fail + // Don't call Rollback() since the _transactionDepth is 0 and it won't try + // Calling rollback makes our _transactionDepth variable correct. + try { + Execute ("rollback"); + } + catch { + // rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best + } + throw; + } + } + // Do nothing on a commit with no open transaction + } + + /// + /// Executes within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an + /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception + /// is rethrown. + /// + /// + /// The to perform within a transaction. can contain any number + /// of operations on the connection but should never call or + /// . + /// + public void RunInTransaction (Action action) + { + try { + var savePoint = SaveTransactionPoint (); + action (); + Release (savePoint); + } + catch (Exception) { + Rollback (); + throw; + } + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// A boolean indicating if the inserts should be wrapped in a transaction. + /// + /// + /// The number of rows added to the table. + /// + public int InsertAll (System.Collections.IEnumerable objects, bool runInTransaction = true) + { + var c = 0; + if (runInTransaction) { + RunInTransaction (() => { + foreach (var r in objects) { + c += Insert (r); + } + }); + } + else { + foreach (var r in objects) { + c += Insert (r); + } + } + return c; + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// A boolean indicating if the inserts should be wrapped in a transaction. + /// + /// + /// The number of rows added to the table. + /// + public int InsertAll (System.Collections.IEnumerable objects, string extra, bool runInTransaction = true) + { + var c = 0; + if (runInTransaction) { + RunInTransaction (() => { + foreach (var r in objects) { + c += Insert (r, extra); + } + }); + } + else { + foreach (var r in objects) { + c += Insert (r); + } + } + return c; + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// A boolean indicating if the inserts should be wrapped in a transaction. + /// + /// + /// The number of rows added to the table. + /// + public int InsertAll (System.Collections.IEnumerable objects, Type objType, bool runInTransaction = true) + { + var c = 0; + if (runInTransaction) { + RunInTransaction (() => { + foreach (var r in objects) { + c += Insert (r, objType); + } + }); + } + else { + foreach (var r in objects) { + c += Insert (r, objType); + } + } + return c; + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj) + { + if (obj == null) { + return 0; + } + return Insert (obj, "", Orm.GetType (obj)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// If a UNIQUE constraint violation occurs with + /// some pre-existing object, this function deletes + /// the old object. + /// + /// + /// The object to insert. + /// + /// + /// The number of rows modified. + /// + public int InsertOrReplace (object obj) + { + if (obj == null) { + return 0; + } + return Insert (obj, "OR REPLACE", Orm.GetType (obj)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, Type objType) + { + return Insert (obj, "", objType); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// If a UNIQUE constraint violation occurs with + /// some pre-existing object, this function deletes + /// the old object. + /// + /// + /// The object to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows modified. + /// + public int InsertOrReplace (object obj, Type objType) + { + return Insert (obj, "OR REPLACE", objType); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, string extra) + { + if (obj == null) { + return 0; + } + return Insert (obj, extra, Orm.GetType (obj)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, string extra, Type objType) + { + if (obj == null || objType == null) { + return 0; + } + + var map = GetMapping (objType); + + if (map.PK != null && map.PK.IsAutoGuid) { + if (map.PK.GetValue (obj).Equals (Guid.Empty)) { + map.PK.SetValue (obj, Guid.NewGuid ()); + } + } + + var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; + + var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns; + var vals = new object[cols.Length]; + for (var i = 0; i < vals.Length; i++) { + vals[i] = cols[i].GetValue (obj); + } + + var insertCmd = GetInsertCommand (map, extra); + int count; + + lock (insertCmd) { + // We lock here to protect the prepared statement returned via GetInsertCommand. + // A SQLite prepared statement can be bound for only one operation at a time. + try { + count = insertCmd.ExecuteNonQuery (vals); + } + catch (SQLiteException ex) { + if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { + throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj); + } + throw; + } + + if (map.HasAutoIncPK) { + var id = SQLite3.LastInsertRowid (Handle); + map.SetAutoIncPK (obj, id); + } + } + if (count > 0) + OnTableChanged (map, NotifyTableChangedAction.Insert); + + return count; + } + + readonly Dictionary, PreparedSqlLiteInsertCommand> _insertCommandMap = new Dictionary, PreparedSqlLiteInsertCommand> (); + + PreparedSqlLiteInsertCommand GetInsertCommand (TableMapping map, string extra) + { + PreparedSqlLiteInsertCommand prepCmd; + + var key = Tuple.Create (map.MappedType.FullName, extra); + + lock (_insertCommandMap) { + if (_insertCommandMap.TryGetValue (key, out prepCmd)) { + return prepCmd; + } + } + + prepCmd = CreateInsertCommand (map, extra); + + lock (_insertCommandMap) { + if (_insertCommandMap.TryGetValue (key, out var existing)) { + prepCmd.Dispose (); + return existing; + } + + _insertCommandMap.Add (key, prepCmd); + } + + return prepCmd; + } + + PreparedSqlLiteInsertCommand CreateInsertCommand (TableMapping map, string extra) + { + var cols = map.InsertColumns; + string insertSql; + if (cols.Length == 0 && map.Columns.Length == 1 && map.Columns[0].IsAutoInc) { + insertSql = string.Format ("insert {1} into \"{0}\" default values", map.TableName, extra); + } + else { + var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; + + if (replacing) { + cols = map.InsertOrReplaceColumns; + } + + insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", map.TableName, + string.Join (",", (from c in cols + select "\"" + c.Name + "\"").ToArray ()), + string.Join (",", (from c in cols + select "?").ToArray ()), extra); + + } + + var insertCommand = new PreparedSqlLiteInsertCommand (this, insertSql); + return insertCommand; + } + + /// + /// Updates all of the columns of a table using the specified object + /// except for its primary key. + /// The object is required to have a primary key. + /// + /// + /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The number of rows updated. + /// + public int Update (object obj) + { + if (obj == null) { + return 0; + } + return Update (obj, Orm.GetType (obj)); + } + + /// + /// Updates all of the columns of a table using the specified object + /// except for its primary key. + /// The object is required to have a primary key. + /// + /// + /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows updated. + /// + public int Update (object obj, Type objType) + { + int rowsAffected = 0; + if (obj == null || objType == null) { + return 0; + } + + var map = GetMapping (objType); + + var pk = map.PK; + + if (pk == null) { + throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK"); + } + + var cols = from p in map.Columns + where p != pk + select p; + var vals = from c in cols + select c.GetValue (obj); + var ps = new List (vals); + if (ps.Count == 0) { + // There is a PK but no accompanying data, + // so reset the PK to make the UPDATE work. + cols = map.Columns; + vals = from c in cols + select c.GetValue (obj); + ps = new List (vals); + } + ps.Add (pk.GetValue (obj)); + var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols + select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); + + try { + rowsAffected = Execute (q, ps.ToArray ()); + } + catch (SQLiteException ex) { + + if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { + throw NotNullConstraintViolationException.New (ex, map, obj); + } + + throw ex; + } + + if (rowsAffected > 0) + OnTableChanged (map, NotifyTableChangedAction.Update); + + return rowsAffected; + } + + /// + /// Updates all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// A boolean indicating if the inserts should be wrapped in a transaction + /// + /// + /// The number of rows modified. + /// + public int UpdateAll (System.Collections.IEnumerable objects, bool runInTransaction = true) + { + var c = 0; + if (runInTransaction) { + RunInTransaction (() => { + foreach (var r in objects) { + c += Update (r); + } + }); + } + else { + foreach (var r in objects) { + c += Update (r); + } + } + return c; + } + + /// + /// Deletes the given object from the database using its primary key. + /// + /// + /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The number of rows deleted. + /// + public int Delete (object objectToDelete) + { + var map = GetMapping (Orm.GetType (objectToDelete)); + var pk = map.PK; + if (pk == null) { + throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); + } + var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); + var count = Execute (q, pk.GetValue (objectToDelete)); + if (count > 0) + OnTableChanged (map, NotifyTableChangedAction.Delete); + return count; + } + + /// + /// Deletes the object with the specified primary key. + /// + /// + /// The primary key of the object to delete. + /// + /// + /// The number of objects deleted. + /// + /// + /// The type of object. + /// + public int Delete (object primaryKey) + { + return Delete (primaryKey, GetMapping (typeof (T))); + } + + /// + /// Deletes the object with the specified primary key. + /// + /// + /// The primary key of the object to delete. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The number of objects deleted. + /// + public int Delete (object primaryKey, TableMapping map) + { + var pk = map.PK; + if (pk == null) { + throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); + } + var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); + var count = Execute (q, primaryKey); + if (count > 0) + OnTableChanged (map, NotifyTableChangedAction.Delete); + return count; + } + + /// + /// Deletes all the objects from the specified table. + /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the + /// specified table. Do you really want to do that? + /// + /// + /// The number of objects deleted. + /// + /// + /// The type of objects to delete. + /// + public int DeleteAll () + { + var map = GetMapping (typeof (T)); + return DeleteAll (map); + } + + /// + /// Deletes all the objects from the specified table. + /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the + /// specified table. Do you really want to do that? + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The number of objects deleted. + /// + public int DeleteAll (TableMapping map) + { + var query = string.Format ("delete from \"{0}\"", map.TableName); + var count = Execute (query); + if (count > 0) + OnTableChanged (map, NotifyTableChangedAction.Delete); + return count; + } + + /// + /// Backup the entire database to the specified path. + /// + /// Path to backup file. + /// The name of the database to backup (usually "main"). + public void Backup (string destinationDatabasePath, string databaseName = "main") + { + // Open the destination + var r = SQLite3.Open (destinationDatabasePath, out var destHandle); + if (r != SQLite3.Result.OK) { + throw SQLiteException.New (r, "Failed to open destination database"); + } + + // Init the backup + var backup = SQLite3.BackupInit (destHandle, databaseName, Handle, databaseName); + if (backup == NullBackupHandle) { + SQLite3.Close (destHandle); + throw new Exception ("Failed to create backup"); + } + + // Perform it + SQLite3.BackupStep (backup, -1); + SQLite3.BackupFinish (backup); + + // Check for errors + r = SQLite3.GetResult (destHandle); + string msg = ""; + if (r != SQLite3.Result.OK) { + msg = SQLite3.GetErrmsg (destHandle); + } + + // Close everything and report errors + SQLite3.Close (destHandle); + if (r != SQLite3.Result.OK) { + throw SQLiteException.New (r, msg); + } + } + + ~SQLiteConnection () + { + Dispose (false); + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + public void Close () + { + Dispose (true); + } + + protected virtual void Dispose (bool disposing) + { + var useClose2 = LibVersionNumber >= 3007014; + + if (_open && Handle != NullHandle) { + try { + if (disposing) { + lock (_insertCommandMap) { + foreach (var sqlInsertCommand in _insertCommandMap.Values) { + sqlInsertCommand.Dispose (); + } + _insertCommandMap.Clear (); + } + + var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle); + if (r != SQLite3.Result.OK) { + string msg = SQLite3.GetErrmsg (Handle); + throw SQLiteException.New (r, msg); + } + } + else { + var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle); + } + } + finally { + Handle = NullHandle; + _open = false; + } + } + } + + void OnTableChanged (TableMapping table, NotifyTableChangedAction action) + { + var ev = TableChanged; + if (ev != null) + ev (this, new NotifyTableChangedEventArgs (table, action)); + } + + public event EventHandler TableChanged; + } + + public class NotifyTableChangedEventArgs : EventArgs + { + public TableMapping Table { get; private set; } + public NotifyTableChangedAction Action { get; private set; } + + public NotifyTableChangedEventArgs (TableMapping table, NotifyTableChangedAction action) + { + Table = table; + Action = action; + } + } + + public enum NotifyTableChangedAction + { + Insert, + Update, + Delete, + } + + /// + /// Represents a parsed connection string. + /// + public class SQLiteConnectionString + { + const string DateTimeSqliteDefaultFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff"; + + public string UniqueKey { get; } + public string DatabasePath { get; } + public bool StoreDateTimeAsTicks { get; } + public bool StoreTimeSpanAsTicks { get; } + public string DateTimeStringFormat { get; } + public System.Globalization.DateTimeStyles DateTimeStyle { get; } + public object Key { get; } + public SQLiteOpenFlags OpenFlags { get; } + public Action PreKeyAction { get; } + public Action PostKeyAction { get; } + public string VfsName { get; } + +#if NETFX_CORE + static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; + + public static readonly string[] InMemoryDbPaths = new[] + { + ":memory:", + "file::memory:" + }; + + public static bool IsInMemoryPath(string databasePath) + { + return InMemoryDbPaths.Any(i => i.Equals(databasePath, StringComparison.OrdinalIgnoreCase)); + } + +#endif + + /// + /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks = true) + : this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks) + { + } + + /// + /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + /// + /// Specifies the encryption key to use on the database. Should be a string or a byte[]. + /// + /// + /// Executes prior to setting key for SQLCipher databases + /// + /// + /// Executes after setting key for SQLCipher databases + /// + /// + /// Specifies the Virtual File System to use on the database. + /// + public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks, object key = null, Action preKeyAction = null, Action postKeyAction = null, string vfsName = null) + : this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks, key, preKeyAction, postKeyAction, vfsName) + { + } + + /// + /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Flags controlling how the connection should be opened. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + /// + /// Specifies the encryption key to use on the database. Should be a string or a byte[]. + /// + /// + /// Executes prior to setting key for SQLCipher databases + /// + /// + /// Executes after setting key for SQLCipher databases + /// + /// + /// Specifies the Virtual File System to use on the database. + /// + /// + /// Specifies the format to use when storing DateTime properties as strings. + /// + /// + /// Specifies whether to store TimeSpan properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeTimeSpanAsTicks = true. + /// + public SQLiteConnectionString (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks, object key = null, Action preKeyAction = null, Action postKeyAction = null, string vfsName = null, string dateTimeStringFormat = DateTimeSqliteDefaultFormat, bool storeTimeSpanAsTicks = true) + { + if (key != null && !((key is byte[]) || (key is string))) + throw new ArgumentException ("Encryption keys must be strings or byte arrays", nameof (key)); + + UniqueKey = string.Format ("{0}_{1:X8}", databasePath, (uint)openFlags); + StoreDateTimeAsTicks = storeDateTimeAsTicks; + StoreTimeSpanAsTicks = storeTimeSpanAsTicks; + DateTimeStringFormat = dateTimeStringFormat; + DateTimeStyle = "o".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) || "r".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) ? System.Globalization.DateTimeStyles.RoundtripKind : System.Globalization.DateTimeStyles.None; + Key = key; + PreKeyAction = preKeyAction; + PostKeyAction = postKeyAction; + OpenFlags = openFlags; + VfsName = vfsName; + +#if NETFX_CORE + DatabasePath = IsInMemoryPath(databasePath) + ? databasePath + : System.IO.Path.Combine(MetroStyleDataPath, databasePath); + +#else + DatabasePath = databasePath; +#endif + } + } + + [AttributeUsage (AttributeTargets.Class)] + public class TableAttribute : Attribute + { + public string Name { get; set; } + + /// + /// Flag whether to create the table without rowid (see https://sqlite.org/withoutrowid.html) + /// + /// The default is false so that sqlite adds an implicit rowid to every table created. + /// + public bool WithoutRowId { get; set; } + + public TableAttribute (string name) + { + Name = name; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public string Name { get; set; } + + public ColumnAttribute (string name) + { + Name = name; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class PrimaryKeyAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Property)] + public class AutoIncrementAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Property)] + public class IndexedAttribute : Attribute + { + public string Name { get; set; } + public int Order { get; set; } + public virtual bool Unique { get; set; } + + public IndexedAttribute () + { + } + + public IndexedAttribute (string name, int order) + { + Name = name; + Order = order; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class IgnoreAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Property)] + public class UniqueAttribute : IndexedAttribute + { + public override bool Unique { + get { return true; } + set { /* throw? */ } + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class MaxLengthAttribute : Attribute + { + public int Value { get; private set; } + + public MaxLengthAttribute (int length) + { + Value = length; + } + } + + public sealed class PreserveAttribute : System.Attribute + { + public bool AllMembers; + public bool Conditional; + } + + /// + /// Select the collating sequence to use on a column. + /// "BINARY", "NOCASE", and "RTRIM" are supported. + /// "BINARY" is the default. + /// + [AttributeUsage (AttributeTargets.Property)] + public class CollationAttribute : Attribute + { + public string Value { get; private set; } + + public CollationAttribute (string collation) + { + Value = collation; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class NotNullAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Enum)] + public class StoreAsTextAttribute : Attribute + { + } + + public class TableMapping + { + public Type MappedType { get; private set; } + + public string TableName { get; private set; } + + public bool WithoutRowId { get; private set; } + + public Column[] Columns { get; private set; } + + public Column PK { get; private set; } + + public string GetByPrimaryKeySql { get; private set; } + + public CreateFlags CreateFlags { get; private set; } + + readonly Column _autoPk; + readonly Column[] _insertColumns; + readonly Column[] _insertOrReplaceColumns; + + public TableMapping (Type type, CreateFlags createFlags = CreateFlags.None) + { + MappedType = type; + CreateFlags = createFlags; + + var typeInfo = type.GetTypeInfo (); + var tableAttr = + typeInfo.CustomAttributes + .Where (x => x.AttributeType == typeof (TableAttribute)) + .Select (x => (TableAttribute)Orm.InflateAttribute (x)) + .FirstOrDefault (); + + TableName = (tableAttr != null && !string.IsNullOrEmpty (tableAttr.Name)) ? tableAttr.Name : MappedType.Name; + WithoutRowId = tableAttr != null ? tableAttr.WithoutRowId : false; + + var props = new List (); + var baseType = type; + var propNames = new HashSet (); + while (baseType != typeof (object)) { + var ti = baseType.GetTypeInfo (); + var newProps = ( + from p in ti.DeclaredProperties + where + !propNames.Contains (p.Name) && + p.CanRead && p.CanWrite && + (p.GetMethod != null) && (p.SetMethod != null) && + (p.GetMethod.IsPublic && p.SetMethod.IsPublic) && + (!p.GetMethod.IsStatic) && (!p.SetMethod.IsStatic) + select p).ToList (); + foreach (var p in newProps) { + propNames.Add (p.Name); + } + props.AddRange (newProps); + baseType = ti.BaseType; + } + + var cols = new List (); + foreach (var p in props) { + var ignore = p.IsDefined (typeof (IgnoreAttribute), true); + if (!ignore) { + cols.Add (new Column (p, createFlags)); + } + } + Columns = cols.ToArray (); + foreach (var c in Columns) { + if (c.IsAutoInc && c.IsPK) { + _autoPk = c; + } + if (c.IsPK) { + PK = c; + } + } + + HasAutoIncPK = _autoPk != null; + + if (PK != null) { + GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name); + } + else { + // People should not be calling Get/Find without a PK + GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName); + } + + _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray (); + _insertOrReplaceColumns = Columns.ToArray (); + } + + public bool HasAutoIncPK { get; private set; } + + public void SetAutoIncPK (object obj, long id) + { + if (_autoPk != null) { + _autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null)); + } + } + + public Column[] InsertColumns { + get { + return _insertColumns; + } + } + + public Column[] InsertOrReplaceColumns { + get { + return _insertOrReplaceColumns; + } + } + + public Column FindColumnWithPropertyName (string propertyName) + { + var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName); + return exact; + } + + public Column FindColumn (string columnName) + { + var exact = Columns.FirstOrDefault (c => c.Name.ToLower () == columnName.ToLower ()); + return exact; + } + + public class Column + { + PropertyInfo _prop; + + public string Name { get; private set; } + + public PropertyInfo PropertyInfo => _prop; + + public string PropertyName { get { return _prop.Name; } } + + public Type ColumnType { get; private set; } + + public string Collation { get; private set; } + + public bool IsAutoInc { get; private set; } + public bool IsAutoGuid { get; private set; } + + public bool IsPK { get; private set; } + + public IEnumerable Indices { get; set; } + + public bool IsNullable { get; private set; } + + public int? MaxStringLength { get; private set; } + + public bool StoreAsText { get; private set; } + + public Column (PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) + { + var colAttr = prop.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (ColumnAttribute)); + + _prop = prop; + Name = (colAttr != null && colAttr.ConstructorArguments.Count > 0) ? + colAttr.ConstructorArguments[0].Value?.ToString () : + prop.Name; + //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead + ColumnType = Nullable.GetUnderlyingType (prop.PropertyType) ?? prop.PropertyType; + Collation = Orm.Collation (prop); + + IsPK = Orm.IsPK (prop) || + (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) && + string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); + + var isAuto = Orm.IsAutoInc (prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); + IsAutoGuid = isAuto && ColumnType == typeof (Guid); + IsAutoInc = isAuto && !IsAutoGuid; + + Indices = Orm.GetIndices (prop); + if (!Indices.Any () + && !IsPK + && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) + && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) + ) { + Indices = new IndexedAttribute[] { new IndexedAttribute () }; + } + IsNullable = !(IsPK || Orm.IsMarkedNotNull (prop)); + MaxStringLength = Orm.MaxStringLength (prop); + + StoreAsText = prop.PropertyType.GetTypeInfo ().CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute)); + } + + public void SetValue (object obj, object val) + { + if (val != null && ColumnType.GetTypeInfo ().IsEnum) { + _prop.SetValue (obj, Enum.ToObject (ColumnType, val)); + } + else { + _prop.SetValue (obj, val, null); + } + } + + public object GetValue (object obj) + { + return _prop.GetValue (obj, null); + } + } + } + + class EnumCacheInfo + { + public EnumCacheInfo (Type type) + { + var typeInfo = type.GetTypeInfo (); + + IsEnum = typeInfo.IsEnum; + + if (IsEnum) { + StoreAsText = typeInfo.CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute)); + + if (StoreAsText) { + EnumValues = new Dictionary (); + foreach (object e in Enum.GetValues (type)) { + EnumValues[Convert.ToInt32 (e)] = e.ToString (); + } + } + } + } + + public bool IsEnum { get; private set; } + + public bool StoreAsText { get; private set; } + + public Dictionary EnumValues { get; private set; } + } + + static class EnumCache + { + static readonly Dictionary Cache = new Dictionary (); + + public static EnumCacheInfo GetInfo () + { + return GetInfo (typeof (T)); + } + + public static EnumCacheInfo GetInfo (Type type) + { + lock (Cache) { + EnumCacheInfo info = null; + if (!Cache.TryGetValue (type, out info)) { + info = new EnumCacheInfo (type); + Cache[type] = info; + } + + return info; + } + } + } + + public static class Orm + { + public const int DefaultMaxStringLength = 140; + public const string ImplicitPkName = "Id"; + public const string ImplicitIndexSuffix = "Id"; + + public static Type GetType (object obj) + { + if (obj == null) + return typeof (object); + var rt = obj as IReflectableType; + if (rt != null) + return rt.GetTypeInfo ().AsType (); + return obj.GetType (); + } + + public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks) + { + string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks, storeTimeSpanAsTicks) + " "; + + if (p.IsPK) { + decl += "primary key "; + } + if (p.IsAutoInc) { + decl += "autoincrement "; + } + if (!p.IsNullable) { + decl += "not null "; + } + if (!string.IsNullOrEmpty (p.Collation)) { + decl += "collate " + p.Collation + " "; + } + + return decl; + } + + public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks) + { + var clrType = p.ColumnType; + if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32) || clrType == typeof (UInt32) || clrType == typeof (Int64)) { + return "integer"; + } + else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) { + return "float"; + } + else if (clrType == typeof (String) || clrType == typeof (StringBuilder) || clrType == typeof (Uri) || clrType == typeof (UriBuilder)) { + int? len = p.MaxStringLength; + + if (len.HasValue) + return "varchar(" + len.Value + ")"; + + return "varchar"; + } + else if (clrType == typeof (TimeSpan)) { + return storeTimeSpanAsTicks ? "bigint" : "time"; + } + else if (clrType == typeof (DateTime)) { + return storeDateTimeAsTicks ? "bigint" : "datetime"; + } + else if (clrType == typeof (DateTimeOffset)) { + return "bigint"; + } + else if (clrType.GetTypeInfo ().IsEnum) { + if (p.StoreAsText) + return "varchar"; + else + return "integer"; + } + else if (clrType == typeof (byte[])) { + return "blob"; + } + else if (clrType == typeof (Guid)) { + return "varchar(36)"; + } + else { + throw new NotSupportedException ("Don't know about " + clrType); + } + } + + public static bool IsPK (MemberInfo p) + { + return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute)); + } + + public static string Collation (MemberInfo p) + { + return + (p.CustomAttributes + .Where (x => typeof (CollationAttribute) == x.AttributeType) + .Select (x => { + var args = x.ConstructorArguments; + return args.Count > 0 ? ((args[0].Value as string) ?? "") : ""; + }) + .FirstOrDefault ()) ?? ""; + } + + public static bool IsAutoInc (MemberInfo p) + { + return p.CustomAttributes.Any (x => x.AttributeType == typeof (AutoIncrementAttribute)); + } + + public static FieldInfo GetField (TypeInfo t, string name) + { + var f = t.GetDeclaredField (name); + if (f != null) + return f; + return GetField (t.BaseType.GetTypeInfo (), name); + } + + public static PropertyInfo GetProperty (TypeInfo t, string name) + { + var f = t.GetDeclaredProperty (name); + if (f != null) + return f; + return GetProperty (t.BaseType.GetTypeInfo (), name); + } + + public static object InflateAttribute (CustomAttributeData x) + { + var atype = x.AttributeType; + var typeInfo = atype.GetTypeInfo (); + var args = x.ConstructorArguments.Select (a => a.Value).ToArray (); + var r = Activator.CreateInstance (x.AttributeType, args); + foreach (var arg in x.NamedArguments) { + if (arg.IsField) { + GetField (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value); + } + else { + GetProperty (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value); + } + } + return r; + } + + public static IEnumerable GetIndices (MemberInfo p) + { + var indexedInfo = typeof (IndexedAttribute).GetTypeInfo (); + return + p.CustomAttributes + .Where (x => indexedInfo.IsAssignableFrom (x.AttributeType.GetTypeInfo ())) + .Select (x => (IndexedAttribute)InflateAttribute (x)); + } + + public static int? MaxStringLength (PropertyInfo p) + { + var attr = p.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (MaxLengthAttribute)); + if (attr != null) { + var attrv = (MaxLengthAttribute)InflateAttribute (attr); + return attrv.Value; + } + return null; + } + + public static bool IsMarkedNotNull (MemberInfo p) + { + return p.CustomAttributes.Any (x => x.AttributeType == typeof (NotNullAttribute)); + } + } + + public partial class SQLiteCommand + { + SQLiteConnection _conn; + private List _bindings; + + public string CommandText { get; set; } + + public SQLiteCommand (SQLiteConnection conn) + { + _conn = conn; + _bindings = new List (); + CommandText = ""; + } + + public int ExecuteNonQuery () + { + if (_conn.Trace) { + _conn.Tracer?.Invoke ("Executing: " + this); + } + + var r = SQLite3.Result.OK; + var stmt = Prepare (); + r = SQLite3.Step (stmt); + Finalize (stmt); + if (r == SQLite3.Result.Done) { + int rowsAffected = SQLite3.Changes (_conn.Handle); + return rowsAffected; + } + else if (r == SQLite3.Result.Error) { + string msg = SQLite3.GetErrmsg (_conn.Handle); + throw SQLiteException.New (r, msg); + } + else if (r == SQLite3.Result.Constraint) { + if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { + throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle)); + } + } + + throw SQLiteException.New (r, r.ToString ()); + } + + public IEnumerable ExecuteDeferredQuery () + { + return ExecuteDeferredQuery (_conn.GetMapping (typeof (T))); + } + + public List ExecuteQuery () + { + return ExecuteDeferredQuery (_conn.GetMapping (typeof (T))).ToList (); + } + + public List ExecuteQuery (TableMapping map) + { + return ExecuteDeferredQuery (map).ToList (); + } + + /// + /// Invoked every time an instance is loaded from the database. + /// + /// + /// The newly created object. + /// + /// + /// This can be overridden in combination with the + /// method to hook into the life-cycle of objects. + /// + protected virtual void OnInstanceCreated (object obj) + { + // Can be overridden. + } + + public IEnumerable ExecuteDeferredQuery (TableMapping map) + { + if (_conn.Trace) { + _conn.Tracer?.Invoke ("Executing Query: " + this); + } + + var stmt = Prepare (); + try { + var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)]; + + for (int i = 0; i < cols.Length; i++) { + var name = SQLite3.ColumnName16 (stmt, i); + cols[i] = map.FindColumn (name); + } + + while (SQLite3.Step (stmt) == SQLite3.Result.Row) { + var obj = Activator.CreateInstance (map.MappedType); + for (int i = 0; i < cols.Length; i++) { + if (cols[i] == null) + continue; + var colType = SQLite3.ColumnType (stmt, i); + var val = ReadCol (stmt, i, colType, cols[i].ColumnType); + cols[i].SetValue (obj, val); + } + OnInstanceCreated (obj); + yield return (T)obj; + } + } + finally { + SQLite3.Finalize (stmt); + } + } + + public T ExecuteScalar () + { + if (_conn.Trace) { + _conn.Tracer?.Invoke ("Executing Query: " + this); + } + + T val = default (T); + + var stmt = Prepare (); + + try { + var r = SQLite3.Step (stmt); + if (r == SQLite3.Result.Row) { + var colType = SQLite3.ColumnType (stmt, 0); + val = (T)ReadCol (stmt, 0, colType, typeof (T)); + } + else if (r == SQLite3.Result.Done) { + } + else { + throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle)); + } + } + finally { + Finalize (stmt); + } + + return val; + } + + public void Bind (string name, object val) + { + _bindings.Add (new Binding { + Name = name, + Value = val + }); + } + + public void Bind (object val) + { + Bind (null, val); + } + + public override string ToString () + { + var parts = new string[1 + _bindings.Count]; + parts[0] = CommandText; + var i = 1; + foreach (var b in _bindings) { + parts[i] = string.Format (" {0}: {1}", i - 1, b.Value); + i++; + } + return string.Join (Environment.NewLine, parts); + } + + Sqlite3Statement Prepare () + { + var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText); + BindAll (stmt); + return stmt; + } + + void Finalize (Sqlite3Statement stmt) + { + SQLite3.Finalize (stmt); + } + + void BindAll (Sqlite3Statement stmt) + { + int nextIdx = 1; + foreach (var b in _bindings) { + if (b.Name != null) { + b.Index = SQLite3.BindParameterIndex (stmt, b.Name); + } + else { + b.Index = nextIdx++; + } + + BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks, _conn.DateTimeStringFormat, _conn.StoreTimeSpanAsTicks); + } + } + + static IntPtr NegativePointer = new IntPtr (-1); + + internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks, string dateTimeStringFormat, bool storeTimeSpanAsTicks) + { + if (value == null) { + SQLite3.BindNull (stmt, index); + } + else { + if (value is Int32) { + SQLite3.BindInt (stmt, index, (int)value); + } + else if (value is String) { + SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer); + } + else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { + SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); + } + else if (value is Boolean) { + SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0); + } + else if (value is UInt32 || value is Int64) { + SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value)); + } + else if (value is Single || value is Double || value is Decimal) { + SQLite3.BindDouble (stmt, index, Convert.ToDouble (value)); + } + else if (value is TimeSpan) { + if (storeTimeSpanAsTicks) { + SQLite3.BindInt64 (stmt, index, ((TimeSpan)value).Ticks); + } + else { + SQLite3.BindText (stmt, index, ((TimeSpan)value).ToString (), -1, NegativePointer); + } + } + else if (value is DateTime) { + if (storeDateTimeAsTicks) { + SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks); + } + else { + SQLite3.BindText (stmt, index, ((DateTime)value).ToString (dateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture), -1, NegativePointer); + } + } + else if (value is DateTimeOffset) { + SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks); + } + else if (value is byte[]) { + SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer); + } + else if (value is Guid) { + SQLite3.BindText (stmt, index, ((Guid)value).ToString (), 72, NegativePointer); + } + else if (value is Uri) { + SQLite3.BindText (stmt, index, ((Uri)value).ToString (), -1, NegativePointer); + } + else if (value is StringBuilder) { + SQLite3.BindText (stmt, index, ((StringBuilder)value).ToString (), -1, NegativePointer); + } + else if (value is UriBuilder) { + SQLite3.BindText (stmt, index, ((UriBuilder)value).ToString (), -1, NegativePointer); + } + else { + // Now we could possibly get an enum, retrieve cached info + var valueType = value.GetType (); + var enumInfo = EnumCache.GetInfo (valueType); + if (enumInfo.IsEnum) { + var enumIntValue = Convert.ToInt32 (value); + if (enumInfo.StoreAsText) + SQLite3.BindText (stmt, index, enumInfo.EnumValues[enumIntValue], -1, NegativePointer); + else + SQLite3.BindInt (stmt, index, enumIntValue); + } + else { + throw new NotSupportedException ("Cannot store type: " + Orm.GetType (value)); + } + } + } + } + + class Binding + { + public string Name { get; set; } + + public object Value { get; set; } + + public int Index { get; set; } + } + + object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType) + { + if (type == SQLite3.ColType.Null) { + return null; + } + else { + var clrTypeInfo = clrType.GetTypeInfo (); + if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) { + clrType = clrTypeInfo.GenericTypeArguments[0]; + clrTypeInfo = clrType.GetTypeInfo (); + } + + if (clrType == typeof (String)) { + return SQLite3.ColumnString (stmt, index); + } + else if (clrType == typeof (Int32)) { + return (int)SQLite3.ColumnInt (stmt, index); + } + else if (clrType == typeof (Boolean)) { + return SQLite3.ColumnInt (stmt, index) == 1; + } + else if (clrType == typeof (double)) { + return SQLite3.ColumnDouble (stmt, index); + } + else if (clrType == typeof (float)) { + return (float)SQLite3.ColumnDouble (stmt, index); + } + else if (clrType == typeof (TimeSpan)) { + if (_conn.StoreTimeSpanAsTicks) { + return new TimeSpan (SQLite3.ColumnInt64 (stmt, index)); + } + else { + var text = SQLite3.ColumnString (stmt, index); + TimeSpan resultTime; + if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) { + resultTime = TimeSpan.Parse (text); + } + return resultTime; + } + } + else if (clrType == typeof (DateTime)) { + if (_conn.StoreDateTimeAsTicks) { + return new DateTime (SQLite3.ColumnInt64 (stmt, index)); + } + else { + var text = SQLite3.ColumnString (stmt, index); + DateTime resultDate; + if (!DateTime.TryParseExact (text, _conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, _conn.DateTimeStyle, out resultDate)) { + resultDate = DateTime.Parse (text); + } + return resultDate; + } + } + else if (clrType == typeof (DateTimeOffset)) { + return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero); + } + else if (clrTypeInfo.IsEnum) { + if (type == SQLite3.ColType.Text) { + var value = SQLite3.ColumnString (stmt, index); + return Enum.Parse (clrType, value.ToString (), true); + } + else + return SQLite3.ColumnInt (stmt, index); + } + else if (clrType == typeof (Int64)) { + return SQLite3.ColumnInt64 (stmt, index); + } + else if (clrType == typeof (UInt32)) { + return (uint)SQLite3.ColumnInt64 (stmt, index); + } + else if (clrType == typeof (decimal)) { + return (decimal)SQLite3.ColumnDouble (stmt, index); + } + else if (clrType == typeof (Byte)) { + return (byte)SQLite3.ColumnInt (stmt, index); + } + else if (clrType == typeof (UInt16)) { + return (ushort)SQLite3.ColumnInt (stmt, index); + } + else if (clrType == typeof (Int16)) { + return (short)SQLite3.ColumnInt (stmt, index); + } + else if (clrType == typeof (sbyte)) { + return (sbyte)SQLite3.ColumnInt (stmt, index); + } + else if (clrType == typeof (byte[])) { + return SQLite3.ColumnByteArray (stmt, index); + } + else if (clrType == typeof (Guid)) { + var text = SQLite3.ColumnString (stmt, index); + return new Guid (text); + } + else if (clrType == typeof(Uri)) { + var text = SQLite3.ColumnString(stmt, index); + return new Uri(text); + } + else if (clrType == typeof (StringBuilder)) { + var text = SQLite3.ColumnString (stmt, index); + return new StringBuilder (text); + } + else if (clrType == typeof(UriBuilder)) { + var text = SQLite3.ColumnString(stmt, index); + return new UriBuilder(text); + } + else { + throw new NotSupportedException ("Don't know how to read " + clrType); + } + } + } + } + + /// + /// Since the insert never changed, we only need to prepare once. + /// + class PreparedSqlLiteInsertCommand : IDisposable + { + bool Initialized; + + SQLiteConnection Connection; + + string CommandText; + + Sqlite3Statement Statement; + static readonly Sqlite3Statement NullStatement = default (Sqlite3Statement); + + public PreparedSqlLiteInsertCommand (SQLiteConnection conn, string commandText) + { + Connection = conn; + CommandText = commandText; + } + + public int ExecuteNonQuery (object[] source) + { + if (Initialized && Statement == NullStatement) { + throw new ObjectDisposedException (nameof (PreparedSqlLiteInsertCommand)); + } + + if (Connection.Trace) { + Connection.Tracer?.Invoke ("Executing: " + CommandText); + } + + var r = SQLite3.Result.OK; + + if (!Initialized) { + Statement = SQLite3.Prepare2 (Connection.Handle, CommandText); + Initialized = true; + } + + //bind the values. + if (source != null) { + for (int i = 0; i < source.Length; i++) { + SQLiteCommand.BindParameter (Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks, Connection.DateTimeStringFormat, Connection.StoreTimeSpanAsTicks); + } + } + r = SQLite3.Step (Statement); + + if (r == SQLite3.Result.Done) { + int rowsAffected = SQLite3.Changes (Connection.Handle); + SQLite3.Reset (Statement); + return rowsAffected; + } + else if (r == SQLite3.Result.Error) { + string msg = SQLite3.GetErrmsg (Connection.Handle); + SQLite3.Reset (Statement); + throw SQLiteException.New (r, msg); + } + else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { + SQLite3.Reset (Statement); + throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle)); + } + else { + SQLite3.Reset (Statement); + throw SQLiteException.New (r, r.ToString ()); + } + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + void Dispose (bool disposing) + { + var s = Statement; + Statement = NullStatement; + Connection = null; + if (s != NullStatement) { + SQLite3.Finalize (s); + } + } + + ~PreparedSqlLiteInsertCommand () + { + Dispose (false); + } + } + + public enum CreateTableResult + { + Created, + Migrated, + } + + public class CreateTablesResult + { + public Dictionary Results { get; private set; } + + public CreateTablesResult () + { + Results = new Dictionary (); + } + } + + public abstract class BaseTableQuery + { + protected class Ordering + { + public string ColumnName { get; set; } + public bool Ascending { get; set; } + } + } + + public class TableQuery : BaseTableQuery, IEnumerable + { + public SQLiteConnection Connection { get; private set; } + + public TableMapping Table { get; private set; } + + Expression _where; + List _orderBys; + int? _limit; + int? _offset; + + BaseTableQuery _joinInner; + Expression _joinInnerKeySelector; + BaseTableQuery _joinOuter; + Expression _joinOuterKeySelector; + Expression _joinSelector; + + Expression _selector; + + TableQuery (SQLiteConnection conn, TableMapping table) + { + Connection = conn; + Table = table; + } + + public TableQuery (SQLiteConnection conn) + { + Connection = conn; + Table = Connection.GetMapping (typeof (T)); + } + + public TableQuery Clone () + { + var q = new TableQuery (Connection, Table); + q._where = _where; + q._deferred = _deferred; + if (_orderBys != null) { + q._orderBys = new List (_orderBys); + } + q._limit = _limit; + q._offset = _offset; + q._joinInner = _joinInner; + q._joinInnerKeySelector = _joinInnerKeySelector; + q._joinOuter = _joinOuter; + q._joinOuterKeySelector = _joinOuterKeySelector; + q._joinSelector = _joinSelector; + q._selector = _selector; + return q; + } + + /// + /// Filters the query based on a predicate. + /// + public TableQuery Where (Expression> predExpr) + { + if (predExpr.NodeType == ExpressionType.Lambda) { + var lambda = (LambdaExpression)predExpr; + var pred = lambda.Body; + var q = Clone (); + q.AddWhere (pred); + return q; + } + else { + throw new NotSupportedException ("Must be a predicate"); + } + } + + /// + /// Delete all the rows that match this query. + /// + public int Delete () + { + return Delete (null); + } + + /// + /// Delete all the rows that match this query and the given predicate. + /// + public int Delete (Expression> predExpr) + { + if (_limit.HasValue || _offset.HasValue) + throw new InvalidOperationException ("Cannot delete with limits or offsets"); + + if (_where == null && predExpr == null) + throw new InvalidOperationException ("No condition specified"); + + var pred = _where; + + if (predExpr != null && predExpr.NodeType == ExpressionType.Lambda) { + var lambda = (LambdaExpression)predExpr; + pred = pred != null ? Expression.AndAlso (pred, lambda.Body) : lambda.Body; + } + + var args = new List (); + var cmdText = "delete from \"" + Table.TableName + "\""; + var w = CompileExpr (pred, args); + cmdText += " where " + w.CommandText; + + var command = Connection.CreateCommand (cmdText, args.ToArray ()); + + int result = command.ExecuteNonQuery (); + return result; + } + + /// + /// Yields a given number of elements from the query and then skips the remainder. + /// + public TableQuery Take (int n) + { + var q = Clone (); + q._limit = n; + return q; + } + + /// + /// Skips a given number of elements from the query and then yields the remainder. + /// + public TableQuery Skip (int n) + { + var q = Clone (); + q._offset = n; + return q; + } + + /// + /// Returns the element at a given index + /// + public T ElementAt (int index) + { + return Skip (index).Take (1).First (); + } + + bool _deferred; + public TableQuery Deferred () + { + var q = Clone (); + q._deferred = true; + return q; + } + + /// + /// Order the query results according to a key. + /// + public TableQuery OrderBy (Expression> orderExpr) + { + return AddOrderBy (orderExpr, true); + } + + /// + /// Order the query results according to a key. + /// + public TableQuery OrderByDescending (Expression> orderExpr) + { + return AddOrderBy (orderExpr, false); + } + + /// + /// Order the query results according to a key. + /// + public TableQuery ThenBy (Expression> orderExpr) + { + return AddOrderBy (orderExpr, true); + } + + /// + /// Order the query results according to a key. + /// + public TableQuery ThenByDescending (Expression> orderExpr) + { + return AddOrderBy (orderExpr, false); + } + + TableQuery AddOrderBy (Expression> orderExpr, bool asc) + { + if (orderExpr.NodeType == ExpressionType.Lambda) { + var lambda = (LambdaExpression)orderExpr; + + MemberExpression mem = null; + + var unary = lambda.Body as UnaryExpression; + if (unary != null && unary.NodeType == ExpressionType.Convert) { + mem = unary.Operand as MemberExpression; + } + else { + mem = lambda.Body as MemberExpression; + } + + if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { + var q = Clone (); + if (q._orderBys == null) { + q._orderBys = new List (); + } + q._orderBys.Add (new Ordering { + ColumnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name, + Ascending = asc + }); + return q; + } + else { + throw new NotSupportedException ("Order By does not support: " + orderExpr); + } + } + else { + throw new NotSupportedException ("Must be a predicate"); + } + } + + private void AddWhere (Expression pred) + { + if (_where == null) { + _where = pred; + } + else { + _where = Expression.AndAlso (_where, pred); + } + } + + ///// + ///// Performs an inner join of two queries based on matching keys extracted from the elements. + ///// + //public TableQuery Join ( + // TableQuery inner, + // Expression> outerKeySelector, + // Expression> innerKeySelector, + // Expression> resultSelector) + //{ + // var q = new TableQuery (Connection, Connection.GetMapping (typeof (TResult))) { + // _joinOuter = this, + // _joinOuterKeySelector = outerKeySelector, + // _joinInner = inner, + // _joinInnerKeySelector = innerKeySelector, + // _joinSelector = resultSelector, + // }; + // return q; + //} + + // Not needed until Joins are supported + // Keeping this commented out forces the default Linq to objects processor to run + //public TableQuery Select (Expression> selector) + //{ + // var q = Clone (); + // q._selector = selector; + // return q; + //} + + private SQLiteCommand GenerateCommand (string selectionList) + { + if (_joinInner != null && _joinOuter != null) { + throw new NotSupportedException ("Joins are not supported."); + } + else { + var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\""; + var args = new List (); + if (_where != null) { + var w = CompileExpr (_where, args); + cmdText += " where " + w.CommandText; + } + if ((_orderBys != null) && (_orderBys.Count > 0)) { + var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ()); + cmdText += " order by " + t; + } + if (_limit.HasValue) { + cmdText += " limit " + _limit.Value; + } + if (_offset.HasValue) { + if (!_limit.HasValue) { + cmdText += " limit -1 "; + } + cmdText += " offset " + _offset.Value; + } + return Connection.CreateCommand (cmdText, args.ToArray ()); + } + } + + class CompileResult + { + public string CommandText { get; set; } + + public object Value { get; set; } + } + + private CompileResult CompileExpr (Expression expr, List queryArgs) + { + if (expr == null) { + throw new NotSupportedException ("Expression is NULL"); + } + else if (expr is BinaryExpression) { + var bin = (BinaryExpression)expr; + + // VB turns 'x=="foo"' into 'CompareString(x,"foo",true/false)==0', so we need to unwrap it + // http://blogs.msdn.com/b/vbteam/archive/2007/09/18/vb-expression-trees-string-comparisons.aspx + if (bin.Left.NodeType == ExpressionType.Call) { + var call = (MethodCallExpression)bin.Left; + if (call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators" + && call.Method.Name == "CompareString") + bin = Expression.MakeBinary (bin.NodeType, call.Arguments[0], call.Arguments[1]); + } + + + var leftr = CompileExpr (bin.Left, queryArgs); + var rightr = CompileExpr (bin.Right, queryArgs); + + //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") + string text; + if (leftr.CommandText == "?" && leftr.Value == null) + text = CompileNullBinaryExpression (bin, rightr); + else if (rightr.CommandText == "?" && rightr.Value == null) + text = CompileNullBinaryExpression (bin, leftr); + else + text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")"; + return new CompileResult { CommandText = text }; + } + else if (expr.NodeType == ExpressionType.Not) { + var operandExpr = ((UnaryExpression)expr).Operand; + var opr = CompileExpr (operandExpr, queryArgs); + object val = opr.Value; + if (val is bool) + val = !((bool)val); + return new CompileResult { + CommandText = "NOT(" + opr.CommandText + ")", + Value = val + }; + } + else if (expr.NodeType == ExpressionType.Call) { + + var call = (MethodCallExpression)expr; + var args = new CompileResult[call.Arguments.Count]; + var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null; + + for (var i = 0; i < args.Length; i++) { + args[i] = CompileExpr (call.Arguments[i], queryArgs); + } + + var sqlCall = ""; + + if (call.Method.Name == "Like" && args.Length == 2) { + sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")"; + } + else if (call.Method.Name == "Contains" && args.Length == 2) { + sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")"; + } + else if (call.Method.Name == "Contains" && args.Length == 1) { + if (call.Object != null && call.Object.Type == typeof (string)) { + sqlCall = "( instr(" + obj.CommandText + "," + args[0].CommandText + ") >0 )"; + } + else { + sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")"; + } + } + else if (call.Method.Name == "StartsWith" && args.Length >= 1) { + var startsWithCmpOp = StringComparison.CurrentCulture; + if (args.Length == 2) { + startsWithCmpOp = (StringComparison)args[1].Value; + } + switch (startsWithCmpOp) { + case StringComparison.Ordinal: + case StringComparison.CurrentCulture: + sqlCall = "( substr(" + obj.CommandText + ", 1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")"; + break; + case StringComparison.OrdinalIgnoreCase: + case StringComparison.CurrentCultureIgnoreCase: + sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))"; + break; + } + + } + else if (call.Method.Name == "EndsWith" && args.Length >= 1) { + var endsWithCmpOp = StringComparison.CurrentCulture; + if (args.Length == 2) { + endsWithCmpOp = (StringComparison)args[1].Value; + } + switch (endsWithCmpOp) { + case StringComparison.Ordinal: + case StringComparison.CurrentCulture: + sqlCall = "( substr(" + obj.CommandText + ", length(" + obj.CommandText + ") - " + args[0].Value.ToString ().Length + "+1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")"; + break; + case StringComparison.OrdinalIgnoreCase: + case StringComparison.CurrentCultureIgnoreCase: + sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))"; + break; + } + } + else if (call.Method.Name == "Equals" && args.Length == 1) { + sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))"; + } + else if (call.Method.Name == "ToLower") { + sqlCall = "(lower(" + obj.CommandText + "))"; + } + else if (call.Method.Name == "ToUpper") { + sqlCall = "(upper(" + obj.CommandText + "))"; + } + else if (call.Method.Name == "Replace" && args.Length == 2) { + sqlCall = "(replace(" + obj.CommandText + "," + args[0].CommandText + "," + args[1].CommandText + "))"; + } + else { + sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")"; + } + return new CompileResult { CommandText = sqlCall }; + + } + else if (expr.NodeType == ExpressionType.Constant) { + var c = (ConstantExpression)expr; + queryArgs.Add (c.Value); + return new CompileResult { + CommandText = "?", + Value = c.Value + }; + } + else if (expr.NodeType == ExpressionType.Convert) { + var u = (UnaryExpression)expr; + var ty = u.Type; + var valr = CompileExpr (u.Operand, queryArgs); + return new CompileResult { + CommandText = valr.CommandText, + Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null + }; + } + else if (expr.NodeType == ExpressionType.MemberAccess) { + var mem = (MemberExpression)expr; + + var paramExpr = mem.Expression as ParameterExpression; + if (paramExpr == null) { + var convert = mem.Expression as UnaryExpression; + if (convert != null && convert.NodeType == ExpressionType.Convert) { + paramExpr = convert.Operand as ParameterExpression; + } + } + + if (paramExpr != null) { + // + // This is a column of our table, output just the column name + // Need to translate it if that column name is mapped + // + var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name; + return new CompileResult { CommandText = "\"" + columnName + "\"" }; + } + else { + object obj = null; + if (mem.Expression != null) { + var r = CompileExpr (mem.Expression, queryArgs); + if (r.Value == null) { + throw new NotSupportedException ("Member access failed to compile expression"); + } + if (r.CommandText == "?") { + queryArgs.RemoveAt (queryArgs.Count - 1); + } + obj = r.Value; + } + + // + // Get the member value + // + object val = null; + + if (mem.Member is PropertyInfo) { + var m = (PropertyInfo)mem.Member; + val = m.GetValue (obj, null); + } + else if (mem.Member is FieldInfo) { + var m = (FieldInfo)mem.Member; + val = m.GetValue (obj); + } + else { + throw new NotSupportedException ("MemberExpr: " + mem.Member.GetType ()); + } + + // + // Work special magic for enumerables + // + if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable)) { + var sb = new System.Text.StringBuilder (); + sb.Append ("("); + var head = ""; + foreach (var a in (System.Collections.IEnumerable)val) { + queryArgs.Add (a); + sb.Append (head); + sb.Append ("?"); + head = ","; + } + sb.Append (")"); + return new CompileResult { + CommandText = sb.ToString (), + Value = val + }; + } + else { + queryArgs.Add (val); + return new CompileResult { + CommandText = "?", + Value = val + }; + } + } + } + throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ()); + } + + static object ConvertTo (object obj, Type t) + { + Type nut = Nullable.GetUnderlyingType (t); + + if (nut != null) { + if (obj == null) return null; + return Convert.ChangeType (obj, nut); + } + else { + return Convert.ChangeType (obj, t); + } + } + + /// + /// Compiles a BinaryExpression where one of the parameters is null. + /// + /// The expression to compile + /// The non-null parameter + private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter) + { + if (expression.NodeType == ExpressionType.Equal) + return "(" + parameter.CommandText + " is ?)"; + else if (expression.NodeType == ExpressionType.NotEqual) + return "(" + parameter.CommandText + " is not ?)"; + else if (expression.NodeType == ExpressionType.GreaterThan + || expression.NodeType == ExpressionType.GreaterThanOrEqual + || expression.NodeType == ExpressionType.LessThan + || expression.NodeType == ExpressionType.LessThanOrEqual) + return "(" + parameter.CommandText + " < ?)"; // always false + else + throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ()); + } + + string GetSqlName (Expression expr) + { + var n = expr.NodeType; + if (n == ExpressionType.GreaterThan) + return ">"; + else if (n == ExpressionType.GreaterThanOrEqual) { + return ">="; + } + else if (n == ExpressionType.LessThan) { + return "<"; + } + else if (n == ExpressionType.LessThanOrEqual) { + return "<="; + } + else if (n == ExpressionType.And) { + return "&"; + } + else if (n == ExpressionType.AndAlso) { + return "and"; + } + else if (n == ExpressionType.Or) { + return "|"; + } + else if (n == ExpressionType.OrElse) { + return "or"; + } + else if (n == ExpressionType.Equal) { + return "="; + } + else if (n == ExpressionType.NotEqual) { + return "!="; + } + else { + throw new NotSupportedException ("Cannot get SQL for: " + n); + } + } + + /// + /// Execute SELECT COUNT(*) on the query + /// + public int Count () + { + return GenerateCommand ("count(*)").ExecuteScalar (); + } + + /// + /// Execute SELECT COUNT(*) on the query with an additional WHERE clause. + /// + public int Count (Expression> predExpr) + { + return Where (predExpr).Count (); + } + + public IEnumerator GetEnumerator () + { + if (!_deferred) + return GenerateCommand ("*").ExecuteQuery ().GetEnumerator (); + + return GenerateCommand ("*").ExecuteDeferredQuery ().GetEnumerator (); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () + { + return GetEnumerator (); + } + + /// + /// Queries the database and returns the results as a List. + /// + public List ToList () + { + return GenerateCommand ("*").ExecuteQuery (); + } + + /// + /// Queries the database and returns the results as an array. + /// + public T[] ToArray () + { + return GenerateCommand ("*").ExecuteQuery ().ToArray (); + } + + /// + /// Returns the first element of this query. + /// + public T First () + { + var query = Take (1); + return query.ToList ().First (); + } + + /// + /// Returns the first element of this query, or null if no element is found. + /// + public T FirstOrDefault () + { + var query = Take (1); + return query.ToList ().FirstOrDefault (); + } + + /// + /// Returns the first element of this query that matches the predicate. + /// + public T First (Expression> predExpr) + { + return Where (predExpr).First (); + } + + /// + /// Returns the first element of this query that matches the predicate, or null + /// if no element is found. + /// + public T FirstOrDefault (Expression> predExpr) + { + return Where (predExpr).FirstOrDefault (); + } + } + + public static class SQLite3 + { + public enum Result : int + { + OK = 0, + Error = 1, + Internal = 2, + Perm = 3, + Abort = 4, + Busy = 5, + Locked = 6, + NoMem = 7, + ReadOnly = 8, + Interrupt = 9, + IOError = 10, + Corrupt = 11, + NotFound = 12, + Full = 13, + CannotOpen = 14, + LockErr = 15, + Empty = 16, + SchemaChngd = 17, + TooBig = 18, + Constraint = 19, + Mismatch = 20, + Misuse = 21, + NotImplementedLFS = 22, + AccessDenied = 23, + Format = 24, + Range = 25, + NonDBFile = 26, + Notice = 27, + Warning = 28, + Row = 100, + Done = 101 + } + + public enum ExtendedResult : int + { + IOErrorRead = (Result.IOError | (1 << 8)), + IOErrorShortRead = (Result.IOError | (2 << 8)), + IOErrorWrite = (Result.IOError | (3 << 8)), + IOErrorFsync = (Result.IOError | (4 << 8)), + IOErrorDirFSync = (Result.IOError | (5 << 8)), + IOErrorTruncate = (Result.IOError | (6 << 8)), + IOErrorFStat = (Result.IOError | (7 << 8)), + IOErrorUnlock = (Result.IOError | (8 << 8)), + IOErrorRdlock = (Result.IOError | (9 << 8)), + IOErrorDelete = (Result.IOError | (10 << 8)), + IOErrorBlocked = (Result.IOError | (11 << 8)), + IOErrorNoMem = (Result.IOError | (12 << 8)), + IOErrorAccess = (Result.IOError | (13 << 8)), + IOErrorCheckReservedLock = (Result.IOError | (14 << 8)), + IOErrorLock = (Result.IOError | (15 << 8)), + IOErrorClose = (Result.IOError | (16 << 8)), + IOErrorDirClose = (Result.IOError | (17 << 8)), + IOErrorSHMOpen = (Result.IOError | (18 << 8)), + IOErrorSHMSize = (Result.IOError | (19 << 8)), + IOErrorSHMLock = (Result.IOError | (20 << 8)), + IOErrorSHMMap = (Result.IOError | (21 << 8)), + IOErrorSeek = (Result.IOError | (22 << 8)), + IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)), + IOErrorMMap = (Result.IOError | (24 << 8)), + LockedSharedcache = (Result.Locked | (1 << 8)), + BusyRecovery = (Result.Busy | (1 << 8)), + CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)), + CannotOpenIsDir = (Result.CannotOpen | (2 << 8)), + CannotOpenFullPath = (Result.CannotOpen | (3 << 8)), + CorruptVTab = (Result.Corrupt | (1 << 8)), + ReadonlyRecovery = (Result.ReadOnly | (1 << 8)), + ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)), + ReadonlyRollback = (Result.ReadOnly | (3 << 8)), + AbortRollback = (Result.Abort | (2 << 8)), + ConstraintCheck = (Result.Constraint | (1 << 8)), + ConstraintCommitHook = (Result.Constraint | (2 << 8)), + ConstraintForeignKey = (Result.Constraint | (3 << 8)), + ConstraintFunction = (Result.Constraint | (4 << 8)), + ConstraintNotNull = (Result.Constraint | (5 << 8)), + ConstraintPrimaryKey = (Result.Constraint | (6 << 8)), + ConstraintTrigger = (Result.Constraint | (7 << 8)), + ConstraintUnique = (Result.Constraint | (8 << 8)), + ConstraintVTab = (Result.Constraint | (9 << 8)), + NoticeRecoverWAL = (Result.Notice | (1 << 8)), + NoticeRecoverRollback = (Result.Notice | (2 << 8)) + } + + + public enum ConfigOption : int + { + SingleThread = 1, + MultiThread = 2, + Serialized = 3 + } + + const string LibraryPath = "sqlite3"; + +#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE && !USE_SQLITEPCL_RAW + [DllImport(LibraryPath, EntryPoint = "sqlite3_threadsafe", CallingConvention=CallingConvention.Cdecl)] + public static extern int Threadsafe (); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] + public static extern Result Open(byte[] filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)] + public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)] + public static extern Result EnableLoadExtension (IntPtr db, int onoff); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Close (IntPtr db); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_close_v2", CallingConvention = CallingConvention.Cdecl)] + public static extern Result Close2(IntPtr db); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Initialize(); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Shutdown(); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Config (ConfigOption option); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)] + public static extern int SetDirectory (uint directoryType, string directoryPath); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)] + public static extern Result BusyTimeout (IntPtr db, int milliseconds); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)] + public static extern int Changes (IntPtr db); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); + +#if NETFX_CORE + [DllImport (LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] + public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail); +#endif + + public static IntPtr Prepare2 (IntPtr db, string query) + { + IntPtr stmt; +#if NETFX_CORE + byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query); + var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero); +#else + var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero); +#endif + if (r != Result.OK) { + throw SQLiteException.New (r, GetErrmsg (db)); + } + return stmt; + } + + [DllImport(LibraryPath, EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Step (IntPtr stmt); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Reset (IntPtr stmt); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Finalize (IntPtr stmt); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)] + public static extern long LastInsertRowid (IntPtr db); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr Errmsg (IntPtr db); + + public static string GetErrmsg (IntPtr db) + { + return Marshal.PtrToStringUni (Errmsg (db)); + } + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindNull (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindInt (IntPtr stmt, int index, int val); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindInt64 (IntPtr stmt, int index, long val); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindDouble (IntPtr stmt, int index, double val); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)] + public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)] + public static extern int ColumnCount (IntPtr stmt); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnName (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)] + static extern IntPtr ColumnName16Internal (IntPtr stmt, int index); + public static string ColumnName16(IntPtr stmt, int index) + { + return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index)); + } + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)] + public static extern ColType ColumnType (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)] + public static extern int ColumnInt (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)] + public static extern long ColumnInt64 (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)] + public static extern double ColumnDouble (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnText (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnText16 (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnBlob (IntPtr stmt, int index); + + [DllImport(LibraryPath, EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)] + public static extern int ColumnBytes (IntPtr stmt, int index); + + public static string ColumnString (IntPtr stmt, int index) + { + return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index)); + } + + public static byte[] ColumnByteArray (IntPtr stmt, int index) + { + int length = ColumnBytes (stmt, index); + var result = new byte[length]; + if (length > 0) + Marshal.Copy (ColumnBlob (stmt, index), result, 0, length); + return result; + } + + [DllImport (LibraryPath, EntryPoint = "sqlite3_errcode", CallingConvention = CallingConvention.Cdecl)] + public static extern Result GetResult (Sqlite3DatabaseHandle db); + + [DllImport (LibraryPath, EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)] + public static extern ExtendedResult ExtendedErrCode (IntPtr db); + + [DllImport (LibraryPath, EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)] + public static extern int LibVersionNumber (); + + [DllImport (LibraryPath, EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)] + public static extern Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, [MarshalAs (UnmanagedType.LPStr)] string destName, Sqlite3DatabaseHandle sourceDb, [MarshalAs (UnmanagedType.LPStr)] string sourceName); + + [DllImport (LibraryPath, EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)] + public static extern Result BackupStep (Sqlite3BackupHandle backup, int numPages); + + [DllImport (LibraryPath, EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)] + public static extern Result BackupFinish (Sqlite3BackupHandle backup); +#else + public static Result Open (string filename, out Sqlite3DatabaseHandle db) + { + return (Result)Sqlite3.sqlite3_open (filename, out db); + } + + public static Result Open (string filename, out Sqlite3DatabaseHandle db, int flags, string vfsName) + { +#if USE_WP8_NATIVE_SQLITE + return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, vfsName ?? ""); +#else + return (Result)Sqlite3.sqlite3_open_v2 (filename, out db, flags, vfsName); +#endif + } + + public static Result Close (Sqlite3DatabaseHandle db) + { + return (Result)Sqlite3.sqlite3_close (db); + } + + public static Result Close2 (Sqlite3DatabaseHandle db) + { + return (Result)Sqlite3.sqlite3_close_v2 (db); + } + + public static Result BusyTimeout (Sqlite3DatabaseHandle db, int milliseconds) + { + return (Result)Sqlite3.sqlite3_busy_timeout (db, milliseconds); + } + + public static int Changes (Sqlite3DatabaseHandle db) + { + return Sqlite3.sqlite3_changes (db); + } + + public static Sqlite3Statement Prepare2 (Sqlite3DatabaseHandle db, string query) + { + Sqlite3Statement stmt = default (Sqlite3Statement); +#if USE_WP8_NATIVE_SQLITE || USE_SQLITEPCL_RAW + var r = Sqlite3.sqlite3_prepare_v2 (db, query, out stmt); +#else + stmt = new Sqlite3Statement(); + var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0); +#endif + if (r != 0) { + throw SQLiteException.New ((Result)r, GetErrmsg (db)); + } + return stmt; + } + + public static Result Step (Sqlite3Statement stmt) + { + return (Result)Sqlite3.sqlite3_step (stmt); + } + + public static Result Reset (Sqlite3Statement stmt) + { + return (Result)Sqlite3.sqlite3_reset (stmt); + } + + public static Result Finalize (Sqlite3Statement stmt) + { + return (Result)Sqlite3.sqlite3_finalize (stmt); + } + + public static long LastInsertRowid (Sqlite3DatabaseHandle db) + { + return Sqlite3.sqlite3_last_insert_rowid (db); + } + + public static string GetErrmsg (Sqlite3DatabaseHandle db) + { + return Sqlite3.sqlite3_errmsg (db); + } + + public static int BindParameterIndex (Sqlite3Statement stmt, string name) + { + return Sqlite3.sqlite3_bind_parameter_index (stmt, name); + } + + public static int BindNull (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_bind_null (stmt, index); + } + + public static int BindInt (Sqlite3Statement stmt, int index, int val) + { + return Sqlite3.sqlite3_bind_int (stmt, index, val); + } + + public static int BindInt64 (Sqlite3Statement stmt, int index, long val) + { + return Sqlite3.sqlite3_bind_int64 (stmt, index, val); + } + + public static int BindDouble (Sqlite3Statement stmt, int index, double val) + { + return Sqlite3.sqlite3_bind_double (stmt, index, val); + } + + public static int BindText (Sqlite3Statement stmt, int index, string val, int n, IntPtr free) + { +#if USE_WP8_NATIVE_SQLITE + return Sqlite3.sqlite3_bind_text(stmt, index, val, n); +#elif USE_SQLITEPCL_RAW + return Sqlite3.sqlite3_bind_text (stmt, index, val); +#else + return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null); +#endif + } + + public static int BindBlob (Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free) + { +#if USE_WP8_NATIVE_SQLITE + return Sqlite3.sqlite3_bind_blob(stmt, index, val, n); +#elif USE_SQLITEPCL_RAW + return Sqlite3.sqlite3_bind_blob (stmt, index, val); +#else + return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null); +#endif + } + + public static int ColumnCount (Sqlite3Statement stmt) + { + return Sqlite3.sqlite3_column_count (stmt); + } + + public static string ColumnName (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_name (stmt, index); + } + + public static string ColumnName16 (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_name (stmt, index); + } + + public static ColType ColumnType (Sqlite3Statement stmt, int index) + { + return (ColType)Sqlite3.sqlite3_column_type (stmt, index); + } + + public static int ColumnInt (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_int (stmt, index); + } + + public static long ColumnInt64 (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_int64 (stmt, index); + } + + public static double ColumnDouble (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_double (stmt, index); + } + + public static string ColumnText (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_text (stmt, index); + } + + public static string ColumnText16 (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_text (stmt, index); + } + + public static byte[] ColumnBlob (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_blob (stmt, index); + } + + public static int ColumnBytes (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_bytes (stmt, index); + } + + public static string ColumnString (Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_text (stmt, index); + } + + public static byte[] ColumnByteArray (Sqlite3Statement stmt, int index) + { + int length = ColumnBytes (stmt, index); + if (length > 0) { + return ColumnBlob (stmt, index); + } + return new byte[0]; + } + + public static Result EnableLoadExtension (Sqlite3DatabaseHandle db, int onoff) + { + return (Result)Sqlite3.sqlite3_enable_load_extension (db, onoff); + } + + public static int LibVersionNumber () + { + return Sqlite3.sqlite3_libversion_number (); + } + + public static Result GetResult (Sqlite3DatabaseHandle db) + { + return (Result)Sqlite3.sqlite3_errcode (db); + } + + public static ExtendedResult ExtendedErrCode (Sqlite3DatabaseHandle db) + { + return (ExtendedResult)Sqlite3.sqlite3_extended_errcode (db); + } + + public static Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, string destName, Sqlite3DatabaseHandle sourceDb, string sourceName) + { + return Sqlite3.sqlite3_backup_init (destDb, destName, sourceDb, sourceName); + } + + public static Result BackupStep (Sqlite3BackupHandle backup, int numPages) + { + return (Result)Sqlite3.sqlite3_backup_step (backup, numPages); + } + + public static Result BackupFinish (Sqlite3BackupHandle backup) + { + return (Result)Sqlite3.sqlite3_backup_finish (backup); + } +#endif + + public enum ColType : int + { + Integer = 1, + Float = 2, + Text = 3, + Blob = 4, + Null = 5 + } + } +} diff --git a/WindowsFormsApp1/db/SQLiteAsync.cs b/WindowsFormsApp1/db/SQLiteAsync.cs new file mode 100644 index 0000000..93d27ff --- /dev/null +++ b/WindowsFormsApp1/db/SQLiteAsync.cs @@ -0,0 +1,1474 @@ +// +// Copyright (c) 2012-2019 Krueger Systems, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading; +using System.Threading.Tasks; + +namespace SQLite +{ + /// + /// A pooled asynchronous connection to a SQLite database. + /// + public partial class SQLiteAsyncConnection + { + readonly SQLiteConnectionString _connectionString; + + /// + /// Constructs a new SQLiteAsyncConnection and opens a pooled SQLite database specified by databasePath. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + public SQLiteAsyncConnection (string databasePath, bool storeDateTimeAsTicks = true) + : this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex, storeDateTimeAsTicks)) + { + } + + /// + /// Constructs a new SQLiteAsyncConnection and opens a pooled SQLite database specified by databasePath. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Flags controlling how the connection should be opened. + /// Async connections should have the FullMutex flag set to provide best performance. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The value of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless + /// the storeDateTimeAsTicks parameter. + /// + public SQLiteAsyncConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true) + : this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks)) + { + } + + /// + /// Constructs a new SQLiteAsyncConnection and opens a pooled SQLite database + /// using the given connection string. + /// + /// + /// Details on how to find and open the database. + /// + public SQLiteAsyncConnection (SQLiteConnectionString connectionString) + { + _connectionString = connectionString; + } + + /// + /// Gets the database path used by this connection. + /// + public string DatabasePath => GetConnection ().DatabasePath; + + /// + /// Gets the SQLite library version number. 3007014 would be v3.7.14 + /// + public int LibVersionNumber => GetConnection ().LibVersionNumber; + + /// + /// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true. + /// + /// The date time string format. + public string DateTimeStringFormat => GetConnection ().DateTimeStringFormat; + + /// + /// The amount of time to wait for a table to become unlocked. + /// + public TimeSpan GetBusyTimeout () + { + return GetConnection ().BusyTimeout; + } + + /// + /// Sets the amount of time to wait for a table to become unlocked. + /// + public Task SetBusyTimeoutAsync (TimeSpan value) + { + return ReadAsync (conn => { + conn.BusyTimeout = value; + return null; + }); + } + + /// + /// Enables the write ahead logging. WAL is significantly faster in most scenarios + /// by providing better concurrency and better disk IO performance than the normal + /// jounral mode. You only need to call this function once in the lifetime of the database. + /// + public Task EnableWriteAheadLoggingAsync () + { + return WriteAsync (conn => { + conn.EnableWriteAheadLogging (); + return null; + }); + } + + /// + /// Whether to store DateTime properties as ticks (true) or strings (false). + /// + public bool StoreDateTimeAsTicks => GetConnection ().StoreDateTimeAsTicks; + + /// + /// Whether to store TimeSpan properties as ticks (true) or strings (false). + /// + public bool StoreTimeSpanAsTicks => GetConnection ().StoreTimeSpanAsTicks; + + /// + /// Whether to writer queries to during execution. + /// + /// The tracer. + public bool Trace { + get { return GetConnection ().Trace; } + set { GetConnection ().Trace = value; } + } + + /// + /// The delegate responsible for writing trace lines. + /// + /// The tracer. + public Action Tracer { + get { return GetConnection ().Tracer; } + set { GetConnection ().Tracer = value; } + } + + /// + /// Whether Trace lines should be written that show the execution time of queries. + /// + public bool TimeExecution { + get { return GetConnection ().TimeExecution; } + set { GetConnection ().TimeExecution = value; } + } + + /// + /// Returns the mappings from types to tables that the connection + /// currently understands. + /// + public IEnumerable TableMappings => GetConnection ().TableMappings; + + /// + /// Closes all connections to all async databases. + /// You should *never* need to do this. + /// This is a blocking operation that will return when all connections + /// have been closed. + /// + public static void ResetPool () + { + SQLiteConnectionPool.Shared.Reset (); + } + + /// + /// Gets the pooled lockable connection used by this async connection. + /// You should never need to use this. This is provided only to add additional + /// functionality to SQLite-net. If you use this connection, you must use + /// the Lock method on it while using it. + /// + public SQLiteConnectionWithLock GetConnection () + { + return SQLiteConnectionPool.Shared.GetConnection (_connectionString); + } + + /// + /// Closes any pooled connections used by the database. + /// + public Task CloseAsync () + { + return Task.Factory.StartNew (() => { + SQLiteConnectionPool.Shared.CloseConnection (_connectionString); + }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + Task ReadAsync (Func read) + { + return Task.Factory.StartNew (() => { + var conn = GetConnection (); + using (conn.Lock ()) { + return read (conn); + } + }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + Task WriteAsync (Func write) + { + return Task.Factory.StartNew (() => { + var conn = GetConnection (); + using (conn.Lock ()) { + return write (conn); + } + }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + /// + /// Enable or disable extension loading. + /// + public Task EnableLoadExtensionAsync (bool enabled) + { + return WriteAsync (conn => { + conn.EnableLoadExtension (enabled); + return null; + }); + } + + /// + /// Executes a "create table if not exists" on the database. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated. + /// + public Task CreateTableAsync (CreateFlags createFlags = CreateFlags.None) + where T : new() + { + return WriteAsync (conn => conn.CreateTable (createFlags)); + } + + /// + /// Executes a "create table if not exists" on the database. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// Type to reflect to a database table. + /// Optional flags allowing implicit PK and indexes based on naming conventions. + /// + /// Whether the table was created or migrated. + /// + public Task CreateTableAsync (Type ty, CreateFlags createFlags = CreateFlags.None) + { + return WriteAsync (conn => conn.CreateTable (ty, createFlags)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public Task CreateTablesAsync (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + { + return CreateTablesAsync (createFlags, typeof (T), typeof (T2)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public Task CreateTablesAsync (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + where T3 : new() + { + return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public Task CreateTablesAsync (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + where T3 : new() + where T4 : new() + { + return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public Task CreateTablesAsync (CreateFlags createFlags = CreateFlags.None) + where T : new() + where T2 : new() + where T3 : new() + where T4 : new() + where T5 : new() + { + return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); + } + + /// + /// Executes a "create table if not exists" on the database for each type. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// Whether the table was created or migrated for each type. + /// + public Task CreateTablesAsync (CreateFlags createFlags = CreateFlags.None, params Type[] types) + { + return WriteAsync (conn => conn.CreateTables (createFlags, types)); + } + + /// + /// Executes a "drop table" on the database. This is non-recoverable. + /// + public Task DropTableAsync () + where T : new() + { + return WriteAsync (conn => conn.DropTable ()); + } + + /// + /// Executes a "drop table" on the database. This is non-recoverable. + /// + /// + /// The TableMapping used to identify the table. + /// + public Task DropTableAsync (TableMapping map) + { + return WriteAsync (conn => conn.DropTable (map)); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public Task CreateIndexAsync (string tableName, string columnName, bool unique = false) + { + return WriteAsync (conn => conn.CreateIndex (tableName, columnName, unique)); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the index to create + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public Task CreateIndexAsync (string indexName, string tableName, string columnName, bool unique = false) + { + return WriteAsync (conn => conn.CreateIndex (indexName, tableName, columnName, unique)); + } + + /// + /// Creates an index for the specified table and columns. + /// + /// Name of the database table + /// An array of column names to index + /// Whether the index should be unique + public Task CreateIndexAsync (string tableName, string[] columnNames, bool unique = false) + { + return WriteAsync (conn => conn.CreateIndex (tableName, columnNames, unique)); + } + + /// + /// Creates an index for the specified table and columns. + /// + /// Name of the index to create + /// Name of the database table + /// An array of column names to index + /// Whether the index should be unique + public Task CreateIndexAsync (string indexName, string tableName, string[] columnNames, bool unique = false) + { + return WriteAsync (conn => conn.CreateIndex (indexName, tableName, columnNames, unique)); + } + + /// + /// Creates an index for the specified object property. + /// e.g. CreateIndex<Client>(c => c.Name); + /// + /// Type to reflect to a database table. + /// Property to index + /// Whether the index should be unique + public Task CreateIndexAsync (Expression> property, bool unique = false) + { + return WriteAsync (conn => conn.CreateIndex (property, unique)); + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// + /// + /// The object to insert. + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAsync (object obj) + { + return WriteAsync (conn => conn.Insert (obj)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAsync (object obj, Type objType) + { + return WriteAsync (conn => conn.Insert (obj, objType)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAsync (object obj, string extra) + { + return WriteAsync (conn => conn.Insert (obj, extra)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAsync (object obj, string extra, Type objType) + { + return WriteAsync (conn => conn.Insert (obj, extra, objType)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// If a UNIQUE constraint violation occurs with + /// some pre-existing object, this function deletes + /// the old object. + /// + /// + /// The object to insert. + /// + /// + /// The number of rows modified. + /// + public Task InsertOrReplaceAsync (object obj) + { + return WriteAsync (conn => conn.InsertOrReplace (obj)); + } + + /// + /// Inserts the given object (and updates its + /// auto incremented primary key if it has one). + /// The return value is the number of rows added to the table. + /// If a UNIQUE constraint violation occurs with + /// some pre-existing object, this function deletes + /// the old object. + /// + /// + /// The object to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows modified. + /// + public Task InsertOrReplaceAsync (object obj, Type objType) + { + return WriteAsync (conn => conn.InsertOrReplace (obj, objType)); + } + + /// + /// Updates all of the columns of a table using the specified object + /// except for its primary key. + /// The object is required to have a primary key. + /// + /// + /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The number of rows updated. + /// + public Task UpdateAsync (object obj) + { + return WriteAsync (conn => conn.Update (obj)); + } + + /// + /// Updates all of the columns of a table using the specified object + /// except for its primary key. + /// The object is required to have a primary key. + /// + /// + /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows updated. + /// + public Task UpdateAsync (object obj, Type objType) + { + return WriteAsync (conn => conn.Update (obj, objType)); + } + + /// + /// Updates all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// A boolean indicating if the inserts should be wrapped in a transaction + /// + /// + /// The number of rows modified. + /// + public Task UpdateAllAsync (IEnumerable objects, bool runInTransaction = true) + { + return WriteAsync (conn => conn.UpdateAll (objects, runInTransaction)); + } + + /// + /// Deletes the given object from the database using its primary key. + /// + /// + /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The number of rows deleted. + /// + public Task DeleteAsync (object objectToDelete) + { + return WriteAsync (conn => conn.Delete (objectToDelete)); + } + + /// + /// Deletes the object with the specified primary key. + /// + /// + /// The primary key of the object to delete. + /// + /// + /// The number of objects deleted. + /// + /// + /// The type of object. + /// + public Task DeleteAsync (object primaryKey) + { + return WriteAsync (conn => conn.Delete (primaryKey)); + } + + /// + /// Deletes the object with the specified primary key. + /// + /// + /// The primary key of the object to delete. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The number of objects deleted. + /// + public Task DeleteAsync (object primaryKey, TableMapping map) + { + return WriteAsync (conn => conn.Delete (primaryKey, map)); + } + + /// + /// Deletes all the objects from the specified table. + /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the + /// specified table. Do you really want to do that? + /// + /// + /// The number of objects deleted. + /// + /// + /// The type of objects to delete. + /// + public Task DeleteAllAsync () + { + return WriteAsync (conn => conn.DeleteAll ()); + } + + /// + /// Deletes all the objects from the specified table. + /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the + /// specified table. Do you really want to do that? + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The number of objects deleted. + /// + public Task DeleteAllAsync (TableMapping map) + { + return WriteAsync (conn => conn.DeleteAll (map)); + } + + /// + /// Backup the entire database to the specified path. + /// + /// Path to backup file. + /// The name of the database to backup (usually "main"). + public Task BackupAsync (string destinationDatabasePath, string databaseName = "main") + { + return WriteAsync (conn => { + conn.Backup (destinationDatabasePath, databaseName); + return 0; + }); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The object with the given primary key. Throws a not found exception + /// if the object is not found. + /// + public Task GetAsync (object pk) + where T : new() + { + return ReadAsync (conn => conn.Get (pk)); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The object with the given primary key. Throws a not found exception + /// if the object is not found. + /// + public Task GetAsync (object pk, TableMapping map) + { + return ReadAsync (conn => conn.Get (pk, map)); + } + + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate. Throws a not found exception + /// if the object is not found. + /// + public Task GetAsync (Expression> predicate) + where T : new() + { + return ReadAsync (conn => conn.Get (predicate)); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The object with the given primary key or null + /// if the object is not found. + /// + public Task FindAsync (object pk) + where T : new() + { + return ReadAsync (conn => conn.Find (pk)); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The object with the given primary key or null + /// if the object is not found. + /// + public Task FindAsync (object pk, TableMapping map) + { + return ReadAsync (conn => conn.Find (pk, map)); + } + + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public Task FindAsync (Expression> predicate) + where T : new() + { + return ReadAsync (conn => conn.Find (predicate)); + } + + /// + /// Attempts to retrieve the first object that matches the query from the table + /// associated with the specified type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public Task FindWithQueryAsync (string query, params object[] args) + where T : new() + { + return ReadAsync (conn => conn.FindWithQuery (query, args)); + } + + /// + /// Attempts to retrieve the first object that matches the query from the table + /// associated with the specified type. + /// + /// + /// The TableMapping used to identify the table. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public Task FindWithQueryAsync (TableMapping map, string query, params object[] args) + { + return ReadAsync (conn => conn.FindWithQuery (map, query, args)); + } + + /// + /// Retrieves the mapping that is automatically generated for the given type. + /// + /// + /// The type whose mapping to the database is returned. + /// + /// + /// Optional flags allowing implicit PK and indexes based on naming conventions + /// + /// + /// The mapping represents the schema of the columns of the database and contains + /// methods to set and get properties of objects. + /// + public Task GetMappingAsync (Type type, CreateFlags createFlags = CreateFlags.None) + { + return ReadAsync (conn => conn.GetMapping (type, createFlags)); + } + + /// + /// Retrieves the mapping that is automatically generated for the given type. + /// + /// + /// Optional flags allowing implicit PK and indexes based on naming conventions + /// + /// + /// The mapping represents the schema of the columns of the database and contains + /// methods to set and get properties of objects. + /// + public Task GetMappingAsync (CreateFlags createFlags = CreateFlags.None) + where T : new() + { + return ReadAsync (conn => conn.GetMapping (createFlags)); + } + + /// + /// Query the built-in sqlite table_info table for a specific tables columns. + /// + /// The columns contains in the table. + /// Table name. + public Task> GetTableInfoAsync (string tableName) + { + return ReadAsync (conn => conn.GetTableInfo (tableName)); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// Use this method instead of Query when you don't expect rows back. Such cases include + /// INSERTs, UPDATEs, and DELETEs. + /// You can set the Trace or TimeExecution properties of the connection + /// to profile execution. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The number of rows modified in the database as a result of this execution. + /// + public Task ExecuteAsync (string query, params object[] args) + { + return WriteAsync (conn => conn.Execute (query, args)); + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// A boolean indicating if the inserts should be wrapped in a transaction. + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAllAsync (IEnumerable objects, bool runInTransaction = true) + { + return WriteAsync (conn => conn.InsertAll (objects, runInTransaction)); + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// A boolean indicating if the inserts should be wrapped in a transaction. + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAllAsync (IEnumerable objects, string extra, bool runInTransaction = true) + { + return WriteAsync (conn => conn.InsertAll (objects, extra, runInTransaction)); + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// A boolean indicating if the inserts should be wrapped in a transaction. + /// + /// + /// The number of rows added to the table. + /// + public Task InsertAllAsync (IEnumerable objects, Type objType, bool runInTransaction = true) + { + return WriteAsync (conn => conn.InsertAll (objects, objType, runInTransaction)); + } + + /// + /// Executes within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an + /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception + /// is rethrown. + /// + /// + /// The to perform within a transaction. can contain any number + /// of operations on the connection but should never call or + /// . + /// + public Task RunInTransactionAsync (Action action) + { + return WriteAsync (conn => { + conn.BeginTransaction (); + try { + action (conn); + conn.Commit (); + return null; + } + catch (Exception) { + conn.Rollback (); + throw; + } + }); + } + + /// + /// Returns a queryable interface to the table represented by the given type. + /// + /// + /// A queryable object that is able to translate Where, OrderBy, and Take + /// queries into native SQL. + /// + public AsyncTableQuery Table () + where T : new() + { + // + // This isn't async as the underlying connection doesn't go out to the database + // until the query is performed. The Async methods are on the query iteself. + // + var conn = GetConnection (); + return new AsyncTableQuery (conn.Table ()); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// Use this method when return primitive values. + /// You can set the Trace or TimeExecution properties of the connection + /// to profile execution. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The number of rows modified in the database as a result of this execution. + /// + public Task ExecuteScalarAsync (string query, params object[] args) + { + return WriteAsync (conn => { + var command = conn.CreateCommand (query, args); + return command.ExecuteScalar (); + }); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the mapping automatically generated for + /// the given type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// + public Task> QueryAsync (string query, params object[] args) + where T : new() + { + return ReadAsync (conn => conn.Query (query, args)); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the specified mapping. This function is + /// only used by libraries in order to query the database via introspection. It is + /// normally not used. + /// + /// + /// A to use to convert the resulting rows + /// into objects. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// + public Task> QueryAsync (TableMapping map, string query, params object[] args) + { + return ReadAsync (conn => conn.Query (map, query, args)); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the mapping automatically generated for + /// the given type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// The enumerator will call sqlite3_step on each call to MoveNext, so the database + /// connection must remain open for the lifetime of the enumerator. + /// + public Task> DeferredQueryAsync (string query, params object[] args) + where T : new() + { + return ReadAsync (conn => (IEnumerable)conn.DeferredQuery (query, args).ToList ()); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the specified mapping. This function is + /// only used by libraries in order to query the database via introspection. It is + /// normally not used. + /// + /// + /// A to use to convert the resulting rows + /// into objects. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// The enumerator will call sqlite3_step on each call to MoveNext, so the database + /// connection must remain open for the lifetime of the enumerator. + /// + public Task> DeferredQueryAsync (TableMapping map, string query, params object[] args) + { + return ReadAsync (conn => (IEnumerable)conn.DeferredQuery (map, query, args).ToList ()); + } + } + + /// + /// Query to an asynchronous database connection. + /// + public class AsyncTableQuery + where T : new() + { + TableQuery _innerQuery; + + /// + /// Creates a new async query that uses given the synchronous query. + /// + public AsyncTableQuery (TableQuery innerQuery) + { + _innerQuery = innerQuery; + } + + Task ReadAsync (Func read) + { + return Task.Factory.StartNew (() => { + var conn = (SQLiteConnectionWithLock)_innerQuery.Connection; + using (conn.Lock ()) { + return read (conn); + } + }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + Task WriteAsync (Func write) + { + return Task.Factory.StartNew (() => { + var conn = (SQLiteConnectionWithLock)_innerQuery.Connection; + using (conn.Lock ()) { + return write (conn); + } + }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + /// + /// Filters the query based on a predicate. + /// + public AsyncTableQuery Where (Expression> predExpr) + { + return new AsyncTableQuery (_innerQuery.Where (predExpr)); + } + + /// + /// Skips a given number of elements from the query and then yields the remainder. + /// + public AsyncTableQuery Skip (int n) + { + return new AsyncTableQuery (_innerQuery.Skip (n)); + } + + /// + /// Yields a given number of elements from the query and then skips the remainder. + /// + public AsyncTableQuery Take (int n) + { + return new AsyncTableQuery (_innerQuery.Take (n)); + } + + /// + /// Order the query results according to a key. + /// + public AsyncTableQuery OrderBy (Expression> orderExpr) + { + return new AsyncTableQuery (_innerQuery.OrderBy (orderExpr)); + } + + /// + /// Order the query results according to a key. + /// + public AsyncTableQuery OrderByDescending (Expression> orderExpr) + { + return new AsyncTableQuery (_innerQuery.OrderByDescending (orderExpr)); + } + + /// + /// Order the query results according to a key. + /// + public AsyncTableQuery ThenBy (Expression> orderExpr) + { + return new AsyncTableQuery (_innerQuery.ThenBy (orderExpr)); + } + + /// + /// Order the query results according to a key. + /// + public AsyncTableQuery ThenByDescending (Expression> orderExpr) + { + return new AsyncTableQuery (_innerQuery.ThenByDescending (orderExpr)); + } + + /// + /// Queries the database and returns the results as a List. + /// + public Task> ToListAsync () + { + return ReadAsync (conn => _innerQuery.ToList ()); + } + + /// + /// Queries the database and returns the results as an array. + /// + public Task ToArrayAsync () + { + return ReadAsync (conn => _innerQuery.ToArray ()); + } + + /// + /// Execute SELECT COUNT(*) on the query + /// + public Task CountAsync () + { + return ReadAsync (conn => _innerQuery.Count ()); + } + + /// + /// Execute SELECT COUNT(*) on the query with an additional WHERE clause. + /// + public Task CountAsync (Expression> predExpr) + { + return ReadAsync (conn => _innerQuery.Count (predExpr)); + } + + /// + /// Returns the element at a given index + /// + public Task ElementAtAsync (int index) + { + return ReadAsync (conn => _innerQuery.ElementAt (index)); + } + + /// + /// Returns the first element of this query. + /// + public Task FirstAsync () + { + return ReadAsync (conn => _innerQuery.First ()); + } + + /// + /// Returns the first element of this query, or null if no element is found. + /// + public Task FirstOrDefaultAsync () + { + return ReadAsync (conn => _innerQuery.FirstOrDefault ()); + } + + /// + /// Returns the first element of this query that matches the predicate. + /// + public Task FirstAsync (Expression> predExpr) + { + return ReadAsync (conn => _innerQuery.First (predExpr)); + } + + /// + /// Returns the first element of this query that matches the predicate. + /// + public Task FirstOrDefaultAsync (Expression> predExpr) + { + return ReadAsync (conn => _innerQuery.FirstOrDefault (predExpr)); + } + + /// + /// Delete all the rows that match this query and the given predicate. + /// + public Task DeleteAsync (Expression> predExpr) + { + return WriteAsync (conn => _innerQuery.Delete (predExpr)); + } + + /// + /// Delete all the rows that match this query. + /// + public Task DeleteAsync () + { + return WriteAsync (conn => _innerQuery.Delete ()); + } + } + + class SQLiteConnectionPool + { + class Entry + { + WeakReference connection; + + public SQLiteConnectionString ConnectionString { get; } + + public Entry (SQLiteConnectionString connectionString) + { + ConnectionString = connectionString; + } + + public SQLiteConnectionWithLock Connect () + { + SQLiteConnectionWithLock c = null; + var wc = connection; + if (wc == null || !wc.TryGetTarget (out c)) { + c = new SQLiteConnectionWithLock (ConnectionString); + + // If the database is FullMutex, then we don't need to bother locking + if (ConnectionString.OpenFlags.HasFlag (SQLiteOpenFlags.FullMutex)) { + c.SkipLock = true; + } + + connection = new WeakReference (c); + } + return c; + } + + public void Close () + { + var wc = connection; + if (wc != null && wc.TryGetTarget (out var c)) { + c.Close (); + } + connection = null; + } + } + + readonly Dictionary _entries = new Dictionary (); + readonly object _entriesLock = new object (); + + static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool (); + + /// + /// Gets the singleton instance of the connection tool. + /// + public static SQLiteConnectionPool Shared { + get { + return _shared; + } + } + + public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString) + { + var key = connectionString.UniqueKey; + Entry entry; + lock (_entriesLock) { + if (!_entries.TryGetValue (key, out entry)) { + entry = new Entry (connectionString); + _entries[key] = entry; + } + } + return entry.Connect (); + } + + public void CloseConnection (SQLiteConnectionString connectionString) + { + var key = connectionString.UniqueKey; + Entry entry; + lock (_entriesLock) { + if (_entries.TryGetValue (key, out entry)) { + _entries.Remove (key); + } + } + entry?.Close (); + } + + /// + /// Closes all connections managed by this pool. + /// + public void Reset () + { + List entries; + lock (_entriesLock) { + entries = new List (_entries.Values); + _entries.Clear (); + } + + foreach (var e in entries) { + e.Close (); + } + } + } + + /// + /// This is a normal connection except it contains a Lock method that + /// can be used to serialize access to the database + /// in lieu of using the sqlite's FullMutex support. + /// + public class SQLiteConnectionWithLock : SQLiteConnection + { + readonly object _lockPoint = new object (); + + /// + /// Initializes a new instance of the class. + /// + /// Connection string containing the DatabasePath. + public SQLiteConnectionWithLock (SQLiteConnectionString connectionString) + : base (connectionString) + { + } + + /// + /// Gets or sets a value indicating whether this skip lock. + /// + /// true if skip lock; otherwise, false. + public bool SkipLock { get; set; } + + /// + /// Lock the database to serialize access to it. To unlock it, call Dispose + /// on the returned object. + /// + /// The lock. + public IDisposable Lock () + { + return SkipLock ? (IDisposable)new FakeLockWrapper() : new LockWrapper (_lockPoint); + } + + class LockWrapper : IDisposable + { + object _lockPoint; + + public LockWrapper (object lockPoint) + { + _lockPoint = lockPoint; + Monitor.Enter (_lockPoint); + } + + public void Dispose () + { + Monitor.Exit (_lockPoint); + } + } + class FakeLockWrapper : IDisposable + { + public void Dispose () + { + } + } + } +} + diff --git a/WindowsFormsApp1/db/SQLiteHelper.cs b/WindowsFormsApp1/db/SQLiteHelper.cs new file mode 100644 index 0000000..6dcb8c6 --- /dev/null +++ b/WindowsFormsApp1/db/SQLiteHelper.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; +using SQLite; +using WindowsFormsApp1.server; + +namespace WindowsFormsApp1.db +{ + public class SQLiteHelper where T : new() + { + + //private readonly string _databasePath = Path.Combine(Environment.CurrentDirectory, "db\\MES_PLC.db"); + private readonly string _databasePath = "C:\\Users\\bnala\\source\\repos\\WindowsFormsApp1\\WindowsFormsApp1\\db\\MES_PLC.db"; + private readonly SQLiteConnection _connection; // SQLite连接对象 + + /// + /// 构造函数 + /// + public SQLiteHelper() + { + // 创建SQLite连接对象并打开连接 + _connection = new SQLiteConnection(_databasePath); + _connection.CreateTable(); // 如果表不存在,则创建该表[不会创建重复的表] + } + + /// + /// 数据插入 + /// + /// 要插入的数据项 + /// + public BllResult Insert(T item) + { + if(_connection.Insert(item) > 0) + { + return BllResult.Sucess(); + } + else + { + return BllResult.Error(); + } + + } + + /// + /// 数据删除 + /// + /// 要删除的数据的主键ID + /// + public BllResult Delete(int id) + { + if (_connection.Delete(id) > 0) + { + return BllResult.Sucess(); + } + else + { + return BllResult.Error(); + } + } + + /// + /// 数据更新 + /// + /// 要更新的数据项 + /// + public BllResult Update(T item) + { + if(_connection.Update(item) > 0) + { + return BllResult.Sucess(); + } + else { + return BllResult.Error(); + } + } + + public BllResult UpdateAll(List item) + { + if (_connection.UpdateAll(item) == item.Count) + { + return BllResult.Sucess(); + } + else + { + return BllResult.Error(); + } + } + + /// + /// 根据条件查询记录 + /// + /// 查询条件 + /// + public BllResult> Query(Expression> predExpr) + { + var result = _connection.Table().Where(predExpr).ToList(); + if (result.Count > 0 ) + { + return BllResult>.Sucess(result); + } + else + { + return BllResult>.Error(); + } + } + + /// + /// 查询所有数据 + /// + /// + public BllResult> QueryAll() + { + var result = _connection.Table().ToList(); + if (result.Count > 0) + { + return BllResult>.Sucess(result); + } + else + { + return BllResult>.Error(); + } + } + + /// + /// 根据条件查询单条记录 + /// + /// 查询条件 + /// + public BllResult QuerySingle(Expression> predExpr) + { + var result = _connection.Table().Where(predExpr).FirstOrDefault(); + if (result != null) + { + return BllResult.Sucess(result); + } + else + { + return BllResult.Error(result); + } + } + } +} diff --git a/WindowsFormsApp1/form/FLOW_Manage.Designer.cs b/WindowsFormsApp1/form/FLOW_Manage.Designer.cs new file mode 100644 index 0000000..ef7942e --- /dev/null +++ b/WindowsFormsApp1/form/FLOW_Manage.Designer.cs @@ -0,0 +1,227 @@ +namespace WindowsFormsApp1.form +{ + partial class FLOW_Manage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.flowid = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.setp = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.hopestatus = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.hopeinterfaceid = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.errstatus = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.errinterfaceid = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.关闭 = new System.Windows.Forms.Button(); + this.保存 = new System.Windows.Forms.Button(); + this.查询 = new System.Windows.Forms.Button(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.flowid, + this.setp, + this.hopestatus, + this.hopeinterfaceid, + this.errstatus, + this.errinterfaceid}); + dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3; + this.dataGridView1.Location = new System.Drawing.Point(3, 3); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersWidth = 72; + this.tableLayoutPanel1.SetRowSpan(this.dataGridView1, 4); + this.dataGridView1.RowTemplate.Height = 23; + this.dataGridView1.Size = new System.Drawing.Size(1686, 1011); + this.dataGridView1.TabIndex = 1; + // + // flowid + // + this.flowid.DataPropertyName = "flowid"; + this.flowid.HeaderText = "流程序号"; + this.flowid.MinimumWidth = 9; + this.flowid.Name = "flowid"; + this.flowid.ReadOnly = true; + this.flowid.Width = 175; + // + // setp + // + this.setp.DataPropertyName = "setp"; + this.setp.HeaderText = "步骤"; + this.setp.MinimumWidth = 9; + this.setp.Name = "setp"; + this.setp.ReadOnly = true; + this.setp.Width = 175; + // + // hopestatus + // + this.hopestatus.DataPropertyName = "hopestatus"; + this.hopestatus.HeaderText = "期望PLC值"; + this.hopestatus.MinimumWidth = 9; + this.hopestatus.Name = "hopestatus"; + this.hopestatus.Width = 150; + // + // hopeinterfaceid + // + this.hopeinterfaceid.DataPropertyName = "hopeinterfaceid"; + this.hopeinterfaceid.HeaderText = "成功调用接口"; + this.hopeinterfaceid.MinimumWidth = 9; + this.hopeinterfaceid.Name = "hopeinterfaceid"; + this.hopeinterfaceid.Width = 200; + // + // errstatus + // + this.errstatus.DataPropertyName = "errstatus"; + this.errstatus.HeaderText = "错误PLC值"; + this.errstatus.MinimumWidth = 9; + this.errstatus.Name = "errstatus"; + this.errstatus.Width = 150; + // + // errinterfaceid + // + this.errinterfaceid.DataPropertyName = "errinterfaceid"; + this.errinterfaceid.HeaderText = "错误调用接口"; + this.errinterfaceid.MinimumWidth = 9; + this.errinterfaceid.Name = "errinterfaceid"; + this.errinterfaceid.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.errinterfaceid.Width = 200; + // + // 关闭 + // + this.关闭.Anchor = System.Windows.Forms.AnchorStyles.None; + this.关闭.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.关闭.Location = new System.Drawing.Point(1740, 950); + this.关闭.Name = "关闭"; + this.关闭.Size = new System.Drawing.Size(92, 41); + this.关闭.TabIndex = 6; + this.关闭.Text = "关闭"; + this.关闭.UseVisualStyleBackColor = true; + this.关闭.Click += new System.EventHandler(this.关闭_Click); + // + // 保存 + // + this.保存.Anchor = System.Windows.Forms.AnchorStyles.None; + this.保存.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.保存.Location = new System.Drawing.Point(1740, 857); + this.保存.Name = "保存"; + this.保存.Size = new System.Drawing.Size(92, 41); + this.保存.TabIndex = 5; + this.保存.Text = "保存"; + this.保存.UseVisualStyleBackColor = true; + this.保存.Click += new System.EventHandler(this.保存_Click); + // + // 查询 + // + this.查询.Anchor = System.Windows.Forms.AnchorStyles.None; + this.查询.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.查询.Location = new System.Drawing.Point(1740, 22); + this.查询.Name = "查询"; + this.查询.Size = new System.Drawing.Size(92, 41); + this.查询.TabIndex = 4; + this.查询.Text = "查询"; + this.查询.UseVisualStyleBackColor = true; + this.查询.Click += new System.EventHandler(this.查询_Click); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.Controls.Add(this.查询, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.关闭, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.保存, 1, 2); + this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 12); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.22067F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 89.77933F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 94F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 91F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1880, 1017); + this.tableLayoutPanel1.TabIndex = 7; + // + // FLOW_Manage + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1904, 1041); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Name = "FLOW_Manage"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "FLOW_Mange"; + this.Load += new System.EventHandler(this.FLOW_Mange_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.tableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.Button 关闭; + private System.Windows.Forms.Button 保存; + private System.Windows.Forms.Button 查询; + private System.Windows.Forms.DataGridViewTextBoxColumn flowid; + private System.Windows.Forms.DataGridViewTextBoxColumn setp; + private System.Windows.Forms.DataGridViewTextBoxColumn hopestatus; + private System.Windows.Forms.DataGridViewComboBoxColumn hopeinterfaceid; + private System.Windows.Forms.DataGridViewTextBoxColumn errstatus; + private System.Windows.Forms.DataGridViewComboBoxColumn errinterfaceid; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/FLOW_Manage.cs b/WindowsFormsApp1/form/FLOW_Manage.cs new file mode 100644 index 0000000..d129a95 --- /dev/null +++ b/WindowsFormsApp1/form/FLOW_Manage.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; + +namespace WindowsFormsApp1.form +{ + public partial class FLOW_Manage : Form + { + public FLOW_Manage() + { + InitializeComponent(); + } + + private void 查询_Click(object sender, EventArgs e) + { + GetInfo(); + } + + private void 保存_Click(object sender, EventArgs e) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.UpdateAll((List)dataGridView1.DataSource); + if (result.Success) + { + MessageBox.Show("更新成功"); + GetInfo(); + } + else + { + MessageBox.Show("更新失败"); + } + } + catch (Exception ex) + { + MessageBox.Show($"更新失败,错误原因{ex.Message}"); + } + } + + private void 关闭_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void FLOW_Mange_Load(object sender, EventArgs e) + { + dataGridView1.AutoGenerateColumns = false; + + SQLiteHelper sQLiteHelper1 = new db.SQLiteHelper(); + var result1 = sQLiteHelper1.QueryAll(); + if (!result1.Success) + { + MessageBox.Show("查询失败"); + return; + } + result1.Data.Insert(0, new t_interface { id = 0, name = "" }); + + var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[3]; + // 绑定数据源到 ComboBox + comboBoxColumn.DataSource = result1.Data; + comboBoxColumn.DisplayMember = "name"; + comboBoxColumn.ValueMember = "id"; + + // 设置默认值为 Product 的 CategoryId + comboBoxColumn.DataPropertyName = "hopeinterfaceid"; // 绑定数据源中的 CategoryId 字段 + + var comboBoxColumn1 = (DataGridViewComboBoxColumn)dataGridView1.Columns[5]; + // 绑定数据源到 ComboBox + comboBoxColumn1.DataSource = result1.Data; + comboBoxColumn1.DisplayMember = "name"; + comboBoxColumn1.ValueMember = "id"; + + // 设置默认值为 Product 的 CategoryId + comboBoxColumn1.DataPropertyName = "errinterfaceid"; // 绑定数据源中的 CategoryId 字段 + + GetInfo(); + } + + public void GetInfo() + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.Query(a => a.flowid == Init.t_Line.flowid); + if (result.Success) + { + dataGridView1.DataSource = null; + dataGridView1.DataSource = result.Data; + dataGridView1.Refresh(); + } + + } + catch (Exception ex) + { + } + } + } +} diff --git a/WindowsFormsApp1/form/FLOW_Manage.resx b/WindowsFormsApp1/form/FLOW_Manage.resx new file mode 100644 index 0000000..e80d3d1 --- /dev/null +++ b/WindowsFormsApp1/form/FLOW_Manage.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/LINE_Manage.Designer.cs b/WindowsFormsApp1/form/LINE_Manage.Designer.cs new file mode 100644 index 0000000..302c222 --- /dev/null +++ b/WindowsFormsApp1/form/LINE_Manage.Designer.cs @@ -0,0 +1,250 @@ +namespace WindowsFormsApp1.form +{ + partial class LINE_Manage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); + this.关闭 = new System.Windows.Forms.Button(); + this.保存 = new System.Windows.Forms.Button(); + this.查询 = new System.Windows.Forms.Button(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.linename = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.linecode = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.linetype = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.linemode = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.plcid1 = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.plcid2 = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.flowid = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // 关闭 + // + this.关闭.Anchor = System.Windows.Forms.AnchorStyles.None; + this.关闭.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.关闭.Location = new System.Drawing.Point(1743, 958); + this.关闭.Name = "关闭"; + this.关闭.Size = new System.Drawing.Size(92, 41); + this.关闭.TabIndex = 10; + this.关闭.Text = "关闭"; + this.关闭.UseVisualStyleBackColor = true; + this.关闭.Click += new System.EventHandler(this.关闭_Click); + // + // 保存 + // + this.保存.Anchor = System.Windows.Forms.AnchorStyles.None; + this.保存.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.保存.Location = new System.Drawing.Point(1743, 886); + this.保存.Name = "保存"; + this.保存.Size = new System.Drawing.Size(92, 41); + this.保存.TabIndex = 9; + this.保存.Text = "保存"; + this.保存.UseVisualStyleBackColor = true; + this.保存.Click += new System.EventHandler(this.保存_Click); + // + // 查询 + // + this.查询.Anchor = System.Windows.Forms.AnchorStyles.None; + this.查询.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.查询.Location = new System.Drawing.Point(1743, 24); + this.查询.Name = "查询"; + this.查询.Size = new System.Drawing.Size(92, 41); + this.查询.TabIndex = 8; + this.查询.Text = "查询"; + this.查询.UseVisualStyleBackColor = true; + this.查询.Click += new System.EventHandler(this.查询_Click); + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.id, + this.linename, + this.linecode, + this.linetype, + this.linemode, + this.plcid1, + this.plcid2, + this.flowid}); + dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3; + this.dataGridView1.Location = new System.Drawing.Point(3, 3); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersWidth = 72; + this.tableLayoutPanel1.SetRowSpan(this.dataGridView1, 4); + this.dataGridView1.RowTemplate.Height = 23; + this.dataGridView1.Size = new System.Drawing.Size(1689, 1011); + this.dataGridView1.TabIndex = 7; + // + // id + // + this.id.DataPropertyName = "id"; + this.id.HeaderText = "序号"; + this.id.MinimumWidth = 9; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Width = 175; + // + // linename + // + this.linename.DataPropertyName = "linename"; + this.linename.HeaderText = "名称"; + this.linename.MinimumWidth = 9; + this.linename.Name = "linename"; + this.linename.ReadOnly = true; + this.linename.Width = 175; + // + // linecode + // + this.linecode.DataPropertyName = "linecode"; + this.linecode.HeaderText = "产线编码"; + this.linecode.MinimumWidth = 9; + this.linecode.Name = "linecode"; + this.linecode.Width = 150; + // + // linetype + // + this.linetype.DataPropertyName = "linetype"; + this.linetype.HeaderText = "产线类型"; + this.linetype.MinimumWidth = 9; + this.linetype.Name = "linetype"; + this.linetype.Width = 150; + // + // linemode + // + this.linemode.DataPropertyName = "linemode"; + this.linemode.HeaderText = "模组"; + this.linemode.MinimumWidth = 9; + this.linemode.Name = "linemode"; + this.linemode.Width = 175; + // + // plcid1 + // + this.plcid1.DataPropertyName = "plcid1"; + this.plcid1.HeaderText = "关联PLC1"; + this.plcid1.MinimumWidth = 9; + this.plcid1.Name = "plcid1"; + this.plcid1.Width = 200; + // + // plcid2 + // + this.plcid2.DataPropertyName = "plcid2"; + this.plcid2.HeaderText = "关联PLC2"; + this.plcid2.MinimumWidth = 9; + this.plcid2.Name = "plcid2"; + this.plcid2.Width = 175; + // + // flowid + // + this.flowid.DataPropertyName = "flowid"; + this.flowid.HeaderText = "关联流程"; + this.flowid.MinimumWidth = 9; + this.flowid.Name = "flowid"; + this.flowid.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.flowid.Width = 200; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.Controls.Add(this.关闭, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.查询, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.保存, 1, 2); + this.tableLayoutPanel1.Location = new System.Drawing.Point(8, 12); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.20642F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 89.79358F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 69F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 75F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1884, 1017); + this.tableLayoutPanel1.TabIndex = 11; + // + // LINE_Manage + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1904, 1041); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.Name = "LINE_Manage"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "LINE_Mange"; + this.Load += new System.EventHandler(this.LINE_Manage_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.tableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button 关闭; + private System.Windows.Forms.Button 保存; + private System.Windows.Forms.Button 查询; + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.DataGridViewTextBoxColumn id; + private System.Windows.Forms.DataGridViewTextBoxColumn linename; + private System.Windows.Forms.DataGridViewTextBoxColumn linecode; + private System.Windows.Forms.DataGridViewTextBoxColumn linetype; + private System.Windows.Forms.DataGridViewTextBoxColumn linemode; + private System.Windows.Forms.DataGridViewComboBoxColumn plcid1; + private System.Windows.Forms.DataGridViewComboBoxColumn plcid2; + private System.Windows.Forms.DataGridViewComboBoxColumn flowid; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/LINE_Manage.cs b/WindowsFormsApp1/form/LINE_Manage.cs new file mode 100644 index 0000000..d9321c8 --- /dev/null +++ b/WindowsFormsApp1/form/LINE_Manage.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace WindowsFormsApp1.form +{ + public partial class LINE_Manage : Form + { + public LINE_Manage() + { + InitializeComponent(); + } + + private void 查询_Click(object sender, EventArgs e) + { + GetInfo(); + } + + private void 保存_Click(object sender, EventArgs e) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.UpdateAll((List)dataGridView1.DataSource); + if (result.Success) + { + MessageBox.Show("更新成功"); + SQLiteHelper sQLiteHelper1 = new db.SQLiteHelper(); + var result_combox = sQLiteHelper1.QuerySingle(a => a.id == Init.t_Line.id); + if (!result_combox.Success) + { + MessageBox.Show("更新产线配置失败!"); + return; + } + else + { + Init.t_Line = result_combox.Data; + GetInfo(); + } + } + else + { + MessageBox.Show("更新失败"); + } + } + catch (Exception ex) + { + MessageBox.Show($"更新失败,错误原因{ex.Message}"); + } + } + + private void 关闭_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void LINE_Manage_Load(object sender, EventArgs e) + { + dataGridView1.AutoGenerateColumns = false; + + SQLiteHelper sQLiteHelper1 = new db.SQLiteHelper(); + var result = sQLiteHelper1.QueryAll(); + if (!result.Success) + { + MessageBox.Show("查询失败!"); + return; + } + var result1 = result.Data.GroupBy(a => a.flowid).ToList(); + + SQLiteHelper sQLiteHelper2 = new db.SQLiteHelper(); + var result2 = sQLiteHelper2.QueryAll(); + if (!result2.Success) + { + MessageBox.Show("查询失败!"); + return; + } + result2.Data.Insert(0, new t_plc { id = 0, plcip = "" }); + + var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[5]; + // 绑定数据源到 ComboBox + comboBoxColumn.DataSource = result2.Data; + comboBoxColumn.DisplayMember = "plcip"; + comboBoxColumn.ValueMember = "id"; + + //// 设置默认值为 Product 的 CategoryId + comboBoxColumn.DataPropertyName = "plcid1"; // 绑定数据源中的 CategoryId 字段 + + var comboBoxColumn1 = (DataGridViewComboBoxColumn)dataGridView1.Columns[6]; + // 绑定数据源到 ComboBox + comboBoxColumn1.DataSource = result2.Data; + comboBoxColumn1.DisplayMember = "plcip"; + comboBoxColumn1.ValueMember = "id"; + + // 设置默认值为 Product 的 CategoryId + comboBoxColumn1.DataPropertyName = "plcid2"; // 绑定数据源中的 CategoryId 字段 + + + var comboBoxColumn2 = (DataGridViewComboBoxColumn)dataGridView1.Columns[7]; + // 绑定数据源到 ComboBox + comboBoxColumn2.DataSource = result1; + comboBoxColumn2.DisplayMember = "key"; + comboBoxColumn2.ValueMember = "key"; + + // 设置默认值为 Product 的 CategoryId + comboBoxColumn2.DataPropertyName = "flowid"; // 绑定数据源中的 CategoryId 字段 + + GetInfo(); + } + public void GetInfo() + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.Query(a=>a.id == Init.t_Line.id); + if (result.Success) + { + dataGridView1.DataSource = null; + dataGridView1.DataSource = result.Data; + dataGridView1.Refresh(); + } + } + catch (Exception ex) + { + } + } + } +} diff --git a/WindowsFormsApp1/form/LINE_Manage.resx b/WindowsFormsApp1/form/LINE_Manage.resx new file mode 100644 index 0000000..c6e5615 --- /dev/null +++ b/WindowsFormsApp1/form/LINE_Manage.resx @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/LoginForm.Designer.cs b/WindowsFormsApp1/form/LoginForm.Designer.cs new file mode 100644 index 0000000..dd28afe --- /dev/null +++ b/WindowsFormsApp1/form/LoginForm.Designer.cs @@ -0,0 +1,160 @@ +namespace WindowsFormsApp1 +{ + partial class LoginForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.label3 = new System.Windows.Forms.Label(); + this.groupBox1.SuspendLayout(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.button1.Location = new System.Drawing.Point(201, 274); + this.button1.Margin = new System.Windows.Forms.Padding(2); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(173, 39); + this.button1.TabIndex = 0; + this.button1.Text = "登录"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // textBox1 + // + this.textBox1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.textBox1.Location = new System.Drawing.Point(201, 48); + this.textBox1.Margin = new System.Windows.Forms.Padding(2); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(268, 29); + this.textBox1.TabIndex = 1; + // + // textBox2 + // + this.textBox2.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.textBox2.Location = new System.Drawing.Point(201, 120); + this.textBox2.Margin = new System.Windows.Forms.Padding(2); + this.textBox2.Name = "textBox2"; + this.textBox2.Size = new System.Drawing.Size(268, 29); + this.textBox2.TabIndex = 2; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label1.Location = new System.Drawing.Point(87, 51); + this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(69, 19); + this.label1.TabIndex = 3; + this.label1.Text = "用户名"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label2.Location = new System.Drawing.Point(103, 123); + this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(49, 19); + this.label2.TabIndex = 4; + this.label2.Text = "密码"; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.label3); + this.groupBox1.Controls.Add(this.comboBox1); + this.groupBox1.Controls.Add(this.textBox1); + this.groupBox1.Controls.Add(this.label1); + this.groupBox1.Controls.Add(this.label2); + this.groupBox1.Controls.Add(this.button1); + this.groupBox1.Controls.Add(this.textBox2); + this.groupBox1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox1.Location = new System.Drawing.Point(30, 26); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(564, 359); + this.groupBox1.TabIndex = 5; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "用户登录"; + // + // comboBox1 + // + this.comboBox1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Location = new System.Drawing.Point(201, 195); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(268, 27); + this.comboBox1.TabIndex = 5; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label3.Location = new System.Drawing.Point(87, 198); + this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(89, 19); + this.label3.TabIndex = 6; + this.label3.Text = "选择产线"; + // + // LoginForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(620, 408); + this.Controls.Add(this.groupBox1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Margin = new System.Windows.Forms.Padding(2); + this.Name = "LoginForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "LoginForm"; + this.Load += new System.EventHandler(this.LoginForm_Load); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.TextBox textBox2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.ComboBox comboBox1; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/LoginForm.cs b/WindowsFormsApp1/form/LoginForm.cs new file mode 100644 index 0000000..684ab34 --- /dev/null +++ b/WindowsFormsApp1/form/LoginForm.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace WindowsFormsApp1 +{ + public partial class LoginForm : Form + { + public LoginForm() + { + InitializeComponent(); + textBox1.Text = "admin"; + textBox2.Text = "admin"; + } + + private void button1_Click(object sender, EventArgs e) + { + if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text) || comboBox1.SelectedValue == null) + { + MessageBox.Show("输入信息为空,请确认"); + } + + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.QuerySingle(a=>a.username == textBox1.Text && a.password == textBox2.Text); + + SQLiteHelper sQLiteHelper1 = new db.SQLiteHelper(); + var result_combox = sQLiteHelper1.QuerySingle(a=>a.id == (int)comboBox1.SelectedValue); + if (!result.Success || !result_combox.Success) + { + MessageBox.Show("账号/密码/产线错误!"); + return; + } + else + { + Init.t_User = result.Data; + Init.t_Line = result_combox.Data; + DialogResult = DialogResult.OK; + this.Close(); + } + } + + private void LoginForm_Load(object sender, EventArgs e) + { + SQLiteHelper sQLiteHelper1 = new db.SQLiteHelper(); + var result_combox = sQLiteHelper1.QueryAll(); + if (!result_combox.Success) + { + MessageBox.Show("查询失败"); + return; + } + + // 绑定数据源到 ComboBox + comboBox1.DataSource = result_combox.Data; + comboBox1.DisplayMember = "linename"; + comboBox1.ValueMember = "id"; + } + } +} diff --git a/WindowsFormsApp1/form/LoginForm.resx b/WindowsFormsApp1/form/LoginForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/WindowsFormsApp1/form/LoginForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/MES_URL.Designer.cs b/WindowsFormsApp1/form/MES_URL.Designer.cs new file mode 100644 index 0000000..b01a81a --- /dev/null +++ b/WindowsFormsApp1/form/MES_URL.Designer.cs @@ -0,0 +1,204 @@ +namespace WindowsFormsApp1 +{ + partial class MES_URL + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); + this.保存 = new System.Windows.Forms.Button(); + this.查询 = new System.Windows.Forms.Button(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.name = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.code = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.url = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.关闭 = new System.Windows.Forms.Button(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // 保存 + // + this.保存.Anchor = System.Windows.Forms.AnchorStyles.None; + this.保存.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.保存.Location = new System.Drawing.Point(1739, 877); + this.保存.Name = "保存"; + this.保存.Size = new System.Drawing.Size(91, 32); + this.保存.TabIndex = 1; + this.保存.Text = "保存"; + this.保存.UseVisualStyleBackColor = true; + this.保存.Click += new System.EventHandler(this.保存_Click); + // + // 查询 + // + this.查询.Anchor = System.Windows.Forms.AnchorStyles.None; + this.查询.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.查询.Location = new System.Drawing.Point(1739, 30); + this.查询.Name = "查询"; + this.查询.Size = new System.Drawing.Size(91, 32); + this.查询.TabIndex = 3; + this.查询.Text = "查询"; + this.查询.UseVisualStyleBackColor = true; + this.查询.Click += new System.EventHandler(this.查询_Click); + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.id, + this.name, + this.code, + this.url}); + dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3; + this.dataGridView1.Location = new System.Drawing.Point(3, 3); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersWidth = 72; + this.tableLayoutPanel1.SetRowSpan(this.dataGridView1, 4); + this.dataGridView1.RowTemplate.Height = 23; + this.dataGridView1.Size = new System.Drawing.Size(1685, 1010); + this.dataGridView1.TabIndex = 0; + // + // id + // + this.id.DataPropertyName = "id"; + this.id.HeaderText = "序号"; + this.id.MinimumWidth = 9; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Width = 175; + // + // name + // + this.name.DataPropertyName = "name"; + this.name.HeaderText = "名称"; + this.name.MinimumWidth = 9; + this.name.Name = "name"; + this.name.ReadOnly = true; + this.name.Width = 175; + // + // code + // + this.code.DataPropertyName = "code"; + this.code.HeaderText = "接口"; + this.code.MinimumWidth = 9; + this.code.Name = "code"; + this.code.ReadOnly = true; + this.code.Width = 175; + // + // url + // + this.url.DataPropertyName = "url"; + this.url.HeaderText = "网址"; + this.url.MinimumWidth = 9; + this.url.Name = "url"; + this.url.Width = 500; + // + // 关闭 + // + this.关闭.Anchor = System.Windows.Forms.AnchorStyles.None; + this.关闭.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.关闭.Location = new System.Drawing.Point(1739, 959); + this.关闭.Name = "关闭"; + this.关闭.Size = new System.Drawing.Size(91, 32); + this.关闭.TabIndex = 2; + this.关闭.Text = "关闭"; + this.关闭.UseVisualStyleBackColor = true; + this.关闭.Click += new System.EventHandler(this.关闭_Click); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.查询, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.关闭, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.保存, 1, 2); + this.tableLayoutPanel1.Location = new System.Drawing.Point(13, 13); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.91549F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 89.08451F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 82F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 81F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1879, 1016); + this.tableLayoutPanel1.TabIndex = 4; + // + // MES_URL + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1904, 1041); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Name = "MES_URL"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "MES_URL"; + this.Load += new System.EventHandler(this.MES_URL_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.tableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + private System.Windows.Forms.Button 保存; + private System.Windows.Forms.Button 查询; + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.DataGridViewTextBoxColumn id; + private System.Windows.Forms.DataGridViewTextBoxColumn name; + private System.Windows.Forms.DataGridViewTextBoxColumn code; + private System.Windows.Forms.DataGridViewTextBoxColumn url; + private System.Windows.Forms.Button 关闭; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/MES_URL.cs b/WindowsFormsApp1/form/MES_URL.cs new file mode 100644 index 0000000..d79e432 --- /dev/null +++ b/WindowsFormsApp1/form/MES_URL.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; + +namespace WindowsFormsApp1 +{ + public partial class MES_URL : Form + { + public MES_URL() + { + InitializeComponent(); + } + + private void MES_URL_Load(object sender, EventArgs e) + { + dataGridView1.AutoGenerateColumns = false; + GetInfo(); + } + + private void 保存_Click(object sender, EventArgs e) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.UpdateAll((List)dataGridView1.DataSource); + if (result.Success) + { + MessageBox.Show("更新成功"); + GetInfo(); + } + else + { + MessageBox.Show("更新失败"); + } + } + catch (Exception ex) + { + MessageBox.Show($"更新失败,错误原因{ex.Message}"); + } + } + + private void 关闭_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void 查询_Click(object sender, EventArgs e) + { + GetInfo(); + } + + public void GetInfo() + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.QueryAll(); + if (result.Success) + { + dataGridView1.DataSource = null; + dataGridView1.DataSource = result.Data; + dataGridView1.Refresh(); + } + } + catch (Exception ex) + { + } + } + } +} diff --git a/WindowsFormsApp1/form/MES_URL.resx b/WindowsFormsApp1/form/MES_URL.resx new file mode 100644 index 0000000..bfbc844 --- /dev/null +++ b/WindowsFormsApp1/form/MES_URL.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/PLCADDRESS_Manage.Designer.cs b/WindowsFormsApp1/form/PLCADDRESS_Manage.Designer.cs new file mode 100644 index 0000000..8695c8b --- /dev/null +++ b/WindowsFormsApp1/form/PLCADDRESS_Manage.Designer.cs @@ -0,0 +1,285 @@ +namespace WindowsFormsApp1.form +{ + partial class PLCADDRESS_Manage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); + this.关闭 = new System.Windows.Forms.Button(); + this.保存 = new System.Windows.Forms.Button(); + this.查询 = new System.Windows.Forms.Button(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.plcid = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.type = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.dbaddress = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.addressoffset = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.addresstype = new System.Windows.Forms.DataGridViewComboBoxColumn(); + this.addresstypelegth = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.remark = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.label1 = new System.Windows.Forms.Label(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // 关闭 + // + this.关闭.Anchor = System.Windows.Forms.AnchorStyles.None; + this.关闭.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.关闭.Location = new System.Drawing.Point(1743, 964); + this.关闭.Name = "关闭"; + this.关闭.Size = new System.Drawing.Size(92, 41); + this.关闭.TabIndex = 11; + this.关闭.Text = "关闭"; + this.关闭.UseVisualStyleBackColor = true; + this.关闭.Click += new System.EventHandler(this.关闭_Click); + // + // 保存 + // + this.保存.Anchor = System.Windows.Forms.AnchorStyles.None; + this.保存.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.保存.Location = new System.Drawing.Point(1743, 886); + this.保存.Name = "保存"; + this.保存.Size = new System.Drawing.Size(92, 41); + this.保存.TabIndex = 10; + this.保存.Text = "保存"; + this.保存.UseVisualStyleBackColor = true; + this.保存.Click += new System.EventHandler(this.保存_Click); + // + // 查询 + // + this.查询.Anchor = System.Windows.Forms.AnchorStyles.None; + this.查询.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.查询.Location = new System.Drawing.Point(1743, 5); + this.查询.Name = "查询"; + this.查询.Size = new System.Drawing.Size(92, 41); + this.查询.TabIndex = 9; + this.查询.Text = "查询"; + this.查询.UseVisualStyleBackColor = true; + this.查询.Click += new System.EventHandler(this.查询_Click); + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.id, + this.plcid, + this.type, + this.dbaddress, + this.addressoffset, + this.addresstype, + this.addresstypelegth, + this.remark}); + this.tableLayoutPanel1.SetColumnSpan(this.dataGridView1, 2); + dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3; + this.dataGridView1.Location = new System.Drawing.Point(3, 54); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersWidth = 72; + this.tableLayoutPanel1.SetRowSpan(this.dataGridView1, 3); + this.dataGridView1.RowTemplate.Height = 23; + this.dataGridView1.Size = new System.Drawing.Size(1689, 960); + this.dataGridView1.TabIndex = 8; + // + // id + // + this.id.DataPropertyName = "id"; + this.id.HeaderText = "序号"; + this.id.MinimumWidth = 9; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Width = 175; + // + // plcid + // + this.plcid.DataPropertyName = "plcid"; + this.plcid.HeaderText = "所属PLC"; + this.plcid.MinimumWidth = 9; + this.plcid.Name = "plcid"; + this.plcid.Width = 175; + // + // type + // + this.type.DataPropertyName = "type"; + this.type.HeaderText = "读写类型"; + this.type.MinimumWidth = 9; + this.type.Name = "type"; + this.type.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.type.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; + this.type.Width = 175; + // + // dbaddress + // + this.dbaddress.DataPropertyName = "dbaddress"; + this.dbaddress.HeaderText = "DB块地址"; + this.dbaddress.MinimumWidth = 9; + this.dbaddress.Name = "dbaddress"; + this.dbaddress.Width = 175; + // + // addressoffset + // + this.addressoffset.DataPropertyName = "addressoffset"; + this.addressoffset.HeaderText = "DB地址"; + this.addressoffset.MinimumWidth = 9; + this.addressoffset.Name = "addressoffset"; + this.addressoffset.Width = 175; + // + // addresstype + // + this.addresstype.DataPropertyName = "addresstype"; + this.addresstype.HeaderText = "数据类型"; + this.addresstype.MinimumWidth = 9; + this.addresstype.Name = "addresstype"; + this.addresstype.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.addresstype.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; + this.addresstype.Width = 175; + // + // addresstypelegth + // + this.addresstypelegth.DataPropertyName = "addresstypelegth"; + this.addresstypelegth.HeaderText = "字节长度"; + this.addresstypelegth.MinimumWidth = 9; + this.addresstypelegth.Name = "addresstypelegth"; + this.addresstypelegth.Width = 175; + // + // remark + // + this.remark.DataPropertyName = "remark"; + this.remark.HeaderText = "注释"; + this.remark.MinimumWidth = 9; + this.remark.Name = "remark"; + this.remark.ReadOnly = true; + this.remark.Width = 175; + // + // label1 + // + this.label1.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.label1.AutoSize = true; + this.label1.Font = new System.Drawing.Font("宋体", 14.14286F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label1.Location = new System.Drawing.Point(2, 16); + this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(229, 19); + this.label1.TabIndex = 12; + this.label1.Text = "选择需要编辑的PLC编号:"; + // + // comboBox1 + // + this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.comboBox1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Location = new System.Drawing.Point(286, 12); + this.comboBox1.Margin = new System.Windows.Forms.Padding(2); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(225, 27); + this.comboBox1.TabIndex = 13; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 3; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 15.07431F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 74.89384F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.Controls.Add(this.comboBox1, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 1); + this.tableLayoutPanel1.Controls.Add(this.关闭, 2, 3); + this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.保存, 2, 2); + this.tableLayoutPanel1.Controls.Add(this.查询, 2, 0); + this.tableLayoutPanel1.Location = new System.Drawing.Point(8, 12); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.930233F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 94.06977F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 93F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 63F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1884, 1017); + this.tableLayoutPanel1.TabIndex = 14; + // + // PLCADDRESS_Manage + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1904, 1041); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Margin = new System.Windows.Forms.Padding(2); + this.Name = "PLCADDRESS_Manage"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "PLCADDRESS_Manage"; + this.Load += new System.EventHandler(this.PLCADDRESS_Manage_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button 关闭; + private System.Windows.Forms.Button 保存; + private System.Windows.Forms.Button 查询; + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.ComboBox comboBox1; + private System.Windows.Forms.DataGridViewTextBoxColumn id; + private System.Windows.Forms.DataGridViewTextBoxColumn plcid; + private System.Windows.Forms.DataGridViewComboBoxColumn type; + private System.Windows.Forms.DataGridViewTextBoxColumn dbaddress; + private System.Windows.Forms.DataGridViewTextBoxColumn addressoffset; + private System.Windows.Forms.DataGridViewComboBoxColumn addresstype; + private System.Windows.Forms.DataGridViewTextBoxColumn addresstypelegth; + private System.Windows.Forms.DataGridViewTextBoxColumn remark; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/PLCADDRESS_Manage.cs b/WindowsFormsApp1/form/PLCADDRESS_Manage.cs new file mode 100644 index 0000000..26c3a84 --- /dev/null +++ b/WindowsFormsApp1/form/PLCADDRESS_Manage.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; + +namespace WindowsFormsApp1.form +{ + public partial class PLCADDRESS_Manage : Form + { + public PLCADDRESS_Manage() + { + InitializeComponent(); + } + + private void 查询_Click(object sender, EventArgs e) + { + GetInfo((int)comboBox1.SelectedValue); + } + + private void 保存_Click(object sender, EventArgs e) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.UpdateAll((List)dataGridView1.DataSource); + if (result.Success) + { + MessageBox.Show("更新成功"); + GetInfo((int)comboBox1.SelectedValue); + } + else + { + MessageBox.Show("更新失败"); + } + } + catch (Exception ex) + { + MessageBox.Show($"更新失败,错误原因{ex.Message}"); + } + } + + private void 关闭_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void PLCADDRESS_Manage_Load(object sender, EventArgs e) + { + dataGridView1.AutoGenerateColumns = false; + SQLiteHelper sQLiteHelper1 = new db.SQLiteHelper(); + var result_combox = sQLiteHelper1.Query(a => a.id == Init.t_Line.plcid1 || a.id == Init.t_Line.plcid2); + if (!result_combox.Success) + { + MessageBox.Show("查询失败"); + return; + } + + // 绑定数据源到 ComboBox + comboBox1.DataSource = result_combox.Data; + comboBox1.DisplayMember = "name"; + comboBox1.ValueMember = "id"; + + var result1 = new List + { + new {name = "read",value = "read"}, + new {name = "write",value = "write"} + }; + + var result2 = new List + { + new {name = "real",value = "real"}, + new {name = "string",value = "string"}, + new {name = "uint",value = "uint"}, + }; + + var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[2]; + // 绑定数据源到 ComboBox + comboBoxColumn.DataSource = result1; + comboBoxColumn.DisplayMember = "name"; + comboBoxColumn.ValueMember = "value"; + + comboBoxColumn.DataPropertyName = "type"; + + var comboBoxColumn1 = (DataGridViewComboBoxColumn)dataGridView1.Columns[5]; + // 绑定数据源到 ComboBox + comboBoxColumn1.DataSource = result2; + comboBoxColumn1.DisplayMember = "name"; + comboBoxColumn1.ValueMember = "value"; + + comboBoxColumn1.DataPropertyName = "addresstype"; + + } + + public void GetInfo(int plcid) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.Query(a=>a.plcid == plcid); + if (result.Success) + { + dataGridView1.DataSource = null; + dataGridView1.DataSource = result.Data; + dataGridView1.Refresh(); + } + } + catch (Exception ex) + { + } + } + } +} diff --git a/WindowsFormsApp1/form/PLCADDRESS_Manage.resx b/WindowsFormsApp1/form/PLCADDRESS_Manage.resx new file mode 100644 index 0000000..480aacc --- /dev/null +++ b/WindowsFormsApp1/form/PLCADDRESS_Manage.resx @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/PLC_Manage.Designer.cs b/WindowsFormsApp1/form/PLC_Manage.Designer.cs new file mode 100644 index 0000000..36f378e --- /dev/null +++ b/WindowsFormsApp1/form/PLC_Manage.Designer.cs @@ -0,0 +1,196 @@ +namespace WindowsFormsApp1.form +{ + partial class PLC_Manage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); + this.关闭 = new System.Windows.Forms.Button(); + this.保存 = new System.Windows.Forms.Button(); + this.查询 = new System.Windows.Forms.Button(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.plcip = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.timeout = new System.Windows.Forms.DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // 关闭 + // + this.关闭.Anchor = System.Windows.Forms.AnchorStyles.None; + this.关闭.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.关闭.Location = new System.Drawing.Point(1743, 955); + this.关闭.Name = "关闭"; + this.关闭.Size = new System.Drawing.Size(92, 41); + this.关闭.TabIndex = 7; + this.关闭.Text = "关闭"; + this.关闭.UseVisualStyleBackColor = true; + this.关闭.Click += new System.EventHandler(this.关闭_Click); + // + // 保存 + // + this.保存.Anchor = System.Windows.Forms.AnchorStyles.None; + this.保存.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.保存.Location = new System.Drawing.Point(1743, 866); + this.保存.Name = "保存"; + this.保存.Size = new System.Drawing.Size(92, 41); + this.保存.TabIndex = 6; + this.保存.Text = "保存"; + this.保存.UseVisualStyleBackColor = true; + this.保存.Click += new System.EventHandler(this.保存_Click); + // + // 查询 + // + this.查询.Anchor = System.Windows.Forms.AnchorStyles.None; + this.查询.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.查询.Location = new System.Drawing.Point(1743, 22); + this.查询.Name = "查询"; + this.查询.Size = new System.Drawing.Size(92, 41); + this.查询.TabIndex = 5; + this.查询.Text = "查询"; + this.查询.UseVisualStyleBackColor = true; + this.查询.Click += new System.EventHandler(this.查询_Click); + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.id, + this.plcip, + this.timeout}); + dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3; + this.dataGridView1.Location = new System.Drawing.Point(3, 3); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersWidth = 72; + this.tableLayoutPanel1.SetRowSpan(this.dataGridView1, 4); + this.dataGridView1.RowTemplate.Height = 23; + this.dataGridView1.Size = new System.Drawing.Size(1689, 1015); + this.dataGridView1.TabIndex = 4; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.Controls.Add(this.关闭, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.保存, 1, 2); + this.tableLayoutPanel1.Controls.Add(this.查询, 1, 0); + this.tableLayoutPanel1.Location = new System.Drawing.Point(8, 8); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.20179F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 89.7982F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 87F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 90F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1884, 1021); + this.tableLayoutPanel1.TabIndex = 8; + // + // id + // + this.id.DataPropertyName = "id"; + this.id.HeaderText = "序号"; + this.id.MinimumWidth = 9; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Width = 175; + // + // plcip + // + this.plcip.DataPropertyName = "plcip"; + this.plcip.HeaderText = "IP地址"; + this.plcip.MinimumWidth = 9; + this.plcip.Name = "plcip"; + this.plcip.ReadOnly = true; + this.plcip.Width = 175; + // + // timeout + // + this.timeout.DataPropertyName = "timeout"; + this.timeout.HeaderText = "超时时间"; + this.timeout.MinimumWidth = 9; + this.timeout.Name = "timeout"; + this.timeout.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.timeout.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; + this.timeout.Width = 175; + // + // PLC_Manage + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1904, 1041); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Margin = new System.Windows.Forms.Padding(2); + this.Name = "PLC_Manage"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "PLC_Manage"; + this.Load += new System.EventHandler(this.PLC_Manage_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.tableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button 关闭; + private System.Windows.Forms.Button 保存; + private System.Windows.Forms.Button 查询; + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.DataGridViewTextBoxColumn id; + private System.Windows.Forms.DataGridViewTextBoxColumn plcip; + private System.Windows.Forms.DataGridViewTextBoxColumn timeout; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/PLC_Manage.cs b/WindowsFormsApp1/form/PLC_Manage.cs new file mode 100644 index 0000000..795d8ff --- /dev/null +++ b/WindowsFormsApp1/form/PLC_Manage.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; + +namespace WindowsFormsApp1.form +{ + public partial class PLC_Manage : Form + { + public PLC_Manage() + { + InitializeComponent(); + } + + private void 查询_Click(object sender, EventArgs e) + { + GetInfo(); + } + + private void 保存_Click(object sender, EventArgs e) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.UpdateAll((List)dataGridView1.DataSource); + if (result.Success) + { + MessageBox.Show("更新成功"); + GetInfo(); + } + else + { + MessageBox.Show("更新失败"); + } + } + catch (Exception ex) + { + MessageBox.Show($"更新失败,错误原因{ex.Message}"); + } + } + + private void 关闭_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void PLC_Manage_Load(object sender, EventArgs e) + { + dataGridView1.AutoGenerateColumns = false; + GetInfo(); + } + + public void GetInfo() + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.Query(a=> a.id == Init.t_Line.plcid1 || a.id == Init.t_Line.plcid2); + if (result.Success) + { + dataGridView1.DataSource = null; + dataGridView1.DataSource = result.Data; + dataGridView1.Refresh(); + } + } + catch (Exception ex) + { + } + } + } +} diff --git a/WindowsFormsApp1/form/PLC_Manage.resx b/WindowsFormsApp1/form/PLC_Manage.resx new file mode 100644 index 0000000..b121660 --- /dev/null +++ b/WindowsFormsApp1/form/PLC_Manage.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/USER_ChangeP.Designer.cs b/WindowsFormsApp1/form/USER_ChangeP.Designer.cs new file mode 100644 index 0000000..fc25646 --- /dev/null +++ b/WindowsFormsApp1/form/USER_ChangeP.Designer.cs @@ -0,0 +1,157 @@ +namespace WindowsFormsApp1.form +{ + partial class USER_ChangeP + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.textBox3 = new System.Windows.Forms.TextBox(); + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.groupBox1.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.label3); + this.groupBox1.Controls.Add(this.label2); + this.groupBox1.Controls.Add(this.label1); + this.groupBox1.Controls.Add(this.button2); + this.groupBox1.Controls.Add(this.button1); + this.groupBox1.Controls.Add(this.textBox3); + this.groupBox1.Controls.Add(this.textBox2); + this.groupBox1.Controls.Add(this.textBox1); + this.groupBox1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox1.Location = new System.Drawing.Point(25, 28); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(351, 268); + this.groupBox1.TabIndex = 0; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "修改密码"; + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(105, 45); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(201, 26); + this.textBox1.TabIndex = 0; + // + // textBox2 + // + this.textBox2.Location = new System.Drawing.Point(105, 94); + this.textBox2.Name = "textBox2"; + this.textBox2.Size = new System.Drawing.Size(201, 26); + this.textBox2.TabIndex = 1; + // + // textBox3 + // + this.textBox3.Location = new System.Drawing.Point(105, 146); + this.textBox3.Name = "textBox3"; + this.textBox3.Size = new System.Drawing.Size(201, 26); + this.textBox3.TabIndex = 2; + // + // button1 + // + this.button1.Location = new System.Drawing.Point(35, 213); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(100, 40); + this.button1.TabIndex = 3; + this.button1.Text = "修改密码"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // button2 + // + this.button2.Location = new System.Drawing.Point(216, 213); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(100, 40); + this.button2.TabIndex = 4; + this.button2.Text = "关闭"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(17, 45); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(55, 16); + this.label1.TabIndex = 5; + this.label1.Text = "原密码"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(17, 104); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(55, 16); + this.label2.TabIndex = 6; + this.label2.Text = "新密码"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(17, 156); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(55, 16); + this.label3.TabIndex = 7; + this.label3.Text = "新密码"; + // + // USER_ChangeP + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(404, 320); + this.Controls.Add(this.groupBox1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Name = "USER_ChangeP"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "USER_ChangeP"; + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TextBox textBox3; + private System.Windows.Forms.TextBox textBox2; + private System.Windows.Forms.TextBox textBox1; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/USER_ChangeP.cs b/WindowsFormsApp1/form/USER_ChangeP.cs new file mode 100644 index 0000000..c414afc --- /dev/null +++ b/WindowsFormsApp1/form/USER_ChangeP.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace WindowsFormsApp1.form +{ + public partial class USER_ChangeP : Form + { + public USER_ChangeP() + { + InitializeComponent(); + } + + private void button2_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void button1_Click(object sender, EventArgs e) + { + + } + } +} diff --git a/WindowsFormsApp1/form/USER_ChangeP.resx b/WindowsFormsApp1/form/USER_ChangeP.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/WindowsFormsApp1/form/USER_ChangeP.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/USER_Manage.Designer.cs b/WindowsFormsApp1/form/USER_Manage.Designer.cs new file mode 100644 index 0000000..ffa3046 --- /dev/null +++ b/WindowsFormsApp1/form/USER_Manage.Designer.cs @@ -0,0 +1,188 @@ +namespace WindowsFormsApp1 +{ + partial class USER_Manage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.查询 = new System.Windows.Forms.Button(); + this.保存 = new System.Windows.Forms.Button(); + this.关闭 = new System.Windows.Forms.Button(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.username = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.password = new System.Windows.Forms.DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // dataGridView1 + // + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.id, + this.username, + this.password}); + dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle3; + this.dataGridView1.Location = new System.Drawing.Point(3, 3); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersWidth = 72; + this.tableLayoutPanel1.SetRowSpan(this.dataGridView1, 4); + this.dataGridView1.RowTemplate.Height = 23; + this.dataGridView1.Size = new System.Drawing.Size(1685, 1011); + this.dataGridView1.TabIndex = 0; + // + // 查询 + // + this.查询.Anchor = System.Windows.Forms.AnchorStyles.None; + this.查询.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.查询.Location = new System.Drawing.Point(1739, 34); + this.查询.Name = "查询"; + this.查询.Size = new System.Drawing.Size(92, 41); + this.查询.TabIndex = 1; + this.查询.Text = "查询"; + this.查询.UseVisualStyleBackColor = true; + this.查询.Click += new System.EventHandler(this.查询_Click); + // + // 保存 + // + this.保存.Anchor = System.Windows.Forms.AnchorStyles.None; + this.保存.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.保存.Location = new System.Drawing.Point(1739, 861); + this.保存.Name = "保存"; + this.保存.Size = new System.Drawing.Size(92, 41); + this.保存.TabIndex = 2; + this.保存.Text = "保存"; + this.保存.UseVisualStyleBackColor = true; + this.保存.Click += new System.EventHandler(this.保存_Click); + // + // 关闭 + // + this.关闭.Anchor = System.Windows.Forms.AnchorStyles.None; + this.关闭.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.关闭.Location = new System.Drawing.Point(1739, 952); + this.关闭.Name = "关闭"; + this.关闭.Size = new System.Drawing.Size(92, 41); + this.关闭.TabIndex = 3; + this.关闭.Text = "关闭"; + this.关闭.UseVisualStyleBackColor = true; + this.关闭.Click += new System.EventHandler(this.关闭_Click); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel1.Controls.Add(this.关闭, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.保存, 1, 2); + this.tableLayoutPanel1.Controls.Add(this.查询, 1, 0); + this.tableLayoutPanel1.Location = new System.Drawing.Point(13, 12); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 13.08411F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 86.91589F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 94F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 87F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(1879, 1017); + this.tableLayoutPanel1.TabIndex = 4; + // + // id + // + this.id.DataPropertyName = "id"; + this.id.HeaderText = "序号"; + this.id.MinimumWidth = 9; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Width = 175; + // + // username + // + this.username.DataPropertyName = "username"; + this.username.HeaderText = "用户名"; + this.username.MinimumWidth = 9; + this.username.Name = "username"; + this.username.Width = 175; + // + // password + // + this.password.DataPropertyName = "password"; + this.password.HeaderText = "密码"; + this.password.MinimumWidth = 9; + this.password.Name = "password"; + this.password.Width = 175; + // + // USER_Manage + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1904, 1041); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Name = "USER_Manage"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "USER_Manage"; + this.Load += new System.EventHandler(this.USER_Manage_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.tableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.Button 查询; + private System.Windows.Forms.Button 保存; + private System.Windows.Forms.Button 关闭; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.DataGridViewTextBoxColumn id; + private System.Windows.Forms.DataGridViewTextBoxColumn username; + private System.Windows.Forms.DataGridViewTextBoxColumn password; + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/USER_Manage.cs b/WindowsFormsApp1/form/USER_Manage.cs new file mode 100644 index 0000000..9523c50 --- /dev/null +++ b/WindowsFormsApp1/form/USER_Manage.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using WindowsFormsApp1.db; +using WindowsFormsApp1.mod; + +namespace WindowsFormsApp1 +{ + public partial class USER_Manage : Form + { + public USER_Manage() + { + InitializeComponent(); + } + + private void 查询_Click(object sender, EventArgs e) + { + GetInfo(); + } + + private void 保存_Click(object sender, EventArgs e) + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.UpdateAll((List)dataGridView1.DataSource); + if (result.Success) + { + var qureuser = sQLiteHelper.QuerySingle(a => a.id == Init.t_User.id); + if (!qureuser.Success) + { + MessageBox.Show("更新失败"); + return; + } + else + { + Init.t_User = qureuser.Data; + MessageBox.Show("更新成功"); + GetInfo(); + } + } + else + { + MessageBox.Show("更新失败"); + } + + } + catch (Exception ex) + { + MessageBox.Show($"更新失败,错误原因{ex.Message}"); + } + } + + private void 关闭_Click(object sender, EventArgs e) + { + this.Close(); + } + + public void GetInfo() + { + try + { + SQLiteHelper sQLiteHelper = new db.SQLiteHelper(); + var result = sQLiteHelper.QueryAll(); + if (result.Success) + { + dataGridView1.DataSource = null; + dataGridView1.DataSource = result.Data; + dataGridView1.Refresh(); + } + } + catch (Exception ex) + { + } + } + + private void USER_Manage_Load(object sender, EventArgs e) + { + dataGridView1.AutoGenerateColumns = false; + GetInfo(); + } + } +} diff --git a/WindowsFormsApp1/form/USER_Manage.resx b/WindowsFormsApp1/form/USER_Manage.resx new file mode 100644 index 0000000..18287e6 --- /dev/null +++ b/WindowsFormsApp1/form/USER_Manage.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/WindowsFormsApp1/mod/database/t_flow.cs b/WindowsFormsApp1/mod/database/t_flow.cs new file mode 100644 index 0000000..b5daa6f --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_flow.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite; + +namespace WindowsFormsApp1.mod +{ + [Table("flow")] + public class t_flow + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public int flowid { get; set; } + public int setp { get; set; } + public int hopeinterfaceid { get; set; } + public int errinterfaceid { get; set; } + public int hopestatus { get; set; } + public int errstatus { get; set; } + + } +} diff --git a/WindowsFormsApp1/mod/database/t_interface.cs b/WindowsFormsApp1/mod/database/t_interface.cs new file mode 100644 index 0000000..4625d74 --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_interface.cs @@ -0,0 +1,17 @@ + + +using SQLite; + +namespace WindowsFormsApp1.mod +{ + [Table("interface")] + public class t_interface + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public string name { get; set; } + public string code { get; set; } + public string url { get; set; } + public string remark { get; set; } + } +} diff --git a/WindowsFormsApp1/mod/database/t_line.cs b/WindowsFormsApp1/mod/database/t_line.cs new file mode 100644 index 0000000..dd7e4a3 --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_line.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite; + +namespace WindowsFormsApp1.mod +{ + [Table("line")] + public class t_line + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public string linename { get; set; } + public string linecode { get; set; } + public string linetype { get; set; } + public string linemode { get; set; } + public int plcid1 { get; set; } + public int plcid2 { get; set; } + public int flowid { get; set; } + + + } +} diff --git a/WindowsFormsApp1/mod/database/t_plc.cs b/WindowsFormsApp1/mod/database/t_plc.cs new file mode 100644 index 0000000..a0fe9e6 --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_plc.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite; +using WindowsFormsApp1.server; + +namespace WindowsFormsApp1.mod +{ + [Table("plc")] + public class t_plc + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public string plcip { get; set; } + public int timeout { get; set; } + + [Ignore] + public DateTime dateTime { get; set; } + [Ignore] + public SiemensHelp plchelp { get; set; } + } +} diff --git a/WindowsFormsApp1/mod/database/t_plcaddress.cs b/WindowsFormsApp1/mod/database/t_plcaddress.cs new file mode 100644 index 0000000..3114938 --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_plcaddress.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite; + +namespace WindowsFormsApp1.mod +{ + [Table("plcaddress")] + public class t_plcaddress + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public int plcid { get; set; } + public string type { get; set; } + public string dbaddress { get; set; } + public string addresstype { get; set; } + public int addresstypelegth { get; set; } + public int addressoffset { get; set; } + public string remark { get; set; } + public string value { get; set; } + + + } +} diff --git a/WindowsFormsApp1/mod/database/t_user.cs b/WindowsFormsApp1/mod/database/t_user.cs new file mode 100644 index 0000000..a0a1085 --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_user.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite; + +namespace WindowsFormsApp1.mod +{ + [Table("user")] + public class t_user + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public string username { get; set; } + public string password { get; set; } + } +} diff --git a/WindowsFormsApp1/packages.config b/WindowsFormsApp1/packages.config new file mode 100644 index 0000000..0008a19 --- /dev/null +++ b/WindowsFormsApp1/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/WindowsFormsApp1/server/ApiClient.cs b/WindowsFormsApp1/server/ApiClient.cs new file mode 100644 index 0000000..8c1a9dc --- /dev/null +++ b/WindowsFormsApp1/server/ApiClient.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; + +namespace WindowsFormsApp1.server +{ + public class ApiClient + { + public BllResult SN_CheckIN() + { + return BllResult.Sucess(); + } + public BllResult Carrier_Check() + { + return BllResult.Sucess(); + } + public BllResult SN_FeedingCheck() + { + return BllResult.Sucess(); + } + public BllResult Link_Comp() + { + return BllResult.Sucess(); + } + public BllResult SN_Release() + { + return BllResult.Sucess(); + } + public BllResult Glue_CheckOut() + { + return BllResult.Sucess(); + } + public BllResult Get_Para() + { + return BllResult.Sucess(); + } + public BllResult DispatchPara() + { + return BllResult.Sucess(); + } + public BllResult Data_Collection() + { + return BllResult.Sucess(); + } + public BllResult Status() + { + return BllResult.Sucess(); + } + public BllResult Alarm() + { + return BllResult.Sucess(); + } + public BllResult OEEDataCollection() + { + return BllResult.Sucess(); + } + public BllResult SN_FileUpload() + { + return BllResult.Sucess(); + } + public BllResult Test() + { + return BllResult.Sucess(); + } + public BllResult SN_Checkout() + { + return BllResult.Sucess(); + } + public BllResult Initialization() + { + //1.获取PLC参数,扫码器参数 + + //2、调用接口 + + //3.给PLC的 writeaddress赋值 + + return BllResult.Sucess("Initialization"); + } + + public BllResult CallFunctionByName(string functionName) + { + // 获取当前类的类型 + Type type = this.GetType(); + + // 使用反射调用指定名称的方法 + MethodInfo methodInfo = type.GetMethod(functionName); + + if (methodInfo != null) + { + // 调用该方法 + return (BllResult)methodInfo.Invoke(this, null); + } + else + { + Console.WriteLine($"Method '{functionName}' not found."); + return BllResult.Error(); + } + } + } +} diff --git a/WindowsFormsApp1/server/BllResult.cs b/WindowsFormsApp1/server/BllResult.cs new file mode 100644 index 0000000..77de056 --- /dev/null +++ b/WindowsFormsApp1/server/BllResult.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WindowsFormsApp1.server +{ + public class BllResult + { + public BllResult(bool success, string msg, T data) + { + Success = success; + Msg = msg; + Data = data; + } + + public bool Success { get; set; } + public string Msg { get; set; } + public T Data { get; set; } + + public static BllResult Sucess(T data, String msg) + { + return new BllResult(true, msg, data); + } + + public static BllResult Sucess(T data) + { + return new BllResult(true, "", data); + } + + public static BllResult Sucess(String msg) + { + return new BllResult(true, msg, default(T)); + } + + public static BllResult Sucess() + { + return new BllResult(true, "", default(T)); + } + + public static BllResult Error(T data, String msg) + { + return new BllResult(false, msg, data); + } + + public static BllResult Error(T data) + { + return new BllResult(false, "", data); + } + + public static BllResult Error(String msg) + { + return new BllResult(false, msg, default(T)); + } + + public static BllResult Error() + { + return new BllResult(false, "", default(T)); + } + } + + public class BllResult + { + private BllResult(bool success, string msg, object data) + { + Success = success; + Msg = msg; + Data = data; + } + + public bool Success { get; set; } + public string Msg { get; set; } + public object Data { get; set; } + + public static BllResult Sucess(Object data, String msg) + { + return new BllResult(true, msg, data); + } + + public static BllResult Sucess(Object data) + { + return new BllResult(true, "", data); + } + + public static BllResult Sucess(String msg) + { + return new BllResult(true, msg, null); + } + + public static BllResult Sucess() + { + return new BllResult(true, "", null); + } + + public static BllResult Error(object data, String msg) + { + return new BllResult(false, msg, data); + } + + public static BllResult Error(object data) + { + return new BllResult(false, "", data); + } + + public static BllResult Error(String msg) + { + return new BllResult(false, msg, null); + } + + public static BllResult Error() + { + return new BllResult(false, "", null); + } + } +} diff --git a/WindowsFormsApp1/server/LogExecute.cs b/WindowsFormsApp1/server/LogExecute.cs new file mode 100644 index 0000000..6ac7425 --- /dev/null +++ b/WindowsFormsApp1/server/LogExecute.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using HslCommunication.LogNet; + +namespace WindowsFormsApp1.server +{ + public class LogExecute + { + public static ILogNet logNet = new LogNetDateTime("C:\\Log\\Logs", GenerateMode.ByEveryDay); + public static ILogNet PlclogNet = new LogNetDateTime("C:\\Log\\PlcLogs", GenerateMode.ByEveryDay); + public static ILogNet ApilogNet = new LogNetDateTime("C:\\Log\\Apilogs", GenerateMode.ByEveryHour); + public static HslCommunication.BasicFramework.SoftNumericalOrder softNumericalOrder = new HslCommunication.BasicFramework.SoftNumericalOrder("", "yyyyMMdd", 4, @"\numericalOrder.txt"); + + public LogExecute() + { + #region 日志 + + //设置日志发布等级及触发时间 + //logNet.SetMessageDegree(HslMessageDegree.INFO);//除DEBUG外,都存储 + + #endregion 日志 + } + } +} diff --git a/WindowsFormsApp1/server/SiemensHelp.cs b/WindowsFormsApp1/server/SiemensHelp.cs new file mode 100644 index 0000000..fd14360 --- /dev/null +++ b/WindowsFormsApp1/server/SiemensHelp.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using HslCommunication.Profinet.Siemens; +using HslCommunication; +using WindowsFormsApp1.mod; + +namespace WindowsFormsApp1.server +{ + public class SiemensHelp + { + private HslCommunication.Core.IByteTransform ByteTransform = new HslCommunication.Core.ReverseBytesTransform(); + private SiemensS7Net siemensS7Net; + private string ip; + private int timeout; + private static bool ConnectB = false; + public SiemensHelp(string ip,int timeout) + { + this.ip = ip; + this.timeout = timeout; + siemensS7Net = new SiemensS7Net(SiemensPLCS.S1500, ip) { ConnectTimeOut = timeout, ReceiveTimeOut = timeout }; + } + + /// + /// 打开S7 Net长连接 + /// + /// + public BllResult OpenConn() + { + try + { + if (!ConnectB) + { + OperateResult connect = siemensS7Net.ConnectServer(); + if (!connect.IsSuccess) + { + return BllResult.Error(connect.Message); + } + else + { + ConnectB = true; + return BllResult.Sucess(); + } + } + else + { + return BllResult.Sucess(); + } + } + catch (Exception ex) + { + return BllResult.Error(ex); + } + } + + /// + /// 关闭S7 Net长连接 + /// + /// + public BllResult CloseConn() + { + try + { + if (ConnectB) + { + OperateResult connect = siemensS7Net.ConnectClose(); + if (connect.IsSuccess) + { + ConnectB = false; + return BllResult.Sucess(); + } + else + { + return BllResult.Error(connect.Message); + } + } + else + { + return BllResult.Sucess(); + } + } + catch (Exception ex) + { + return BllResult.Error(ex); + } + } + + private BllResult ReadOneDB(List address) + { + address = address.OrderBy(a => a.addressoffset).ToList(); + OperateResult read; + if (address.Count == 1) + { + string startaddress = address[0].dbaddress + "." + address[0].addressoffset.ToString(); + read = siemensS7Net.Read(startaddress, Convert.ToUInt16(address[0].addresstypelegth)); + } + else + { + double admax = address.Select(a => a.addressoffset).Max(); + double admin = address.Select(a => a.addressoffset).Min(); + ushort length = (ushort)(Math.Floor(admax - admin) + address.Last().addresstypelegth); + string startaddress = address[0].dbaddress + "." + admin.ToString(); + read = siemensS7Net.Read(startaddress, length); + } + if (read.IsSuccess) + { + if (TransforWCSDataToAddressData(address, read).Success) + { + return BllResult.Sucess(address, "成功"); + } + else + { + return BllResult.Sucess(address, "成功"); + } + } + else + { + return BllResult.Error(read.Message); + } + } + + public BllResult ReadAddress(List address) + { + var ulist = address.GroupBy(a => a.dbaddress).ToList(); + foreach (var u in ulist) + { + var readresult = ReadOneDB(u.ToList()); + if (!readresult.Success) + { + return BllResult.Error(readresult.Msg); + } + } + return BllResult.Sucess(address, "成功"); + } + + private BllResult WriteOneDB(List address) + { + address = address.OrderBy(a => a.addressoffset).ToList(); + string startaddress = address[0].dbaddress + "." + address[0].addressoffset.ToString(); + BllResult bllResult = TransforAddressDataToWCSData(address); + if (bllResult.Success) + { + OperateResult operate = siemensS7Net.Write(startaddress, (byte[])bllResult.Data); + if (operate.IsSuccess) + { + return BllResult.Sucess(); + } + else + { + return BllResult.Error(operate.Message); + } + } + else + { + return BllResult.Error(bllResult.Msg); + } + } + + public BllResult WriteAddress(List address) + { + var ulist = address.GroupBy(a => a.dbaddress).ToList(); + foreach (var u in ulist) + { + var readresult = WriteOneDB(u.ToList()); + if (!readresult.Success) + { + return BllResult.Error(readresult.Msg); + } + } + return BllResult.Sucess(address, "成功"); + } + + private BllResult TransforWCSDataToAddressData(List address, OperateResult read) + { + try + { + //按偏移量排序 + address = address.OrderBy(a => a.addressoffset).ToList(); + int startindex = address[0].addressoffset; + for (int i = 0; i < address.Count; i++) + { + int index = address[i].addressoffset - startindex; + switch (address[i].type) + { + case "byte": + address[i].value = ByteTransform.TransByte(read.Content, index).ToString(); + break; + + case "real": + address[i].value = ByteTransform.TransSingle(read.Content, index).ToString(); + break; + + case "lword": + address[i].value = Convert.ToString(ByteTransform.TransInt64(read.Content, index), 16); ; + break; + + case "int": + address[i].value = ByteTransform.TransInt16(read.Content, index).ToString(); + break; + + case "uint": + address[i].value = BitConverter.ToUInt16(read.Content, index).ToString(); + break; + + case "dint": + address[i].value = Convert.ToString(ByteTransform.TransInt32(read.Content, index), 10); + break; + + case "string": + address[i].value = Encoding.ASCII.GetString(read.Content, index, address[i].addresstypelegth).Replace(" ", "").Replace("\0", "").Replace("\u0003", ""); + break; + + default: + return BllResult.Error("找不到未知的数据类型"); + } + } + return BllResult.Sucess(address); + } + catch (Exception ex) + { + return BllResult.Error($"转换WCS数据失败{ex.Message}"); + } + } + + private BllResult TransforAddressDataToWCSData(List address) //返回一个byte[] + { + try + { + address = address.OrderBy(a => a.addressoffset).ToList(); + double admax = address.Select(a => a.addressoffset).Max(); + double admin = address.Select(a => a.addressoffset).Min(); + ushort length = (ushort)(Math.Floor(admax - admin) + address.Last().addresstypelegth); + int startindex = address[0].addressoffset; + byte[] writebyte = new byte[length]; + for (int i = 0; i < address.Count; i++) + { + int index = address[i].addressoffset - startindex; + object value = address[i].value; + switch (address[i].addresstype) + { + case "byte": + byte tobyte = Convert.ToByte(value); + ByteTransform.TransByte(tobyte).CopyTo(writebyte, index); + break; + + case "lword": + if ((string)value == "") value = null; + long tolong = Convert.ToInt64((string)value, 16); + ByteTransform.TransByte(tolong).CopyTo(writebyte, index); + break; + + case "int": + short toint = Convert.ToInt16(value); + ByteTransform.TransByte(toint).CopyTo(writebyte, index); + break; + + case "uint": + ushort touint = Convert.ToUInt16(value); + ByteTransform.TransByte(touint).CopyTo(writebyte, index); + break; + + case "dint": + int todint = Convert.ToInt32(value); + ByteTransform.TransByte(todint).CopyTo(writebyte, index); + break; + + case "read": + float todreal = Convert.ToSingle(value); + ByteTransform.TransByte(todreal).CopyTo(writebyte, index); + break; + + case "string": + byte[] tochar = Encoding.ASCII.GetBytes(((string)value).PadRight(address[i].addresstypelegth, ' ')); + tochar.CopyTo(writebyte, index); + break; + + default: + return BllResult.Error("找不到未知的数据类型"); + } + } + return BllResult.Sucess(writebyte); + } + catch (Exception ex) + { + return BllResult.Error($"转换WCS数据失败{ex.Message}"); + } + } + } +}